-
Notifications
You must be signed in to change notification settings - Fork 3
/
DeprefixingContainer.php
99 lines (87 loc) · 2.54 KB
/
DeprefixingContainer.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
<?php
declare(strict_types=1);
namespace Dhii\Container;
use Dhii\Collection\ContainerInterface;
use Psr\Container\ContainerInterface as PsrContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* A container implementation that wraps around an inner container to automatically add prefixes to keys during
* fetching and look up, allowing consumers to omit them.
*
* @since [*next-version*]
*/
class DeprefixingContainer implements ContainerInterface
{
/**
* @since [*next-version*]
*
* @var PsrContainerInterface
*/
protected $inner;
/**
* @since [*next-version*]
*
* @var string
*/
protected $prefix;
/**
* @since [*next-version*]
*
* @var bool
*/
protected $strict;
/**
* Constructor.
*
* @since [*next-version*]
*
* @param PsrContainerInterface $container The container whose keys to deprefix.
* @param string $prefix The prefix to remove from the container's keys.
* @param bool $strict Whether or not to fallback to prefixed keys if an un-prefixed key does
* not exist in the inner container.
*/
public function __construct(PsrContainerInterface $container, string $prefix, bool $strict = true)
{
$this->inner = $container;
$this->prefix = $prefix;
$this->strict = $strict;
}
/**
* @inheritdoc
*/
public function get(string $key)
{
/**
* @psalm-suppress InvalidCatch
* The base interface does not extend Throwable, but in fact everything that is possible
* in theory to catch will be Throwable, and PSR-11 exceptions will implement this interface
*/
try {
return $this->inner->get($this->getInnerKey($key));
} catch (NotFoundExceptionInterface $nfException) {
if ($this->strict || !$this->inner->has($key)) {
throw $nfException;
}
}
return $this->inner->get($key);
}
/**
* @inheritdoc
*/
public function has(string $key): bool
{
$realKey = $this->getInnerKey($key);
return $this->inner->has($realKey) || (!$this->strict && $this->inner->has($key));
}
/**
* Retrieves the key to use for the inner container.
*
* @param string $key The outer key.
*
* @return string The inner key.
*/
protected function getInnerKey(string $key): string
{
return $this->prefix . $key;
}
}