RemoveEmptyControllerArgumentLocatorsPass.php 2.5 KB

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