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

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace JMS\SerializerBundle\DependencyInjection\Compiler;
  4. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  5. use Symfony\Component\DependencyInjection\ContainerBuilder;
  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 = [];
  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.         call_user_func($this->callable$container$serviceMap);
  51.     }
  52.     public function serialize()
  53.     {
  54.         return serialize([$this->tagName$this->keyAttributeName]);
  55.     }
  56.     public function unserialize($str)
  57.     {
  58.         [$this->tagName$this->keyAttributeName] = unserialize($str);
  59.     }
  60. }