-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathParameterBag.php
116 lines (97 loc) · 2.52 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use function array_key_exists;
use ArrayIterator;
use function call_user_func_array;
use function count;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
class ParameterBag implements IteratorAggregate, Countable
{
/**
* @var array
*/
private $parameters = [];
/**
* @return mixed
*/
public function __call(string $name, array $arguments)
{
if (method_exists($this, $name)) {
return call_user_func_array([$this, $name], $arguments);
}
if (0 === count($arguments)) {
return $this->get($name);
}
array_unshift($arguments, $name);
return call_user_func_array([$this, 'set'], $arguments);
}
public function all(): array
{
return $this->parameters;
}
public function keys(): array
{
return array_keys($this->parameters);
}
public function replace(array $parameters): void
{
$this->parameters = $parameters;
}
/**
* @throws InvalidArgumentException if the parameters are invalid
*/
public function add(array $parameters): void
{
$replaced = array_replace($this->parameters, $parameters);
if (null === $replaced) {
throw new InvalidArgumentException('Invalid parameters');
}
$this->parameters = $replaced;
}
/**
* @throws InvalidArgumentException if the selected parameter is missing
*
* @return mixed
*/
public function get(string $key)
{
if (!array_key_exists($key, $this->parameters)) {
throw new InvalidArgumentException(sprintf('Parameter "%s" is missing', $key));
}
return $this->parameters[$key];
}
/**
* @param mixed $value The value
*/
public function set(string $key, $value): void
{
$this->parameters[$key] = $value;
}
public function has(string $key): bool
{
return array_key_exists($key, $this->parameters);
}
public function remove(string $key): void
{
unset($this->parameters[$key]);
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->parameters);
}
public function count(): int
{
return count($this->parameters);
}
}