1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of DivineNii opensource projects. |
7
|
|
|
* |
8
|
|
|
* PHP version 7.4 and above required |
9
|
|
|
* |
10
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
11
|
|
|
* @copyright 2021 DivineNii (https://divinenii.com/) |
12
|
|
|
* @license https://opensource.org/licenses/BSD-3-Clause License |
13
|
|
|
* |
14
|
|
|
* For the full copyright and license information, please view the LICENSE |
15
|
|
|
* file that was distributed with this source code. |
16
|
|
|
*/ |
17
|
|
|
|
18
|
|
|
namespace Rade\DI\Traits; |
19
|
|
|
|
20
|
|
|
use Rade\DI\Exceptions\ContainerResolutionException; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* This trait adds aliasing functionality to container. |
24
|
|
|
* |
25
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
trait AliasTrait |
28
|
|
|
{ |
29
|
|
|
/** @var array<string,string> alias => service name */ |
30
|
|
|
protected array $aliases = []; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Remove an aliased definition. |
34
|
|
|
*/ |
35
|
|
|
final public function removeAlias(string $id): void |
36
|
|
|
{ |
37
|
|
|
unset($this->aliases[$id]); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* {@inheritdoc} |
42
|
|
|
*/ |
43
|
|
|
public function alias(string $id, string $serviceId): void |
44
|
|
|
{ |
45
|
|
|
if ($id === $serviceId) { |
46
|
|
|
throw new \LogicException(\sprintf('[%s] is aliased to itself.', $id)); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (isset($this->types) && $typed = $this->typed($serviceId, true)) { |
|
|
|
|
50
|
|
|
if (\count($typed) > 1) { |
51
|
|
|
throw new ContainerResolutionException(\sprintf('Aliasing an alias of "%s" on a multiple defined type "%s" is not allowed.', $id, $serviceId)); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$serviceId = $typed[0]; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
if (!$this->has($serviceId)) { |
|
|
|
|
58
|
|
|
throw $this->createNotFound($serviceId); |
|
|
|
|
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$this->aliases[$id] = $this->aliases[$serviceId] ?? $serviceId; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* {@inheritdoc} |
66
|
|
|
*/ |
67
|
|
|
public function aliased(string $id): bool |
68
|
|
|
{ |
69
|
|
|
foreach ($this->aliases as $serviceId) { |
70
|
|
|
if ($id === $serviceId) { |
71
|
|
|
return true; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return false; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|