RegisterEntityResolversCompilerPass.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Drupal\serialization;
  3. use Symfony\Component\DependencyInjection\Reference;
  4. use Symfony\Component\DependencyInjection\ContainerBuilder;
  5. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  6. /**
  7. * Adds services tagged 'normalizer' and 'encoder' to the Serializer.
  8. */
  9. class RegisterEntityResolversCompilerPass implements CompilerPassInterface {
  10. /**
  11. * Adds services to the Serializer.
  12. *
  13. * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
  14. * The container to process.
  15. */
  16. public function process(ContainerBuilder $container) {
  17. $definition = $container->getDefinition('serializer.entity_resolver');
  18. $resolvers = [];
  19. // Retrieve registered Normalizers and Encoders from the container.
  20. foreach ($container->findTaggedServiceIds('entity_resolver') as $id => $attributes) {
  21. $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
  22. $resolvers[$priority][] = new Reference($id);
  23. }
  24. // Add the registered concrete EntityResolvers to the ChainEntityResolver.
  25. foreach ($this->sort($resolvers) as $resolver) {
  26. $definition->addMethodCall('addResolver', [$resolver]);
  27. }
  28. }
  29. /**
  30. * Sorts by priority.
  31. *
  32. * Order services from highest priority number to lowest (reverse sorting).
  33. *
  34. * @param array $services
  35. * A nested array keyed on priority number. For each priority number, the
  36. * value is an array of Symfony\Component\DependencyInjection\Reference
  37. * objects, each a reference to a normalizer or encoder service.
  38. *
  39. * @return array
  40. * A flattened array of Reference objects from $services, ordered from high
  41. * to low priority.
  42. */
  43. protected function sort($services) {
  44. $sorted = [];
  45. krsort($services);
  46. // Flatten the array.
  47. foreach ($services as $a) {
  48. $sorted = array_merge($sorted, $a);
  49. }
  50. return $sorted;
  51. }
  52. }