Completed
Push — master ( 77de06...45cc8d )
by
unknown
01:29
created

addRequestedModelFieldsToQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Spatie\QueryBuilder\Concerns;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Support\Collection;
7
use Spatie\QueryBuilder\Exceptions\InvalidFieldQuery;
8
use Spatie\QueryBuilder\Exceptions\UnknownIncludedFieldsQuery;
9
use Spatie\QueryBuilder\Exceptions\AllowedFieldsMustBeCalledBeforeAllowedIncludes;
10
11
trait AddsFieldsToQuery
12
{
13
    /** @var \Illuminate\Support\Collection */
14
    protected $allowedFields;
15
16
    public function allowedFields($fields): self
17
    {
18
        if ($this->allowedIncludes instanceof Collection) {
0 ignored issues
show
Bug introduced by
The property allowedIncludes 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...
19
            throw new AllowedFieldsMustBeCalledBeforeAllowedIncludes();
20
        }
21
22
        $fields = is_array($fields) ? $fields : func_get_args();
23
24
        $this->allowedFields = collect($fields)
25
            ->map(function (string $fieldName) {
26
                return $this->prependField($fieldName);
27
            });
28
29
        $this->ensureAllFieldsExist();
30
31
        $this->addRequestedModelFieldsToQuery();
32
33
        return $this;
34
    }
35
36
    protected function addRequestedModelFieldsToQuery()
37
    {
38
        $modelTableName = $this->getModel()->getTable();
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...
39
40
        $modelFields = $this->request->fields()->get($modelTableName);
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...
41
42
        if (empty($modelFields)) {
43
            return;
44
        }
45
46
        $prependedFields = $this->prependFieldsWithTableName($modelFields, $modelTableName);
47
48
        $this->select($prependedFields);
0 ignored issues
show
Bug introduced by
It seems like select() 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...
49
    }
50
51
    public function getRequestedFieldsForRelatedTable(string $relation): array
52
    {
53
        $fields = $this->request->fields()->get($relation);
54
55
        if (! $fields) {
56
            return [];
57
        }
58
59
        if (! $this->allowedFields instanceof Collection) {
60
            // We have requested fields but no allowed fields (yet?)
61
62
            throw new UnknownIncludedFieldsQuery($fields);
63
        }
64
65
        return $fields;
66
    }
67
68
    protected function ensureAllFieldsExist()
69
    {
70
        $requestedFields = $this->request->fields()
71
            ->map(function ($fields, $model) {
72
                $tableName = Str::snake(preg_replace('/-/', '_', $model));
73
74
                $fields = array_map([Str::class, 'snake'], $fields);
75
76
                return $this->prependFieldsWithTableName($fields, $tableName);
77
            })
78
            ->flatten()
79
            ->unique();
80
81
        $unknownFields = $requestedFields->diff($this->allowedFields);
82
83
        if ($unknownFields->isNotEmpty()) {
84
            throw InvalidFieldQuery::fieldsNotAllowed($unknownFields, $this->allowedFields);
85
        }
86
    }
87
88
    protected function prependFieldsWithTableName(array $fields, string $tableName): array
89
    {
90
        return array_map(function ($field) use ($tableName) {
91
            return $this->prependField($field, $tableName);
92
        }, $fields);
93
    }
94
95
    protected function prependField(string $field, ?string $table = null): string
96
    {
97
        if (! $table) {
98
            $table = $this->getModel()->getTable();
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...
99
        }
100
101
        if (Str::contains($field, '.')) {
102
            // Already prepended
103
104
            return $field;
105
        }
106
107
        return "{$table}.{$field}";
108
    }
109
}
110