Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Test Setup Failed
Pull Request — master (#3250)
by Cristian
16:59 queued 42s
created

Relationships::isNestedRelation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Arr;
7
use Illuminate\Support\Str;
8
9
trait Relationships
10
{
11
    /**
12
     * From the field entity we get the relation instance.
13
     *
14
     * @param array $entity
15
     * @return object
16
     */
17
    public function getRelationInstance($field)
18
    {
19
        $entity = $this->getOnlyRelationEntity($field);
0 ignored issues
show
Bug introduced by
It seems like getOnlyRelationEntity() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

19
        /** @scrutinizer ignore-call */ 
20
        $entity = $this->getOnlyRelationEntity($field);
Loading history...
20
        $entity_array = explode('.', $entity);
21
        $relation_model = $this->getRelationModel($entity);
0 ignored issues
show
Bug introduced by
The method getRelationModel() does not exist on Backpack\CRUD\app\Librar...el\Traits\Relationships. Did you maybe mean getRelationInstance()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

21
        /** @scrutinizer ignore-call */ 
22
        $relation_model = $this->getRelationModel($entity);

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...
22
23
        $related_method = Arr::last($entity_array);
24
        if (count(explode('.', $entity)) == count(explode('.', $field['entity']))) {
25
            $relation_model = $this->getRelationModel($entity, -1);
26
        }
27
        $relation_model = new $relation_model();
28
29
        //if counts are diferent means that last element of entity is the field in relation.
30
        if (count(explode('.', $entity)) != count(explode('.', $field['entity']))) {
31
            if (in_array($related_method, $relation_model->getFillable())) {
32
                if (count($entity_array) > 1) {
33
                    $related_method = $entity_array[(count($entity_array) - 2)];
34
                    $relation_model = $this->getRelationModel($entity, -2);
35
                } else {
36
                    $relation_model = $this->model;
37
                }
38
            }
39
        }
40
        if (count($entity_array) == 1) {
41
            if (method_exists($this->model, $related_method)) {
42
                return $this->model->{$related_method}();
43
            }
44
        }
45
46
        return $relation_model->{$related_method}();
47
    }
48
49
    /**
50
     * Get the fields with specific relation types that are not nested relations.
51
     *
52
     * @param array|string $relation_types
53
     *
54
     * @return array The fields with corresponding relation types.
55
     */
56
    public function getFieldsWithRelationType($relation_types): array
57
    {
58
        $relation_types = is_array($relation_types) ?: (array) $relation_types;
59
60
        return collect($this->fields())
0 ignored issues
show
Bug introduced by
It seems like fields() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

60
        return collect($this->/** @scrutinizer ignore-call */ fields())
Loading history...
61
            ->where('model')
62
            ->whereIn('relation_type', $relation_types)
63
            ->filter(function ($item) {
64
                return Str::contains($item['entity'], '.') && $item['model'] !== get_class($this->model->{Arr::first(explode('.', $item['entity']))}()->getRelated()) ? false : true;
65
            })
66
            ->toArray();
67
    }
68
69
    /**
70
     * Grabs an relation instance and returns the class name of the related model.
71
     *
72
     * @param array $field
73
     * @return string
74
     */
75
    public function inferFieldModelFromRelationship($field)
76
    {
77
        $relation = $this->getRelationInstance($field);
78
79
        return get_class($relation->getRelated());
80
    }
81
82
    /**
83
     * Return the relation type from a given field: BelongsTo, HasOne ... etc.
84
     *
85
     * @param array $field
86
     * @return string
87
     */
88
    public function inferRelationTypeFromRelationship($field)
89
    {
90
        $relation = $this->getRelationInstance($field);
91
92
        return Arr::last(explode('\\', get_class($relation)));
93
    }
94
95
    /**
96
     * Parse the field name back to the related entity after the form is submited.
97
     * Its called in getAllFieldNames().
98
     *
99
     * @param array $fields
100
     * @return array
101
     */
102
    public function parseRelationFieldNamesFromHtml($fields)
103
    {
104
        foreach ($fields as &$field) {
105
            //we only want to parse fields that has a relation type and their name contains [ ] used in html.
106
            if (isset($field['relation_type']) && preg_match('/[\[\]]/', $field['name']) !== 0) {
107
                $chunks = explode('[', $field['name']);
108
109
                foreach ($chunks as &$chunk) {
110
                    if (strpos($chunk, ']')) {
111
                        $chunk = str_replace(']', '', $chunk);
112
                    }
113
                }
114
                $field['name'] = implode('.', $chunks);
115
            }
116
        }
117
118
        return $fields;
119
    }
120
121
    /**
122
     * Based on relation type returns the default field type.
123
     *
124
     * @param string $relation_type
125
     * @return bool
126
     */
127
    public function inferFieldTypeFromFieldRelation($field)
128
    {
129
        switch ($field['relation_type']) {
130
            case 'BelongsToMany':
131
            case 'HasMany':
132
            case 'HasManyThrough':
133
            case 'MorphMany':
134
            case 'MorphToMany':
135
            case 'BelongsTo':
136
                return 'relationship';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'relationship' returns the type string which is incompatible with the documented return type boolean.
Loading history...
137
138
            default:
139
                return 'text';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'text' returns the type string which is incompatible with the documented return type boolean.
Loading history...
140
        }
141
    }
142
143
    /**
144
     * Based on relation type returns if relation allows multiple entities.
145
     *
146
     * @param string $relation_type
147
     * @return bool
148
     */
149
    public function guessIfFieldHasMultipleFromRelationType($relation_type)
150
    {
151
        switch ($relation_type) {
152
            case 'BelongsToMany':
153
            case 'HasMany':
154
            case 'HasManyThrough':
155
            case 'HasOneOrMany':
156
            case 'MorphMany':
157
            case 'MorphOneOrMany':
158
            case 'MorphToMany':
159
                return true;
160
161
            default:
162
                return false;
163
        }
164
    }
165
166
    /**
167
     * Based on relation type returns if relation has a pivot table.
168
     *
169
     * @param string $relation_type
170
     * @return bool
171
     */
172
    public function guessIfFieldHasPivotFromRelationType($relation_type)
173
    {
174
        switch ($relation_type) {
175
            case 'BelongsToMany':
176
            case 'HasManyThrough':
177
            case 'MorphMany':
178
            case 'MorphOneOrMany':
179
            case 'MorphToMany':
180
                return true;
181
            default:
182
                return false;
183
        }
184
    }
185
186
    /**
187
     * Check if field name contains a dot, if so, meaning it's a nested relation.
188
     *
189
     * @param array $field
190
     * @return bool
191
     */
192
    protected function isNestedRelation($field): bool
193
    {
194
        if (strpos($field['entity'], '.') !== false) {
195
            return true;
196
        }
197
198
        return false;
199
    }
200
201
    /**
202
     * Associate and dissociate BelongsTo relations in the model.
203
     *
204
     * @param  Model
205
     * @param  array The form data.
0 ignored issues
show
Bug introduced by
The type Backpack\CRUD\app\Library\CrudPanel\Traits\The was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
206
     * @return Model Model with relationships set up.
207
     */
208
    public function associateOrDissociateBelongsToRelations($item, array $data)
209
    {
210
        $belongsToFields = $this->getFieldsWithRelationType('BelongsTo');
211
212
        foreach ($belongsToFields as $relationField) {
213
            if (method_exists($item, $this->getOnlyRelationEntity($relationField))) {
214
                $relatedId = Arr::get($data, $relationField['name']);
215
                $related = $relationField['model']::find($relatedId);
216
217
                $item->{$this->getOnlyRelationEntity($relationField)}()->associate($related);
218
            }
219
        }
220
221
        return $item;
222
    }
223
}
224