Skip to content

Instantly share code, notes, and snippets.

@angry-dan
Last active April 26, 2017 09:30
Show Gist options
  • Save angry-dan/7760a82345143120866c95fff6596353 to your computer and use it in GitHub Desktop.
Save angry-dan/7760a82345143120866c95fff6596353 to your computer and use it in GitHub Desktop.
A function that executes a list of functions, gathering necessary dependencies as it goes.
<?php
public static function callFunctionDependencyTree($functions) {
do {
$funcDidExecute = FALSE;
$functions = array_map(function ($spec) use ($functions, &$funcDidExecute) {
if (array_key_exists('value', $spec)) {
return $spec;
}
$funcCanExecute = TRUE;
$args = [];
foreach ($spec['deps'] as $i => $dep) {
if (!array_key_exists('value', $functions[$dep])) {
$funcCanExecute = FALSE;
break;
}
$args[$i] = $functions[$dep]['value'];
}
if ($funcCanExecute) {
$funcDidExecute = TRUE;
if (!is_callable($spec['func'])) {
trigger_error('not callable');
}
return $spec + ['value' => call_user_func_array($spec['func'], $args)];
}
return $spec;
}, $functions);
} while ($funcDidExecute);
$values = array_map(function ($f) {
return isset($f['value']) ? $f['value'] : (isset($f['default']) ? $f['default'] : NULL);
}, $functions);
return $values;
}
<?php
$values = executeInOrder([
'thing0' => [
'deps' => [],
'func' => function () {
return 1;
},
],
'thing1' => [
'deps' => ['thing0'],
'func' => function ($thing) {
return $thing + 1;
},
],
'thing2' => [
'deps' => ['thing0', 'thing1'],
'func' => function ($thing0, $thing1) {
assert($thing0 + $thing1 === 3, '1 + 2 = 3');
return 3;
},
],
'somethingbad' => [
'deps' => ['somethingbad'],
'default' => 'answer',
],
'withoutadefault' => [
'deps' => ['somethingbad'],
],
'withadefault' => [
'deps' => ['somethingbad'],
'default' => 12.344,
],
]);
@angry-dan
Copy link
Author

The default thing should probably go. It shouldn't be used under any normal circumstance. Either that or allow some kind of pattern to return the default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment