CallableReflection.php
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace Smashballoon\TwitterFeed\Vendor\Invoker\Reflection; |
| 5 | |
| 6 | use Closure; |
| 7 | use Smashballoon\TwitterFeed\Vendor\Invoker\Exception\NotCallableException; |
| 8 | use ReflectionException; |
| 9 | use ReflectionFunction; |
| 10 | use ReflectionFunctionAbstract; |
| 11 | use ReflectionMethod; |
| 12 | /** |
| 13 | * Create a reflection object from a callable or a callable-like. |
| 14 | * |
| 15 | * @internal |
| 16 | */ |
| 17 | class CallableReflection |
| 18 | { |
| 19 | /** |
| 20 | * @param callable|array|string $callable Can be a callable or a callable-like. |
| 21 | * @throws NotCallableException|ReflectionException |
| 22 | */ |
| 23 | public static function create($callable): ReflectionFunctionAbstract |
| 24 | { |
| 25 | // Closure |
| 26 | if ($callable instanceof Closure) { |
| 27 | return new ReflectionFunction($callable); |
| 28 | } |
| 29 | // Array callable |
| 30 | if (is_array($callable)) { |
| 31 | [$class, $method] = $callable; |
| 32 | if (!method_exists($class, $method)) { |
| 33 | throw NotCallableException::fromInvalidCallable($callable); |
| 34 | } |
| 35 | return new ReflectionMethod($class, $method); |
| 36 | } |
| 37 | // Callable object (i.e. implementing __invoke()) |
| 38 | if (is_object($callable) && method_exists($callable, '__invoke')) { |
| 39 | return new ReflectionMethod($callable, '__invoke'); |
| 40 | } |
| 41 | // Standard function |
| 42 | if (is_string($callable) && function_exists($callable)) { |
| 43 | return new ReflectionFunction($callable); |
| 44 | } |
| 45 | throw new NotCallableException(sprintf('%s is not a callable', is_string($callable) ? $callable : 'Instance of ' . get_class($callable))); |
| 46 | } |
| 47 | } |
| 48 |