AutowireRequiredPropertiesPass.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\ContainerInterface;
  12. use Symfony\Component\DependencyInjection\Definition;
  13. use Symfony\Component\DependencyInjection\TypedReference;
  14. use Symfony\Contracts\Service\Attribute\Required;
  15. /**
  16. * Looks for definitions with autowiring enabled and registers their corresponding "@required" properties.
  17. *
  18. * @author Sebastien Morel (Plopix) <morel.seb@gmail.com>
  19. * @author Nicolas Grekas <p@tchwork.com>
  20. */
  21. class AutowireRequiredPropertiesPass extends AbstractRecursivePass
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. protected function processValue($value, bool $isRoot = false)
  27. {
  28. if (\PHP_VERSION_ID < 70400) {
  29. return $value;
  30. }
  31. $value = parent::processValue($value, $isRoot);
  32. if (!$value instanceof Definition || !$value->isAutowired() || $value->isAbstract() || !$value->getClass()) {
  33. return $value;
  34. }
  35. if (!$reflectionClass = $this->container->getReflectionClass($value->getClass(), false)) {
  36. return $value;
  37. }
  38. $properties = $value->getProperties();
  39. foreach ($reflectionClass->getProperties() as $reflectionProperty) {
  40. if (!($type = $reflectionProperty->getType()) instanceof \ReflectionNamedType) {
  41. continue;
  42. }
  43. if ((\PHP_VERSION_ID < 80000 || !$reflectionProperty->getAttributes(Required::class))
  44. && ((false === $doc = $reflectionProperty->getDocComment()) || false === stripos($doc, '@required') || !preg_match('#(?:^/\*\*|\n\s*+\*)\s*+@required(?:\s|\*/$)#i', $doc))
  45. ) {
  46. continue;
  47. }
  48. if (\array_key_exists($name = $reflectionProperty->getName(), $properties)) {
  49. continue;
  50. }
  51. $type = $type->getName();
  52. $value->setProperty($name, new TypedReference($type, $type, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $name));
  53. }
  54. return $value;
  55. }
  56. }