SectionBy::__invoke()   A
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.2408
c 0
b 0
f 0
cc 5
nc 1
nop 0
1
<?php
2
3
namespace Spatie\CollectionMacros\Macros;
4
5
use Illuminate\Support\Collection;
6
7
/**
8
 * Splits a collection into sections grouped by a given key.
9
 *
10
 * @param mixed $key
11
 * @param bool $preserveKeys
12
 * @param mixed $sectionKey
13
 * @param mixed $itemsKey
14
 *
15
 * @mixin \Illuminate\Support\Collection
16
 *
17
 * @return \Illuminate\Support\Collection
18
 */
19
class SectionBy
20
{
21
    public function __invoke()
22
    {
23
        return function ($key, bool $preserveKeys = false, $sectionKey = 0, $itemsKey = 1): Collection {
24
            $sectionNameRetriever = $this->valueRetriever($key);
0 ignored issues
show
Bug introduced by
The method valueRetriever() does not seem to exist on object<Spatie\CollectionMacros\Macros\SectionBy>.

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.

Loading history...
25
26
            $results = new Collection();
27
28
            foreach ($this->items as $key => $value) {
0 ignored issues
show
Bug introduced by
The property items does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
29
                $sectionName = $sectionNameRetriever($value);
30
31
                if (! $results->last() || $results->last()->get($sectionKey) !== $sectionName) {
32
                    $results->push(new Collection([
33
                        $sectionKey => $sectionName,
34
                        $itemsKey => new Collection(),
35
                    ]));
36
                }
37
38
                $results->last()->get($itemsKey)->offsetSet($preserveKeys ? $key : null, $value);
39
            }
40
41
            return $results;
42
        };
43
    }
44
}
45