AliasDeprecatedPublicServicesPass.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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\InvalidArgumentException;
  13. use Symfony\Component\DependencyInjection\Reference;
  14. final class AliasDeprecatedPublicServicesPass extends AbstractRecursivePass
  15. {
  16. private $tagName;
  17. private $aliases = [];
  18. public function __construct(string $tagName = 'container.private')
  19. {
  20. $this->tagName = $tagName;
  21. }
  22. /**
  23. * {@inheritdoc}
  24. */
  25. protected function processValue($value, bool $isRoot = false)
  26. {
  27. if ($value instanceof Reference && isset($this->aliases[$id = (string) $value])) {
  28. return new Reference($this->aliases[$id], $value->getInvalidBehavior());
  29. }
  30. return parent::processValue($value, $isRoot);
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function process(ContainerBuilder $container)
  36. {
  37. foreach ($container->findTaggedServiceIds($this->tagName) as $id => $tags) {
  38. if (null === $package = $tags[0]['package'] ?? null) {
  39. throw new InvalidArgumentException(sprintf('The "package" attribute is mandatory for the "%s" tag on the "%s" service.', $this->tagName, $id));
  40. }
  41. if (null === $version = $tags[0]['version'] ?? null) {
  42. throw new InvalidArgumentException(sprintf('The "version" attribute is mandatory for the "%s" tag on the "%s" service.', $this->tagName, $id));
  43. }
  44. $definition = $container->getDefinition($id);
  45. if (!$definition->isPublic() || $definition->isPrivate()) {
  46. throw new InvalidArgumentException(sprintf('The "%s" service is private: it cannot have the "%s" tag.', $id, $this->tagName));
  47. }
  48. $container
  49. ->setAlias($id, $aliasId = '.'.$this->tagName.'.'.$id)
  50. ->setPublic(true)
  51. ->setDeprecated($package, $version, 'Accessing the "%alias_id%" service directly from the container is deprecated, use dependency injection instead.');
  52. $container->setDefinition($aliasId, $definition);
  53. $this->aliases[$id] = $aliasId;
  54. }
  55. parent::process($container);
  56. }
  57. }