|
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
|
|
|
public function groupBy($fn) |
|
27
|
|
|
{ |
|
28
|
|
|
$array = $this->toArray(); |
|
|
|
|
|
|
29
|
|
|
$mapped = (new $this($array))->map($fn)->toArray(); |
|
30
|
|
|
$grouped = []; |
|
31
|
|
|
foreach ($mapped as $key => $val) { |
|
32
|
|
|
$grouped[$val][$key] = $array[$key]; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
return new $this($grouped, $this->debug); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* SQL's LEFT JOIN |
|
40
|
|
|
* - in order to avoid N+1 problem |
|
41
|
|
|
*/ |
|
42
|
|
|
public function leftJoin($map, callable $fetch, callable $combine) |
|
43
|
|
|
{ |
|
44
|
|
|
$array = $this->toArray(); |
|
|
|
|
|
|
45
|
|
|
|
|
46
|
|
|
if ($map) { |
|
47
|
|
|
$mapped = (new $this($array))->groupBy($map)->toArray(); |
|
48
|
|
|
} else { |
|
49
|
|
|
$mapped = []; |
|
50
|
|
|
foreach ($array as $key => $val) { |
|
51
|
|
|
$mapped[$key] = [$key]; |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
$keys = array_keys($mapped); |
|
55
|
|
|
$fetched = $fetch($keys); |
|
56
|
|
|
if (!is_array($fetched)) { |
|
57
|
|
|
throw new \UnexpectedValueException( |
|
58
|
|
|
'leftJoin($map, $fetch, $combine) $fetch must be function-type [key1, key2, ...] => [key1 => val1, ...]' |
|
59
|
|
|
); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
foreach ($fetched as $key => $val) { |
|
63
|
|
|
if (!isset($mapped[$key])) { |
|
64
|
|
|
throw new \UnexpectedValueException( |
|
65
|
|
|
'leftJoin($map, $fetch, $combine) $fetch returned an array having unexpected key: ' . $key |
|
66
|
|
|
); |
|
67
|
|
|
} |
|
68
|
|
|
foreach ($mapped[$key] as $originKey) { |
|
69
|
|
|
$array[$originKey] = $combine($array[$originKey], $val); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
return new $this($array, $this->debug); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|
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: