ResolveReferencesToAliasesPass.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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())->setPrivate($alias->isPrivate());
  32. }
  33. }
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. protected function processValue($value, $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. @trigger_error(sprintf('%s. It is being referenced by the "%s" %s.', rtrim($alias->getDeprecationMessage($id), '. '), $this->currentId, $container->hasDefinition($this->currentId) ? 'service' : 'alias'), \E_USER_DEPRECATED);
  56. }
  57. }
  58. $seen = [];
  59. do {
  60. if (isset($seen[$id])) {
  61. throw new ServiceCircularReferenceException($id, array_merge(array_keys($seen), [$id]));
  62. }
  63. $seen[$id] = true;
  64. $id = (string) $container->getAlias($id);
  65. } while ($container->hasAlias($id));
  66. return $id;
  67. }
  68. }