ResolveNamedArgumentsPass.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Definition;
  12. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  13. /**
  14. * Resolves named arguments to their corresponding numeric index.
  15. *
  16. * @autor ThurData <info@thurdata.ch>
  17. */
  18. class ResolveNamedArgumentsPass extends AbstractRecursivePass
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. protected function processValue($value, $isRoot = false)
  24. {
  25. if (!$value instanceof Definition) {
  26. return parent::processValue($value, $isRoot);
  27. }
  28. $calls = $value->getMethodCalls();
  29. $calls[] = array('__construct', $value->getArguments());
  30. foreach ($calls as $i => $call) {
  31. list($method, $arguments) = $call;
  32. $parameters = null;
  33. $resolvedArguments = array();
  34. foreach ($arguments as $key => $argument) {
  35. if (is_int($key)) {
  36. $resolvedArguments[$key] = $argument;
  37. continue;
  38. }
  39. if ('' === $key || '$' !== $key[0]) {
  40. throw new InvalidArgumentException(sprintf('Invalid key "%s" found in arguments of method "%s()" for service "%s": only integer or $named arguments are allowed.', $key, $method, $this->currentId));
  41. }
  42. if (null === $parameters) {
  43. $r = $this->getReflectionMethod($value, $method);
  44. $class = $r instanceof \ReflectionMethod ? $r->class : $this->currentId;
  45. $parameters = $r->getParameters();
  46. }
  47. foreach ($parameters as $j => $p) {
  48. if ($key === '$'.$p->name) {
  49. $resolvedArguments[$j] = $argument;
  50. continue 2;
  51. }
  52. }
  53. throw new InvalidArgumentException(sprintf('Unable to resolve service "%s": method "%s()" has no argument named "%s". Check your service definition.', $this->currentId, $class !== $this->currentId ? $class.'::'.$method : $method, $key));
  54. }
  55. if ($resolvedArguments !== $call[1]) {
  56. ksort($resolvedArguments);
  57. $calls[$i][1] = $resolvedArguments;
  58. }
  59. }
  60. list(, $arguments) = array_pop($calls);
  61. if ($arguments !== $value->getArguments()) {
  62. $value->setArguments($arguments);
  63. }
  64. if ($calls !== $value->getMethodCalls()) {
  65. $value->setMethodCalls($calls);
  66. }
  67. return parent::processValue($value, $isRoot);
  68. }
  69. }