|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* (c) Anton Medvedev <[email protected]> |
|
6
|
|
|
* |
|
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
8
|
|
|
* file that was distributed with this source code. |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace Deployer\Collection; |
|
12
|
|
|
|
|
13
|
|
|
use Countable; |
|
14
|
|
|
use IteratorAggregate; |
|
15
|
|
|
|
|
16
|
|
|
class Collection implements Countable, IteratorAggregate |
|
17
|
|
|
{ |
|
18
|
|
|
protected array $values = []; |
|
19
|
|
|
|
|
20
|
|
|
public function all(): array |
|
21
|
|
|
{ |
|
22
|
26 |
|
return $this->values; |
|
23
|
|
|
} |
|
24
|
26 |
|
|
|
25
|
21 |
|
public function get(string $name): mixed |
|
26
|
|
|
{ |
|
27
|
5 |
|
if ($this->has($name)) { |
|
28
|
|
|
return $this->values[$name]; |
|
29
|
|
|
} |
|
30
|
|
|
throw $this->notFound($name); |
|
31
|
26 |
|
} |
|
32
|
|
|
|
|
33
|
26 |
|
public function has(string $name): bool |
|
34
|
|
|
{ |
|
35
|
|
|
return array_key_exists($name, $this->values); |
|
36
|
23 |
|
} |
|
37
|
|
|
|
|
38
|
23 |
|
public function set(string $name, mixed $object) |
|
39
|
23 |
|
{ |
|
40
|
|
|
$this->values[$name] = $object; |
|
41
|
2 |
|
} |
|
42
|
|
|
|
|
43
|
2 |
|
public function remove(string $name): void |
|
44
|
|
|
{ |
|
45
|
|
|
if ($this->has($name)) { |
|
46
|
5 |
|
unset($this->values[$name]); |
|
47
|
|
|
} |
|
48
|
5 |
|
throw $this->notFound($name); |
|
49
|
|
|
} |
|
50
|
5 |
|
|
|
51
|
5 |
|
public function count(): int |
|
52
|
5 |
|
{ |
|
53
|
|
|
return count($this->values); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
5 |
|
public function select(callable $callback): array |
|
57
|
|
|
{ |
|
58
|
|
|
$values = []; |
|
59
|
13 |
|
|
|
60
|
|
|
foreach ($this->values as $key => $value) { |
|
61
|
13 |
|
if ($callback($value, $key)) { |
|
62
|
|
|
$values[$key] = $value; |
|
63
|
|
|
} |
|
64
|
1 |
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
return $values; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @return \ArrayIterator|\Traversable |
|
71
|
|
|
*/ |
|
72
|
|
|
#[\ReturnTypeWillChange] |
|
73
|
|
|
public function getIterator() |
|
74
|
|
|
{ |
|
75
|
|
|
return new \ArrayIterator($this->values); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
protected function notFound(string $name): \InvalidArgumentException |
|
79
|
|
|
{ |
|
80
|
|
|
return new \InvalidArgumentException("Element \"$name\" not found in collection."); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|