RemoveEmptyControllerArgumentLocatorsPass.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. /**
  21. * @return void
  22. */
  23. public function process(ContainerBuilder $container)
  24. {
  25. $controllerLocator = $container->findDefinition('argument_resolver.controller_locator');
  26. $controllers = $controllerLocator->getArgument(0);
  27. foreach ($controllers as $controller => $argumentRef) {
  28. $argumentLocator = $container->getDefinition((string) $argumentRef->getValues()[0]);
  29. if (!$argumentLocator->getArgument(0)) {
  30. // remove empty argument locators
  31. $reason = \sprintf('Removing service-argument resolver for controller "%s": no corresponding services exist for the referenced types.', $controller);
  32. } else {
  33. // any methods listed for call-at-instantiation cannot be actions
  34. $reason = false;
  35. [$id, $action] = explode('::', $controller);
  36. if ($container->hasAlias($id)) {
  37. continue;
  38. }
  39. $controllerDef = $container->getDefinition($id);
  40. foreach ($controllerDef->getMethodCalls() as [$method]) {
  41. if (0 === strcasecmp($action, $method)) {
  42. $reason = \sprintf('Removing method "%s" of service "%s" from controller candidates: the method is called at instantiation, thus cannot be an action.', $action, $id);
  43. break;
  44. }
  45. }
  46. if (!$reason) {
  47. // see Symfony\Component\HttpKernel\Controller\ContainerControllerResolver
  48. $controllers[$id.':'.$action] = $argumentRef;
  49. if ('__invoke' === $action) {
  50. $controllers[$id] = $argumentRef;
  51. }
  52. continue;
  53. }
  54. }
  55. unset($controllers[$controller]);
  56. $container->log($this, $reason);
  57. }
  58. $controllerLocator->replaceArgument(0, $controllers);
  59. }
  60. }