1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\DependencyInjection\Compiler;
13
14use Symfony\Component\DependencyInjection\ContainerBuilder;
15use Symfony\Component\DependencyInjection\Reference;
16
17/**
18 * Trait that allows a generic method to find and sort service by priority option in the tag.
19 *
20 * @author Iltar van der Berg <kjarli@gmail.com>
21 */
22trait PriorityTaggedServiceTrait
23{
24    /**
25     * Finds all services with the given tag name and order them by their priority.
26     *
27     * The order of additions must be respected for services having the same priority,
28     * and knowing that the \SplPriorityQueue class does not respect the FIFO method,
29     * we should not use that class.
30     *
31     * @see https://bugs.php.net/53710
32     * @see https://bugs.php.net/60926
33     *
34     * @param string $tagName
35     *
36     * @return Reference[]
37     */
38    private function findAndSortTaggedServices($tagName, ContainerBuilder $container)
39    {
40        $services = [];
41
42        foreach ($container->findTaggedServiceIds($tagName, true) as $serviceId => $attributes) {
43            $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
44            $services[$priority][] = new Reference($serviceId);
45        }
46
47        if ($services) {
48            krsort($services);
49            $services = \call_user_func_array('array_merge', $services);
50        }
51
52        return $services;
53    }
54}
55