RemoveEmptyControllerArgumentLocatorsPass.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. /**
  14. * Removes empty service-locators registered for ServiceValueResolver.
  15. *
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. class RemoveEmptyControllerArgumentLocatorsPass implements CompilerPassInterface
  19. {
  20. private $controllerLocator;
  21. public function __construct(string $controllerLocator = 'argument_resolver.controller_locator')
  22. {
  23. $this->controllerLocator = $controllerLocator;
  24. }
  25. public function process(ContainerBuilder $container)
  26. {
  27. $controllerLocator = $container->findDefinition($this->controllerLocator);
  28. $controllers = $controllerLocator->getArgument(0);
  29. foreach ($controllers as $controller => $argumentRef) {
  30. $argumentLocator = $container->getDefinition((string) $argumentRef->getValues()[0]);
  31. if (!$argumentLocator->getArgument(0)) {
  32. // remove empty argument locators
  33. $reason = sprintf('Removing service-argument resolver for controller "%s": no corresponding services exist for the referenced types.', $controller);
  34. } else {
  35. // any methods listed for call-at-instantiation cannot be actions
  36. $reason = false;
  37. [$id, $action] = explode('::', $controller);
  38. if ($container->hasAlias($id)) {
  39. continue;
  40. }
  41. $controllerDef = $container->getDefinition($id);
  42. foreach ($controllerDef->getMethodCalls() as [$method]) {
  43. if (0 === strcasecmp($action, $method)) {
  44. $reason = sprintf('Removing method "%s" of service "%s" from controller candidates: the method is called at instantiation, thus cannot be an action.', $action, $id);
  45. break;
  46. }
  47. }
  48. if (!$reason) {
  49. // see Symfony\Component\HttpKernel\Controller\ContainerControllerResolver
  50. $controllers[$id.':'.$action] = $argumentRef;
  51. if ('__invoke' === $action) {
  52. $controllers[$id] = $argumentRef;
  53. }
  54. continue;
  55. }
  56. }
  57. unset($controllers[$controller]);
  58. $container->log($this, $reason);
  59. }
  60. $controllerLocator->replaceArgument(0, $controllers);
  61. }
  62. }