|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Nayjest\Collection\Decorator; |
|
4
|
|
|
|
|
5
|
|
|
use Nayjest\Collection\Collection; |
|
6
|
|
|
use Nayjest\Collection\CollectionReadInterface; |
|
7
|
|
|
use Nayjest\Collection\CollectionReadTrait; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Implementation of composite design pattern for collections. |
|
11
|
|
|
* |
|
12
|
|
|
* @package Nayjest\Collection\Decorator |
|
13
|
|
|
*/ |
|
14
|
|
|
class CompositeCollection implements CollectionReadInterface |
|
15
|
|
|
{ |
|
16
|
|
|
use CollectionReadTrait; |
|
17
|
|
|
|
|
18
|
|
|
/** @var CollectionReadInterface[] */ |
|
19
|
|
|
private $collections = []; |
|
20
|
|
|
private $data; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @return CollectionReadInterface[] |
|
24
|
|
|
*/ |
|
25
|
|
|
public function getCollections() |
|
26
|
|
|
{ |
|
27
|
|
|
return $this->collections; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param CollectionReadInterface[] $collections |
|
32
|
|
|
* |
|
33
|
|
|
* @return $this |
|
34
|
|
|
*/ |
|
35
|
9 |
|
public function setCollections(array $collections) |
|
36
|
|
|
{ |
|
37
|
9 |
|
$this->collections = $collections; |
|
38
|
|
|
|
|
39
|
9 |
|
return $this; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Returns composed collection by index |
|
44
|
|
|
* |
|
45
|
|
|
* @param $index |
|
46
|
|
|
* |
|
47
|
|
|
* @return CollectionReadInterface |
|
48
|
|
|
*/ |
|
49
|
|
|
public function getCollection($index) |
|
50
|
|
|
{ |
|
51
|
|
|
return array_key_exists($index, $this->collections) |
|
52
|
|
|
? $this->collections[$index] |
|
53
|
|
|
: null; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
1 |
|
protected function createCollection(array $items) |
|
57
|
|
|
{ |
|
58
|
1 |
|
$collection = new static(); |
|
59
|
1 |
|
$collection->setCollections([new Collection($items)]); |
|
60
|
|
|
|
|
61
|
1 |
|
return $collection; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Returns reference to array storing collection items. |
|
66
|
|
|
* |
|
67
|
|
|
* @return array |
|
68
|
|
|
*/ |
|
69
|
9 |
|
protected function &items() |
|
70
|
|
|
{ |
|
71
|
9 |
|
$this->updateData(); |
|
72
|
|
|
|
|
73
|
9 |
|
return $this->data; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
9 |
|
private function updateData() |
|
77
|
|
|
{ |
|
78
|
9 |
|
$this->data = (count($this->collections) !== 0) |
|
79
|
9 |
|
? call_user_func_array( |
|
80
|
9 |
|
'array_merge', |
|
81
|
9 |
|
array_map('iterator_to_array', $this->collections) |
|
82
|
9 |
|
) : []; |
|
83
|
9 |
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|