Skip to content

Instantly share code, notes, and snippets.

@slifin
Created April 28, 2020 20:15
Show Gist options
  • Select an option

  • Save slifin/1afeff6b815896d239d739602bb53094 to your computer and use it in GitHub Desktop.

Select an option

Save slifin/1afeff6b815896d239d739602bb53094 to your computer and use it in GitHub Desktop.
dispatch on function signatures
<?php
class B {
public static function A(int $a, int $b = NULL) {
}
public static function C(int $a) {
return 2;
}
}
function dispatcher(array $callables, $input) {
$scores = [];
foreach ($callables as $callable) {
$match = $callable['dispatch'];
try {
$match(...$input);
$score = count((new ReflectionMethod(...$match))->getParameters());
$scores[$score] = $callable['invoke'] ?? $match;
}
catch (Throwable $e) {
}
}
krsort($scores);
foreach ($scores as $invoke) {
return $invoke(...$input);
}
throw $e;
}
var_dump(
dispatcher(
[
['dispatch' => ['B', 'C']],
['dispatch' => ['B', 'A']],
],
[3]
)
);
@slifin
Copy link
Copy Markdown
Author

slifin commented Apr 28, 2020

(method dispatcher)

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