SerializerPass.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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\Serializer\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  15. /**
  16. * Adds all services with the tags "serializer.encoder" and "serializer.normalizer" as
  17. * encoders and normalizers to the "serializer" service.
  18. *
  19. * @author Javier Lopez <f12loalf@gmail.com>
  20. * @author Robin Chalas <robin.chalas@gmail.com>
  21. */
  22. class SerializerPass implements CompilerPassInterface
  23. {
  24. use PriorityTaggedServiceTrait;
  25. private $serializerService;
  26. private $normalizerTag;
  27. private $encoderTag;
  28. public function __construct(string $serializerService = 'serializer', string $normalizerTag = 'serializer.normalizer', string $encoderTag = 'serializer.encoder')
  29. {
  30. $this->serializerService = $serializerService;
  31. $this->normalizerTag = $normalizerTag;
  32. $this->encoderTag = $encoderTag;
  33. }
  34. public function process(ContainerBuilder $container)
  35. {
  36. if (!$container->hasDefinition($this->serializerService)) {
  37. return;
  38. }
  39. if (!$normalizers = $this->findAndSortTaggedServices($this->normalizerTag, $container)) {
  40. throw new RuntimeException(sprintf('You must tag at least one service as "%s" to use the "%s" service.', $this->normalizerTag, $this->serializerService));
  41. }
  42. $serializerDefinition = $container->getDefinition($this->serializerService);
  43. $serializerDefinition->replaceArgument(0, $normalizers);
  44. if (!$encoders = $this->findAndSortTaggedServices($this->encoderTag, $container)) {
  45. throw new RuntimeException(sprintf('You must tag at least one service as "%s" to use the "%s" service.', $this->encoderTag, $this->serializerService));
  46. }
  47. $serializerDefinition->replaceArgument(1, $encoders);
  48. }
  49. }