1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spatie\DataTransferObject; |
6
|
|
|
|
7
|
|
|
use ArrayAccess; |
8
|
|
|
use Countable; |
9
|
|
|
use Iterator; |
10
|
|
|
|
11
|
|
|
abstract class DataTransferObjectCollection implements |
12
|
|
|
ArrayAccess, |
13
|
|
|
Iterator, |
14
|
|
|
Countable |
15
|
|
|
{ |
16
|
|
|
protected array $collection; |
|
|
|
|
17
|
|
|
|
18
|
|
|
protected int $position = 0; |
19
|
|
|
|
20
|
|
|
public function __construct(array $collection = []) |
21
|
|
|
{ |
22
|
|
|
$this->collection = $collection; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function current() |
26
|
|
|
{ |
27
|
|
|
return $this->collection[$this->position]; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function offsetGet($offset) |
31
|
|
|
{ |
32
|
|
|
return $this->collection[$offset] ?? null; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function offsetSet($offset, $value) |
36
|
|
|
{ |
37
|
|
|
if (is_null($offset)) { |
38
|
|
|
$this->collection[] = $value; |
39
|
|
|
} else { |
40
|
|
|
$this->collection[$offset] = $value; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function offsetExists($offset): bool |
45
|
|
|
{ |
46
|
|
|
return array_key_exists($offset, $this->collection); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function offsetUnset($offset) |
50
|
|
|
{ |
51
|
|
|
unset($this->collection[$offset]); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function next() |
55
|
|
|
{ |
56
|
|
|
$this->position++; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function key(): int |
60
|
|
|
{ |
61
|
|
|
return $this->position; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function valid(): bool |
65
|
|
|
{ |
66
|
|
|
return array_key_exists($this->position, $this->collection); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function rewind() |
70
|
|
|
{ |
71
|
|
|
$this->position = 0; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function toArray(): array |
75
|
|
|
{ |
76
|
|
|
$collection = $this->collection; |
77
|
|
|
|
78
|
|
|
foreach ($collection as $key => $item) { |
79
|
|
|
if ( |
80
|
|
|
! $item instanceof DataTransferObject |
81
|
|
|
&& ! $item instanceof DataTransferObjectCollection |
82
|
|
|
) { |
83
|
|
|
continue; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
$collection[$key] = $item->toArray(); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return $collection; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
public function items(): array |
93
|
|
|
{ |
94
|
|
|
return $this->collection; |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
public function count(): int |
98
|
|
|
{ |
99
|
|
|
return count($this->collection); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|