CheckArgumentsValidityPass.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\RuntimeException;
  13. /**
  14. * Checks if arguments of methods are properly configured.
  15. *
  16. * @author Kévin Dunglas <dunglas@gmail.com>
  17. * @author Nicolas Grekas <p@tchwork.com>
  18. */
  19. class CheckArgumentsValidityPass extends AbstractRecursivePass
  20. {
  21. private $throwExceptions;
  22. public function __construct(bool $throwExceptions = true)
  23. {
  24. $this->throwExceptions = $throwExceptions;
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. protected function processValue($value, bool $isRoot = false)
  30. {
  31. if (!$value instanceof Definition) {
  32. return parent::processValue($value, $isRoot);
  33. }
  34. $i = 0;
  35. foreach ($value->getArguments() as $k => $v) {
  36. if ($k !== $i++) {
  37. if (!\is_int($k)) {
  38. $msg = sprintf('Invalid constructor argument for service "%s": integer expected but found string "%s". Check your service definition.', $this->currentId, $k);
  39. $value->addError($msg);
  40. if ($this->throwExceptions) {
  41. throw new RuntimeException($msg);
  42. }
  43. break;
  44. }
  45. $msg = sprintf('Invalid constructor argument %d for service "%s": argument %d must be defined before. Check your service definition.', 1 + $k, $this->currentId, $i);
  46. $value->addError($msg);
  47. if ($this->throwExceptions) {
  48. throw new RuntimeException($msg);
  49. }
  50. }
  51. }
  52. foreach ($value->getMethodCalls() as $methodCall) {
  53. $i = 0;
  54. foreach ($methodCall[1] as $k => $v) {
  55. if ($k !== $i++) {
  56. if (!\is_int($k)) {
  57. $msg = sprintf('Invalid argument for method call "%s" of service "%s": integer expected but found string "%s". Check your service definition.', $methodCall[0], $this->currentId, $k);
  58. $value->addError($msg);
  59. if ($this->throwExceptions) {
  60. throw new RuntimeException($msg);
  61. }
  62. break;
  63. }
  64. $msg = sprintf('Invalid argument %d for method call "%s" of service "%s": argument %d must be defined before. Check your service definition.', 1 + $k, $methodCall[0], $this->currentId, $i);
  65. $value->addError($msg);
  66. if ($this->throwExceptions) {
  67. throw new RuntimeException($msg);
  68. }
  69. }
  70. }
  71. }
  72. return null;
  73. }
  74. }