Last active
April 26, 2017 09:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, | |
], | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.