Skip to content

Instantly share code, notes, and snippets.

@angry-dan
Created April 26, 2017 09:29
Show Gist options
  • Save angry-dan/d3ad9ef298db9c8e59e8efa653cd9ef0 to your computer and use it in GitHub Desktop.
Save angry-dan/d3ad9ef298db9c8e59e8efa653cd9ef0 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment