Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

87 строки
2.2KB

  1. <?php
  2. declare(strict_types=1);
  3. namespace Core;
  4. use Exception;
  5. use ReflectionFunction;
  6. use ReflectionMethod;
  7. class App
  8. {
  9. protected array $bindings = [];
  10. public function bind(string $name, mixed $value): void
  11. {
  12. $this->bindings[$name] = $value;
  13. }
  14. public function get(string $name): mixed
  15. {
  16. return $this->bindings[$name] ?? null;
  17. }
  18. public function call(callable|array|string $handler, array $parameters = []): mixed
  19. {
  20. if (is_array($handler)) {
  21. return $this->callMethod($handler, $parameters);
  22. }
  23. if (is_callable($handler)) {
  24. return $this->callFunction($handler, $parameters);
  25. }
  26. throw new Exception('Invalid handler.');
  27. }
  28. protected function callFunction(callable $handler, array $parameters): mixed
  29. {
  30. $reflection = new ReflectionFunction($handler);
  31. return $reflection->invokeArgs($this->resolveArgs($reflection, $parameters));
  32. }
  33. protected function callMethod(array $handler, array $parameters): mixed
  34. {
  35. [$class, $method] = $handler;
  36. if (is_string($class)) {
  37. $class = new $class();
  38. }
  39. $reflection = new ReflectionMethod($class, $method);
  40. return $reflection->invokeArgs($class, $this->resolveArgs($reflection, $parameters));
  41. }
  42. protected function resolveArgs(\ReflectionFunctionAbstract $reflection, array $parameters): array
  43. {
  44. $args = [];
  45. foreach ($reflection->getParameters() as $param) {
  46. $name = $param->getName();
  47. if (array_key_exists($name, $parameters)) {
  48. $args[] = $parameters[$name];
  49. continue;
  50. }
  51. $type = $param->getType();
  52. if ($type instanceof \ReflectionNamedType && !$type->isBuiltin()) {
  53. $typeName = $type->getName();
  54. if (array_key_exists($typeName, $this->bindings)) {
  55. $args[] = $this->bindings[$typeName];
  56. continue;
  57. }
  58. }
  59. $args[] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
  60. }
  61. return $args;
  62. }
  63. }

Powered by TurnKey Linux.