|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Collections\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Collections\ArrayList; |
|
6
|
|
|
use Collections\Dictionary; |
|
7
|
|
|
use Collections\Iterable; |
|
8
|
|
|
|
|
9
|
|
|
trait CommonMutableContainerTrait |
|
10
|
|
|
{ |
|
11
|
|
|
use ExtractTrait; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* {@inheritdoc} |
|
15
|
|
|
*/ |
|
16
|
1 |
|
public function values() |
|
17
|
|
|
{ |
|
18
|
1 |
|
return new ArrayList($this); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function toValuesArray() |
|
22
|
|
|
{ |
|
23
|
|
|
return $this->toArray(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
1 |
|
public function toKeysArray() |
|
27
|
|
|
{ |
|
28
|
1 |
|
$res = []; |
|
29
|
1 |
|
foreach ($this as $k => $_) { |
|
|
|
|
|
|
30
|
1 |
|
$res[] = $k; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
1 |
|
return $res; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* {@inheritdoc} |
|
38
|
|
|
*/ |
|
39
|
17 |
|
public function toArray() |
|
40
|
|
|
{ |
|
41
|
17 |
|
$arr = []; |
|
42
|
17 |
|
foreach ($this as $key => $value) { |
|
|
|
|
|
|
43
|
16 |
|
if ($value instanceof Iterable) { |
|
44
|
6 |
|
$arr[$key] = $value->toArray(); |
|
45
|
|
|
} else { |
|
46
|
16 |
|
$arr[$key] = $value; |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
17 |
|
return $arr; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* {@inheritdoc} |
|
55
|
|
|
*/ |
|
56
|
1 |
|
public static function fromArray(array $arr) |
|
57
|
|
|
{ |
|
58
|
1 |
|
$map = new static(); |
|
59
|
1 |
|
foreach ($arr as $k => $v) { |
|
60
|
1 |
|
if (is_array($v)) { |
|
61
|
|
|
$map[$k] = new static($v); |
|
|
|
|
|
|
62
|
|
|
} else { |
|
63
|
1 |
|
$map[$k] = $v; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
1 |
|
return $map; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* {@inheritDoc} |
|
72
|
|
|
* @return $this |
|
73
|
|
|
*/ |
|
74
|
2 |
|
public function groupBy($callback) |
|
75
|
|
|
{ |
|
76
|
2 |
|
$callback = $this->propertyExtractor($callback); |
|
77
|
2 |
|
$group = new Dictionary(); |
|
78
|
2 |
|
foreach ($this as $value) { |
|
|
|
|
|
|
79
|
2 |
|
$key = $callback($value); |
|
80
|
2 |
|
if (!$group->containsKey($key)) { |
|
81
|
2 |
|
$group->add($key, new ArrayList([$value])); |
|
82
|
|
|
} else { |
|
83
|
2 |
|
$value = $group->get($key)->add($value); |
|
84
|
2 |
|
$group->set($key, $value); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
2 |
|
return $group; |
|
89
|
|
|
} |
|
90
|
|
|
|
|
91
|
|
|
/** |
|
92
|
|
|
* {@inheritDoc} |
|
93
|
|
|
* @return $this |
|
94
|
|
|
*/ |
|
95
|
2 |
|
public function indexBy($callback) |
|
96
|
|
|
{ |
|
97
|
2 |
|
$callback = $this->propertyExtractor($callback); |
|
98
|
2 |
|
$group = new Dictionary(); |
|
99
|
2 |
|
foreach ($this as $value) { |
|
|
|
|
|
|
100
|
2 |
|
$key = $callback($value); |
|
101
|
2 |
|
$group->set($key, $value); |
|
102
|
|
|
} |
|
103
|
|
|
|
|
104
|
2 |
|
return $group; |
|
105
|
|
|
} |
|
106
|
|
|
} |
|
107
|
|
|
|