菜谱项目

RemoveEmptyControllerArgumentLocatorsPass.php 2.9KB

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