Completed
Push — master ( 6d0dd7...30241b )
by Sebastian
02:33
created

src/macros/sectionBy.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
use Illuminate\Support\Collection;
4
5
/*
6
 * Splits a collection into sections grouped by a given key.
7
 *
8
 * @param mixed $key
9
 * @param bool $preserveKeys
10
 * @param mixed $sectionKey
11
 * @param mixed $itemsKey
12
 *
13
 * @return \Illuminate\Support\Collection
14
 */
15
Collection::macro('sectionBy', function ($key, bool $preserveKeys = false, $sectionKey = 0, $itemsKey = 1): Collection {
16
    $sectionNameRetriever = $this->valueRetriever($key);
0 ignored issues
show
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
17
18
    $results = new Collection();
19
20
    foreach ($this->items as $key => $value) {
21
        $sectionName = $sectionNameRetriever($value);
22
23
        if (! $results->last() || $results->last()->get($sectionKey) !== $sectionName) {
24
            $results->push(new Collection([
25
                $sectionKey => $sectionName,
26
                $itemsKey => new Collection(),
27
            ]));
28
        }
29
30
        $results->last()->get($itemsKey)->offsetSet($preserveKeys ? $key : null, $value);
31
    }
32
33
    return $results;
34
});
35