/
TagHelpersTrait.php
112 lines (97 loc) · 2.65 KB
/
TagHelpersTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/*
* This file is part of the Arachne
*
* Copyright (c) Jáchym Toušek (enumag@gmail.com)
*
* For the full copyright and license information, please view the file license.md that was distributed with this source code.
*/
namespace Arachne\DIHelpers\DI;
use Nette\Utils\AssertionException;
/**
* @author Jáchym Toušek <enumag@gmail.com>
*/
trait TagHelpersTrait
{
/**
* @var string[]
*/
private $tags = [];
/**
* @var string[]
*/
private $overrides = [];
/**
* @var bool
*/
private $freeze;
/**
* @param string $tag
* @param string|null $type
*
* @return string
*/
public function add($tag, $type = null)
{
if ($this->freeze) {
throw new AssertionException('Usage of '.__CLASS__.'::add() is only allowed in loadConfiguration.');
}
$this->tags[$tag] = $type;
}
/**
* @param string $tag
* @param string $service
*/
public function override($tag, $service)
{
if ($this->freeze) {
throw new AssertionException('Usage of '.__CLASS__.'::override() is only allowed in loadConfiguration.');
}
$this->overrides[$tag] = $service;
}
/**
* @param string $tag
* @param bool $override
*
* @return string
*/
public function get($tag, $override = true)
{
if (!$this->freeze) {
throw new AssertionException('Usage of '.__CLASS__.'::get() is only allowed in beforeCompile. Also make sure that '.__CLASS__.' is registered before all extensions which use it.');
}
if ($override && isset($this->overrides[$tag])) {
return $this->overrides[$tag];
}
if (!isset($this->tags[$tag])) {
throw new AssertionException("Tag '$tag' is not registered.");
}
return $this->prefixTag($tag);
}
public function beforeCompile()
{
$this->freeze = true;
$builder = $this->getContainerBuilder();
foreach ($this->tags as $tag => $type) {
if (!$type) {
continue;
}
foreach ($builder->findByTag($tag) as $key => $value) {
$class = $builder->getDefinition($key)->getClass();
if ($class !== $type && !is_subclass_of($class, $type)) {
throw new AssertionException("Service '$key' is not an instance of '$type'.");
}
}
}
$this->processTags();
}
/**
* @param string $tag
*
* @return string
*/
private function prefixTag($tag)
{
return $this->prefix('tag.'.$tag);
}
}