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