Reflection.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Utils;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. /**
  6. * Class Reflection : Gestion des réflection de class.
  7. */
  8. class Reflection
  9. {
  10. public function __construct(readonly private ContainerInterface $container)
  11. {
  12. }
  13. /**
  14. * Appelle une fonction avec ses paramètres depuis le nom d'un service.
  15. *
  16. * @param mixed[] $parameters
  17. */
  18. public function dynamicInvokeServiceWithArgsAndMethod(string $serviceName, string $method, array $parameters = []): mixed
  19. {
  20. $class = $this->container->get($serviceName);
  21. if ($class === null) {
  22. throw new \LogicException('no class found for service '.$serviceName, 400);
  23. }
  24. if (!method_exists($class, $method)) {
  25. throw new \LogicException('method_not_exist', 400);
  26. }
  27. return $class->{$method}(...$parameters);
  28. }
  29. /**
  30. * Appelle une fonction avec ses paramètres depuis le nom d'une classe.
  31. *
  32. * @param mixed[] $parameters
  33. * @param mixed[] $constructorParameters
  34. *
  35. * @throws \ReflectionException
  36. */
  37. public function dynamicInvokeClassWithArgsAndMethod(string $className, string $methodName, array $parameters = [], array $constructorParameters = []): mixed
  38. {
  39. $reflection = new \ReflectionClass($className);
  40. $method = $reflection->getMethod($methodName);
  41. if ($method->isStatic()) {
  42. return $method->invoke(null, ...$parameters);
  43. }
  44. return $method->invoke(new $className(...$constructorParameters), ...$parameters);
  45. }
  46. }