1
|
|
|
<?php |
2
|
|
|
namespace Spindle\Collection\Traits; |
3
|
|
|
|
4
|
|
|
trait SetsTrait |
5
|
|
|
{ |
6
|
|
|
/** |
7
|
|
|
* @param int $size |
8
|
|
|
* @return \Spindle\Collection\Collection |
9
|
|
|
*/ |
10
|
1 |
|
public function chunk($size) |
11
|
|
|
{ |
12
|
1 |
|
return new $this(array_chunk($this->toArray(), $size), $this->debug); |
|
|
|
|
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @return \Spindle\Collection\Collection |
17
|
|
|
*/ |
18
|
1 |
|
public function unique() |
19
|
|
|
{ |
20
|
1 |
|
return new $this(array_unique($this->toArray()), $this->debug); |
|
|
|
|
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @return \Spindle\Collection\Collection |
25
|
|
|
*/ |
26
|
1 |
|
public function groupBy($fn) |
27
|
|
|
{ |
28
|
1 |
|
$array = $this->toArray(); |
|
|
|
|
29
|
1 |
|
$mapped = (new $this($array))->map($fn)->toArray(); |
30
|
1 |
|
$grouped = []; |
31
|
1 |
|
foreach ($mapped as $key => $val) { |
32
|
1 |
|
$grouped[$val][$key] = $array[$key]; |
33
|
1 |
|
} |
34
|
|
|
|
35
|
1 |
|
return new $this($grouped, $this->debug); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* SQL's LEFT JOIN |
40
|
|
|
* - in order to avoid N+1 problem |
41
|
|
|
*/ |
42
|
3 |
|
public function leftJoin($map, callable $fetch, callable $combine) |
43
|
|
|
{ |
44
|
3 |
|
$array = $this->toArray(); |
|
|
|
|
45
|
|
|
|
46
|
3 |
|
if ($map) { |
47
|
3 |
|
$keys = (new $this($array))->map($map)->toArray(); |
48
|
3 |
|
$mapped = []; |
49
|
3 |
|
foreach ($keys as $key => $val) { |
50
|
3 |
|
$mapped[$val][] = $key; |
51
|
3 |
|
} |
52
|
3 |
|
} else { |
53
|
1 |
|
$mapped = []; |
54
|
1 |
|
foreach ($array as $key => $val) { |
55
|
1 |
|
$mapped[$key] = [$key]; |
56
|
1 |
|
} |
57
|
|
|
} |
58
|
3 |
|
$keys = array_keys($mapped); |
59
|
3 |
|
$fetched = $fetch($keys); |
60
|
3 |
|
if (!is_array($fetched)) { |
61
|
1 |
|
throw new \UnexpectedValueException( |
62
|
|
|
'leftJoin($map, $fetch, $combine) $fetch must be function-type [key1, key2, ...] => [key1 => val1, ...]' |
63
|
1 |
|
); |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
foreach ($fetched as $key => $val) { |
67
|
2 |
|
if (!isset($mapped[$key])) { |
68
|
1 |
|
throw new \UnexpectedValueException( |
69
|
|
|
'leftJoin($map, $fetch, $combine) $fetch returned an array having unexpected key: ' . $key |
70
|
1 |
|
); |
71
|
|
|
} |
72
|
1 |
|
foreach ($mapped[$key] as $originKey) { |
73
|
1 |
|
$array[$originKey] = $combine($array[$originKey], $val); |
74
|
1 |
|
} |
75
|
1 |
|
} |
76
|
|
|
|
77
|
1 |
|
return new $this($array, $this->debug); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: