CollectsPaginationResult::collectResource()   B
last analyzed

Complexity

Conditions 6
Paths 13

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
nc 13
nop 1
dl 0
loc 23
ccs 0
cts 14
cp 0
crap 42
rs 8.9297
c 0
b 0
f 0
1
<?php
2
3
namespace mav3rick177\RapidPagination\Http\Resources;
4
5
use Illuminate\Http\Resources\CollectsResources;
6
use Illuminate\Http\Resources\MissingValue;
7
use Illuminate\Pagination\AbstractPaginator;
8
use mav3rick177\RapidPagination\PaginationResult;
9
10
/**
11
 * Trait CollectsPaginationResult
12
 *
13
 * @mixin \Illuminate\Http\Resources\Json\ResourceCollection
14
 */
15
trait CollectsPaginationResult
16
{
17
    use CollectsResources;
18
19
    /**
20
     * Map the given collection resource into its individual resources.
21
     *
22
     * @param  mixed $resource
23
     * @return mixed
24
     */
25
    protected function collectResource($resource)
26
    {
27
        if ($resource instanceof MissingValue) {
28
            return $resource;
29
        }
30
31
        $collects = $this->collects();
32
33
        $this->collection = $collects && !$resource->first() instanceof $collects
0 ignored issues
show
Bug introduced by
The property collection 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...
Bug Best Practice introduced by
The expression $collects of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
34
            ? $resource->mapInto($collects)
35
            : $resource->toBase();
36
37
        if ($resource instanceof AbstractPaginator) {
38
            $resource->setCollection($this->collection);
39
            return $resource;
40
        }
41
        if ($resource instanceof PaginationResult) {
42
            $resource->records = $this->collection;
43
            return $resource;
44
        }
45
46
        return $this->collection;
47
    }
48
}
49