Completed
Push — master ( fe3617...85ef1d )
by
unknown
01:22
created

AddsFieldsToQuery::addModelFieldsToQuery()   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\ColumnNameSanitizer;
8
use Spatie\QueryBuilder\Exceptions\InvalidFieldQuery;
9
10
trait AddsFieldsToQuery
11
{
12
    /** @var \Illuminate\Support\Collection */
13
    protected $allowedFields;
14
15
    public function allowedFields($fields): self
16
    {
17
        $fields = is_array($fields) ? $fields : func_get_args();
18
19
        $this->allowedFields = collect($fields)
20
            ->map(function (string $fieldName) {
21
                if (! Str::contains($fieldName, '.')) {
22
                    $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...
23
24
                    return "{$modelTableName}.{$fieldName}";
25
                }
26
27
                return $fieldName;
28
            });
29
30
        $this->guardAgainstUnknownFields();
31
32
        $this->addModelFieldsToQuery();
33
34
        return $this;
35
    }
36
37
    public function addAllRequestedFields()
38
    {
39
        if ($this->allowedFields instanceof Collection) {
40
            // If we have allowed fields we will add them in the allowed fields method.
41
            return;
42
        }
43
44
        $this
45
            ->getRequestedFields()
46
            ->each(function (array $fields, string $table) {
0 ignored issues
show
Unused Code introduced by
The parameter $table is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
47
                return ColumnNameSanitizer::sanitizeArray($fields);
48
            });
49
50
        $this->addModelFieldsToQuery();
51
    }
52
53
    protected function getFieldsForRelatedTable(string $relation): array
54
    {
55
        // This method is being called from the `allowedIncludes` section of the query builder.
56
        // If `allowedIncludes` is called before `allowedFields` we don't know what fields to
57
        // sanitize yet so we'll sanitize all of them. This is an edge case that will be fixed
58
        // in version 2 of the package.
59
        // TL;DR: Put `allowedFields` before `allowedIncludes`
60
61
        $fields = $this->getRequestedFields()->get($relation, []);
62
63
        if ($this->allowedFields instanceof Collection) {
64
            // AllowedFields method has already sanitized for us.
65
66
            return $fields;
67
        }
68
69
        // Empty allowed fields means they're all allowed by default.
70
        // Sanitize all of them to be safe.
71
72
        return ColumnNameSanitizer::sanitizeArray($fields);
73
    }
74
75
// TEMP: Below this point is sanitized
76
77
    protected function getRequestedFields(): Collection
78
    {
79
        // We can't sanitize here yet because the sketchy fields might be allowed.
80
81
        return $this->request->fields();
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...
82
    }
83
84
    protected function guardAgainstUnknownFields()
85
    {
86
        $fields = $this->getRequestedFields()
87
            ->map(function ($fields, $model) {
88
                $tableName = Str::snake(preg_replace('/-/', '_', $model));
89
90
                $fields = array_map([Str::class, 'snake'], $fields);
91
92
                return $this->prependFieldsWithTableName($fields, $tableName);
93
            })
94
            ->flatten()
95
            ->unique();
96
97
        $diff = $fields->diff($this->allowedFields);
98
99
        if ($diff->count()) {
100
            throw InvalidFieldQuery::fieldsNotAllowed($diff, $this->allowedFields);
101
        }
102
    }
103
104
    protected function addModelFieldsToQuery()
105
    {
106
        $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...
107
108
        $modelFields = $this->getRequestedFields()->get($modelTableName);
109
110
        if (empty($modelFields)) {
111
            return;
112
        }
113
114
        $prependedFields = $this->prependFieldsWithTableName($modelFields, $modelTableName);
115
116
        $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...
117
    }
118
119
    protected function prependFieldsWithTableName(array $fields, string $tableName): array
120
    {
121
        return array_map(function ($field) use ($tableName) {
122
            return "{$tableName}.{$field}";
123
        }, $fields);
124
    }
125
}
126