Skip to content

Instantly share code, notes, and snippets.

@hguochen
Created July 22, 2016 03:59
Show Gist options
  • Save hguochen/9323ab422106021cc8aae5204e899b50 to your computer and use it in GitHub Desktop.
Save hguochen/9323ab422106021cc8aae5204e899b50 to your computer and use it in GitHub Desktop.
collapseOperation
// get a collapsed operations array
private function collapseOperations($operations) {
// setup a glossary of operations categorized by name
$glossary = parseOperationsByName($operations);
// serialize leftover operations
$result = [];
foreach ($glossary as $operation) {
$result = array_merge($result, $operation);
}
return $result;
}
// get a glossary array in the following format:
// $glossary = [
// '<operation name>' => [
// <operation array 1>,
// <operation array 2>,
// ]
// ]
private function parseOperationsByName($operations) {
$glossary = [];
$matchingOperations = [
'add' => 'remove',
'remove' => 'add'
];
foreach ($operations as $operation) {
// if operation name already exists, check details. else add operation with operation name as key
if (array_key_exists($operation['name'], $glossary)) {
foreach ($glossary[$operation['name']] as $key => $op) {
// remove matching operations for this operation name, otherwise add the operation to array
if (array_key_exists($operation['op'], $matchingOperations) &&
$matchingOperations[$operation['op']] === $op['op']) {
unset($glossary[$operation['name']][$key]);
} else {
// is not a matching operation, push into array
array_push($glossary[$operation['name']], $op);
}
// remove names with empty operations
if (empty($glossary[$operation['name']])) {
unset($glossary[$operation['name']]);
}
}
} else {
$glossary[$operation['name']] = array($operation);
}
}
return $glossary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment