Created
April 28, 2020 20:15
-
-
Save slifin/1afeff6b815896d239d739602bb53094 to your computer and use it in GitHub Desktop.
dispatch on function signatures
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 | |
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] | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(method dispatcher)