-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntityList.php
More file actions
129 lines (106 loc) · 2.76 KB
/
Copy pathEntityList.php
File metadata and controls
129 lines (106 loc) · 2.76 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
namespace DevMakerLab;
use Closure;
use Countable;
use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;
abstract class EntityList implements Countable, ArrayAccess, IteratorAggregate
{
protected array $entities = [];
public function __construct(array $entities)
{
foreach ($entities as $entity) {
$this->add($entity);
}
}
public function add(Entity $entity, $offset = null): void
{
if (is_null($offset)) {
$this->entities[] = $entity;
} else {
$this->entities[$offset] = $entity;
}
}
public function all(): array
{
return $this->entities;
}
public function count(): int
{
return count($this->entities);
}
public function toArray(): array
{
return array_map(function (Entity $entity) {
return $entity->toArray();
}, $this->entities);
}
public function toJson(int $options = 0)
{
return json_encode($this->toArray(), $options);
}
public function offsetExists($offset): bool
{
return array_key_exists($offset, $this->entities);
}
public function offsetGet($offset)
{
return $this->entities[$offset];
}
public function offsetSet($offset, $value)
{
$this->add($value, $offset);
}
public function offsetUnset($offset)
{
unset($this->entities[$offset]);
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->entities);
}
public function sortBy(string $property): self
{
usort($this->entities, function($a, $b) use ($property) {
return $a->{$property} > $b->{$property} ? 1 : -1;
});
return $this;
}
public function only(...$keys): array
{
$items = [];
foreach ($this->entities as $entity) {
$result = array_intersect_key((array)$entity, array_flip($keys));
if (! empty($result)) {
$items[] = $result;
}
}
return $items;
}
/**
* @param mixed|Closure
* @param ?mixed $value
*/
public function filter($key, $value = null): array
{
$callable = is_callable($key)
? $key
: function (Entity $entity) use ($key, $value) {
return $entity->{$key} === $value;
};
return array_filter($this->entities, $callable);
}
public function pluck(string $key): array
{
return array_column($this->entities, $key);
}
public function groupBy(string $key): array
{
$group = [];
foreach ($this->entities as $entity) {
$group[$entity->{$key}][] = $entity;
}
return $group;
}
}