Skip to content

Instantly share code, notes, and snippets.

@slifin
Created August 24, 2020 12:51
Show Gist options
  • Save slifin/9a2fa6eacb99fa26c3e6f0748e914e8d to your computer and use it in GitHub Desktop.
Save slifin/9a2fa6eacb99fa26c3e6f0748e914e8d to your computer and use it in GitHub Desktop.
<?php
class B {
public static function A(int $a, int $b = NULL) {
return 5;
}
public static function C(int $a, string $hey) {
return 2;
}
}
function argument_list(callable $callable, $input) : array {
$params = (new ReflectionMethod(...$callable))->getParameters();
$args = [];
$i = 0;
foreach ($params as $param) {
$name = $param->getName();
if (isset($input[$i])) {
$args[$i] = $input[$i];
}
elseif (isset($input[$name])) {
$args[$i] = $input[$name];
}
$i++;
}
return $args;
}
function dispatcher(array $callables, $input) {
foreach ($callables as $callable) {
$call = $callable['dispatch'] ?? $callable;
$args = argument_list($call, $input);
try {
$match(...$args);
$scores[$score] = $callable['invoke'] ?? $call;
}
catch (Throwable $e) {
}
}
krsort($scores);
foreach ($scores as $invoke) {
return $invoke(...$input);
}
throw $e;
}
var_dump(
dispatcher(
[
['dispatch' => ['B', 'C']],
['dispatch' => ['B', 'A']],
],
[2, 'hey' => 3]
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment