forked from nelmio/alice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParameterBag.php
100 lines (83 loc) · 2.11 KB
/
ParameterBag.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
<?php
/*
* This file is part of the Alice package.
*
* (c) Nelmio <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Nelmio\Alice;
use Nelmio\Alice\Throwable\Exception\ParameterNotFoundException;
use Nelmio\Alice\Throwable\Exception\ParameterNotFoundExceptionFactory;
/**
* Value object containing a list of parameters.
*/
final class ParameterBag implements \IteratorAggregate, \Countable
{
/**
* @var mixed[]
*/
private $parameters = [];
/**
* @param mixed[] $parameters Keys/values pair of parameters
*/
public function __construct(array $parameters = [])
{
$this->parameters = deep_clone($parameters);
}
/**
* Returns a new instance which will include the passed parameter. If a parameter with that key already exist, it
* WILL NOT be overridden.
*/
public function with(Parameter $parameter): self
{
$key = $parameter->getKey();
$clone = clone $this;
if (false === $clone->has($key)) {
$clone->parameters[$key] = $parameter->getValue();
}
return $clone;
}
public function without(string $key): self
{
$clone = clone $this;
unset($clone->parameters[$key]);
return $clone;
}
public function has(string $key): bool
{
return array_key_exists($key, $this->parameters);
}
/**
* @throws ParameterNotFoundException
*
* @return mixed
*/
public function get(string $key)
{
if ($this->has($key)) {
return deep_clone($this->parameters[$key]);
}
throw ParameterNotFoundExceptionFactory::create($key);
}
/**
* @inheritdoc
*/
public function getIterator()
{
return new \ArrayIterator($this->parameters);
}
/**
* @inheritdoc
*/
public function count()
{
return count($this->parameters);
}
public function toArray(): array
{
return $this->parameters;
}
}