|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\CollectionMacros\Macros; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Slice a collection before a given callback is met into separate chunks. |
|
9
|
|
|
* |
|
10
|
|
|
* @param callable $callback |
|
11
|
|
|
* @param bool $preserveKeys |
|
12
|
|
|
* |
|
13
|
|
|
* @mixin \Illuminate\Support\Collection |
|
14
|
|
|
* |
|
15
|
|
|
* @return \Illuminate\Support\Collection |
|
16
|
|
|
*/ |
|
17
|
|
|
class SliceBefore |
|
18
|
|
|
{ |
|
19
|
|
|
public function __invoke() |
|
20
|
|
|
{ |
|
21
|
|
|
return function ($callback, bool $preserveKeys = false): Collection { |
|
22
|
|
|
if ($this->isEmpty()) { |
|
|
|
|
|
|
23
|
|
|
return new static(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
if (! $preserveKeys) { |
|
27
|
|
|
$sliced = new static([ |
|
|
|
|
|
|
28
|
|
|
new static([$this->first()]), |
|
|
|
|
|
|
29
|
|
|
]); |
|
30
|
|
|
|
|
31
|
|
|
return $this->eachCons(2)->reduce(function ($sliced, $previousAndCurrent) use ($callback) { |
|
|
|
|
|
|
32
|
|
|
[$previousItem, $item] = $previousAndCurrent; |
|
|
|
|
|
|
33
|
|
|
|
|
34
|
|
|
$callback($item, $previousItem) |
|
35
|
|
|
? $sliced->push(new static([$item])) |
|
|
|
|
|
|
36
|
|
|
: $sliced->last()->push($item); |
|
37
|
|
|
|
|
38
|
|
|
return $sliced; |
|
39
|
|
|
}, $sliced); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$sliced = new static([$this->take(1)]); |
|
|
|
|
|
|
43
|
|
|
|
|
44
|
|
|
return $this->eachCons(2, $preserveKeys)->reduce(function ($sliced, $previousAndCurrent) use ($callback) { |
|
|
|
|
|
|
45
|
|
|
$previousItem = $previousAndCurrent->take(1); |
|
46
|
|
|
$item = $previousAndCurrent->take(-1); |
|
47
|
|
|
|
|
48
|
|
|
$itemKey = $item->keys()->first(); |
|
49
|
|
|
$valuesItem = $item->first(); |
|
50
|
|
|
$valuesPreviousItem = $previousItem->first(); |
|
51
|
|
|
|
|
52
|
|
|
$callback($valuesItem, $valuesPreviousItem) |
|
53
|
|
|
? $sliced->push($item) |
|
54
|
|
|
: $sliced->last()->put($itemKey, $valuesItem); |
|
55
|
|
|
|
|
56
|
|
|
return $sliced; |
|
57
|
|
|
}, $sliced); |
|
58
|
|
|
}; |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.