-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMaskingContainer.php
90 lines (77 loc) · 2.37 KB
/
MaskingContainer.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
<?php
declare(strict_types=1);
namespace Dhii\Container;
use Dhii\Collection\ContainerInterface;
use Dhii\Container\Exception\NotFoundException;
use Dhii\Container\Util\StringTranslatingTrait;
use Psr\Container\ContainerInterface as PsrContainerInterface;
use function array_key_exists;
/**
* An implementation of a container that wraps around another to selectively expose or mask certain keys.
*/
class MaskingContainer implements ContainerInterface
{
use StringTranslatingTrait;
/**
* @var PsrContainerInterface
*/
protected $inner;
/**
* @var bool[]
*/
protected $mask;
/**
* @var bool
*/
protected $defMask;
/**
* Constructor.
*
* @param PsrContainerInterface $inner The container whose entries to mask.
* @param bool $defaultMask The default mask. If true, all inner keys are exposed. If false, all
* inner keys are hidden. Any keys specified in the $mask parameter will
* naturally override this setting.
* @param bool[] $mask A mapping of keys to booleans, such that `true` exposes the mapped key
* and `false` hides the mapped key.
*/
public function __construct(PsrContainerInterface $inner, bool $defaultMask, array $mask)
{
$this->inner = $inner;
$this->defMask = $defaultMask;
$this->mask = $mask;
}
/**
* @inheritdoc
*/
public function get(string $key)
{
if (!$this->isExposed($key)) {
throw new NotFoundException(
$this->__('Inner key "%1$s" is not exposed', [$key]),
0,
null
);
}
return $this->inner->get($key);
}
/**
* @inheritdoc
*/
public function has(string $key): bool
{
return $this->isExposed($key) && $this->inner->has($key);
}
/**
* Checks if a key is exposed through the mask.
*
* @param string $key The key to check.
*
* @return bool True if the key is exposed, false if the key is hidden.
*/
protected function isExposed(string $key): bool
{
return array_key_exists($key, $this->mask)
? $this->mask[$key] !== false
: $this->defMask;
}
}