SerializerPass.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\Bundle\FrameworkBundle\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Reference;
  14. /**
  15. * Adds all services with the tags "serializer.encoder" and "serializer.normalizer" as
  16. * encoders and normalizers to the Serializer service.
  17. *
  18. * @author Javier Lopez <f12loalf@gmail.com>
  19. */
  20. class SerializerPass implements CompilerPassInterface
  21. {
  22. public function process(ContainerBuilder $container)
  23. {
  24. if (!$container->hasDefinition('serializer')) {
  25. return;
  26. }
  27. // Looks for all the services tagged "serializer.normalizer" and adds them to the Serializer service
  28. $normalizers = $this->findAndSortTaggedServices('serializer.normalizer', $container);
  29. $container->getDefinition('serializer')->replaceArgument(0, $normalizers);
  30. // Looks for all the services tagged "serializer.encoders" and adds them to the Serializer service
  31. $encoders = $this->findAndSortTaggedServices('serializer.encoder', $container);
  32. $container->getDefinition('serializer')->replaceArgument(1, $encoders);
  33. }
  34. /**
  35. * Finds all services with the given tag name and order them by their priority.
  36. *
  37. * @param string $tagName
  38. * @param ContainerBuilder $container
  39. *
  40. * @return array
  41. *
  42. * @throws \RuntimeException
  43. */
  44. private function findAndSortTaggedServices($tagName, ContainerBuilder $container)
  45. {
  46. $services = $container->findTaggedServiceIds($tagName);
  47. if (empty($services)) {
  48. throw new \RuntimeException(sprintf('You must tag at least one service as "%s" to use the Serializer service', $tagName));
  49. }
  50. $sortedServices = array();
  51. foreach ($services as $serviceId => $attributes) {
  52. $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
  53. $sortedServices[$priority][] = new Reference($serviceId);
  54. }
  55. krsort($sortedServices);
  56. // Flatten the array
  57. return \call_user_func_array('array_merge', $sortedServices);
  58. }
  59. }