Completed
Pull Request — master (#465)
by
unknown
01:18
created

AddsIncludesToQuery::allowedIncludes()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 9.0808
c 0
b 0
f 0
cc 5
nc 2
nop 1
1
<?php
2
3
namespace Spatie\QueryBuilder\Concerns;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Str;
8
use Spatie\QueryBuilder\AllowedInclude;
9
use Spatie\QueryBuilder\Exceptions\InvalidIncludeQuery;
10
use Spatie\QueryBuilder\Includes\IncludeInterface;
11
12
trait AddsIncludesToQuery
13
{
14
    /** @var \Illuminate\Support\Collection */
15
    protected $allowedIncludes;
16
17
    public function allowedIncludes($includes): self
18
    {
19
        $includes = is_array($includes) ? $includes : func_get_args();
20
21
        $this->allowedIncludes = collect($includes)
22
            ->reject(function ($include) {
23
                return empty($include);
24
            })
25
            ->flatMap(function ($include): Collection {
26
                if ($include instanceof Collection) {
27
                    return $include;
28
                }
29
30
                if ($include instanceof IncludeInterface) {
31
                    return collect([$include]);
32
                }
33
34
                if (Str::endsWith($include, config('query-builder.count_suffix'))) {
35
                    return AllowedInclude::count($include);
36
                }
37
38
                return AllowedInclude::relationship($include);
39
            })
40
            ->unique(function (AllowedInclude $allowedInclude) {
41
                return $allowedInclude->getName();
42
            });
43
44
        $this->ensureAllIncludesExist();
45
46
        $this->addIncludesToQuery($this->request->includes());
0 ignored issues
show
Bug introduced by
The property request 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...
47
48
        return $this;
49
    }
50
51
    protected function addIncludesToQuery(Collection $includes)
52
    {
53
        $includes->each(function ($include) {
54
            $include = $this->findInclude($include);
55
56
            $include->include($this);
57
        });
58
    }
59
60
    protected function findInclude(string $include): ?AllowedInclude
61
    {
62
        return $this->allowedIncludes
63
            ->first(function (AllowedInclude $included) use ($include) {
64
                return $included->isForInclude($include);
65
            });
66
    }
67
68
    protected function ensureAllIncludesExist()
69
    {
70
        $includes = $this->request->includes();
71
72
        $allowedIncludeNames = $this->allowedIncludes->map(function (AllowedInclude $allowedInclude) {
73
            return $allowedInclude->getName();
74
        });
75
76
        $diff = $includes->diff($allowedIncludeNames);
77
78
        if ($diff->count()) {
79
            throw InvalidIncludeQuery::includesNotAllowed($diff, $allowedIncludeNames);
80
        }
81
82
        $this->ensureRelationshipsExist($this->getModel(), $includes, $allowedIncludeNames);
0 ignored issues
show
Bug introduced by
It seems like getModel() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
83
    }
84
85
    protected function ensureRelationshipsExist($model, $includes, $allowedIncludeNames)
86
    {
87
        $includes->map(function ($include) {
88
            return [$this->getInternalName($include), $include];
89
        })->eachSpread(function ($relationships, $include) use ($model, $allowedIncludeNames) {
90
            $relationships = explode('.', Str::of($relationships)->before('Count'), 2);
91
92
            if (count($relationships) > 1) {
93
                $this->ensureRelationshipsExist($model->{$relationships[0]}()->getRelated(), collect($relationships[1]), $allowedIncludeNames);
94
            }
95
96
            $availableRelationships = collect(get_class_methods($model))->reject(function ($method) {
97
                return method_exists(Model::class, $method);
98
            });
99
100
            if (! $availableRelationships->contains($relationships[0])) {
101
                throw InvalidIncludeQuery::includesNotAllowed(collect($include), $allowedIncludeNames);
102
            }
103
        });
104
    }
105
106
    protected function getInternalName($include)
107
    {
108
        return optional($this->allowedIncludes->first(function (AllowedInclude $allowedInclude) use ($include) {
109
            return $allowedInclude->getName() === $include;
110
        }))->getInterlName() ?? $include;
111
    }
112
}
113