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