-
Notifications
You must be signed in to change notification settings - Fork 0
/
Collection.php
59 lines (52 loc) · 1.24 KB
/
Collection.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
<?php
/** @template T */
class Collection
{
public int $position;
/** @var array<T> */
private array $items;
public function __construct()
{
$this->position = 1;
}
/** @param T $item */
public function add(mixed $item, $key = null)
{
if ($key) {
$this->items[$key] = $item;
} else {
$this->items[$this->position] = $item;
return $this->position++;
}
}
/** @return array<T> */
public function getAllByField($field, $value): array
{
$response = [];
foreach ($this->items as $item) {
if (property_exists($item, $field) && $item->$field == $value) {
$response[] = $item;
}
}
return $response;
}
/** @return array<T> */
public function getAll(): array
{
return $this->items;
}
/** @return T */
public function get($key)
{
if (array_key_exists($key, $this->items)) {
return $this->items[$key];
} else {
return ["message" => "Not found entity with key : " . $key];
}
}
/** @return array<int> */
public function getKeys(): array
{
return array_keys($this->items);
}
}