ResolveReferencesToAliasesPass.php 2.7 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\ContainerBuilder;
  12. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  13. use Symfony\Component\DependencyInjection\Reference;
  14. /**
  15. * Replaces all references to aliases with references to the actual service.
  16. *
  17. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  18. */
  19. class ResolveReferencesToAliasesPass extends AbstractRecursivePass
  20. {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function process(ContainerBuilder $container)
  25. {
  26. parent::process($container);
  27. foreach ($container->getAliases() as $id => $alias) {
  28. $aliasId = (string) $alias;
  29. $this->currentId = $id;
  30. if ($aliasId !== $defId = $this->getDefinitionId($aliasId, $container)) {
  31. $container->setAlias($id, $defId)->setPublic($alias->isPublic());
  32. }
  33. }
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. protected function processValue($value, bool $isRoot = false)
  39. {
  40. if (!$value instanceof Reference) {
  41. return parent::processValue($value, $isRoot);
  42. }
  43. $defId = $this->getDefinitionId($id = (string) $value, $this->container);
  44. return $defId !== $id ? new Reference($defId, $value->getInvalidBehavior()) : $value;
  45. }
  46. private function getDefinitionId(string $id, ContainerBuilder $container): string
  47. {
  48. if (!$container->hasAlias($id)) {
  49. return $id;
  50. }
  51. $alias = $container->getAlias($id);
  52. if ($alias->isDeprecated()) {
  53. $referencingDefinition = $container->hasDefinition($this->currentId) ? $container->getDefinition($this->currentId) : $container->getAlias($this->currentId);
  54. if (!$referencingDefinition->isDeprecated()) {
  55. $deprecation = $alias->getDeprecation($id);
  56. trigger_deprecation($deprecation['package'], $deprecation['version'], rtrim($deprecation['message'], '. ').'. It is being referenced by the "%s" '.($container->hasDefinition($this->currentId) ? 'service.' : 'alias.'), $this->currentId);
  57. }
  58. }
  59. $seen = [];
  60. do {
  61. if (isset($seen[$id])) {
  62. throw new ServiceCircularReferenceException($id, array_merge(array_keys($seen), [$id]));
  63. }
  64. $seen[$id] = true;
  65. $id = (string) $container->getAlias($id);
  66. } while ($container->hasAlias($id));
  67. return $id;
  68. }
  69. }