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