vendor/jms/serializer-bundle/DependencyInjection/Compiler/ServiceMapPass.php line 28

Open in your IDE?
  1. <?php
  2. namespace JMS\SerializerBundle\DependencyInjection\Compiler;
  3. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  4. use Symfony\Component\DependencyInjection\ContainerBuilder;
  5. use Symfony\Component\DependencyInjection\Definition;
  6. use Symfony\Component\DependencyInjection\Reference;
  7. /**
  8.  * This pass allows you to easily create service maps.
  9.  *
  10.  * ```php
  11.  *    $container->addCompilerPass(new ServiceMapPass(
  12.  *        'jms_serializer.visitor',
  13.  *        'format',
  14.  *        function(ContainerBuilder $container, Definition $def) {
  15.  *            $container->getDefinition('jms_serializer')
  16.  *                ->addArgument($def);
  17.  *        }
  18.  *    ));
  19.  * ```
  20.  *
  21.  * In the example above, we convert the visitors into a map service.
  22.  *
  23.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  24.  */
  25. class ServiceMapPass implements CompilerPassInterface, \Serializable
  26. {
  27.     private $tagName;
  28.     private $keyAttributeName;
  29.     private $callable;
  30.     public function __construct($tagName$keyAttributeName$callable)
  31.     {
  32.         $this->tagName $tagName;
  33.         $this->keyAttributeName $keyAttributeName;
  34.         $this->callable $callable;
  35.     }
  36.     public function process(ContainerBuilder $container)
  37.     {
  38.         if (!is_callable($this->callable)) {
  39.             throw new \RuntimeException('The callable is invalid. If you had serialized this pass, the original callable might not be available anymore.');
  40.         }
  41.         $serviceMap = array();
  42.         foreach ($container->findTaggedServiceIds($this->tagName) as $id => $tags) {
  43.             foreach ($tags as $tag) {
  44.                 if (!isset($tag[$this->keyAttributeName])) {
  45.                     throw new \RuntimeException(sprintf('The attribute "%s" must be set for service "%s" and tag "%s".'$this->keyAttributeName$id$this->tagName));
  46.                 }
  47.                 $serviceMap[$tag[$this->keyAttributeName]] = new Reference($id);
  48.             }
  49.         }
  50.         $def = new Definition('PhpCollection\Map');
  51.         $def->addArgument($serviceMap);
  52.         call_user_func($this->callable$container$def);
  53.     }
  54.     public function serialize()
  55.     {
  56.         return serialize(array($this->tagName$this->keyAttributeName));
  57.     }
  58.     public function unserialize($str)
  59.     {
  60.         list($this->tagName$this->keyAttributeName) = unserialize($str);
  61.     }
  62. }