SuperdeskWebPublisher/SWPBridgeBundle

View on GitHub
DependencyInjection/Compiler/TransformersCompilerPass.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php

/*
 * This file is part of the Superdesk Web Publisher Bridge Bundle.
 *
 * Copyright 2016 Sourcefabric z.ú. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code.
 *
 * @copyright 2016 Sourcefabric z.ú
 * @license http://www.superdesk.org/license
 */

namespace SWP\Bundle\BridgeBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;

class TransformersCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('swp_bridge.http_push.transformer_chain')) {
            return;
        }

        $definition = $container->getDefinition('swp_bridge.http_push.transformer_chain');
        $transformers = $this->findAndSortTaggedServices('transformer.http_push_transformer', $container);

        $definition->replaceArgument(0, $transformers);
    }

    /**
     * Finds all services with the given tag name and order them by their priority.
     * Can be replaced by PriorityTaggedServiceTrait when upgraded to Symfony 3.0.
     *
     * @param string           $tagName
     * @param ContainerBuilder $container
     *
     * @return Reference[]
     */
    private function findAndSortTaggedServices($tagName, ContainerBuilder $container)
    {
        $services = $container->findTaggedServiceIds($tagName);
        $queue = new \SplPriorityQueue();
        foreach ($services as $serviceId => $tags) {
            foreach ($tags as $attributes) {
                $priority = isset($attributes['priority']) ? $attributes['priority'] : 0;
                $queue->insert(new Reference($serviceId), $priority);
            }
        }

        return iterator_to_array($queue, false);
    }
}