Mappable   F
last analyzed

Complexity

Total Complexity 69

Size/Duplication

Total Lines 591
Duplicated Lines 3.72 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 69
lcom 1
cbo 8
dl 22
loc 591
rs 2.88
c 0
b 0
f 0

31 Methods

Rating   Name   Duplication   Size   Complexity  
A bootMappable() 0 15 2
A mappedQuery() 0 12 2
B mappedSelect() 0 37 6
A mappedRelationQuery() 0 10 2
A mappedJoinQuery() 0 12 3
A orderByMapped() 0 6 1
A listsMapped() 0 4 1
A pluckMapped() 0 12 2
A mappedSelectListsKey() 0 8 2
A joinMapped() 0 12 2
A joinSegment() 0 27 5
A alreadyJoined() 0 6 1
A getJoinKeys() 0 16 5
A mappedSingleResult() 0 4 1
A mappedHasQuery() 0 12 1
A getMappedWhereConstraint() 0 6 1
A getMappedBoolean() 0 8 1
A getMappedOperator() 0 12 4
A getMappingForAttribute() 0 6 2
A relationMapping() 0 4 1
A hasMapping() 0 8 2
A parseMappings() 0 12 3
A parseImplicitMapping() 0 6 2
A mapAttribute() 0 6 1
A getTarget() 0 12 3
A setMappedAttribute() 12 12 2
A addTargetToSave() 0 6 2
A saveMapped() 0 8 2
A forget() 10 10 2
A mutateAttributeForArray() 0 10 3
A getMaps() 0 4 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Mappable often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Mappable, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Sofa\Eloquence;
4
5
use LogicException;
6
use Illuminate\Support\Arr;
7
use Sofa\Eloquence\Mappable\Hooks;
8
use Sofa\Hookable\Contracts\ArgumentBag;
9
use Illuminate\Contracts\Support\Arrayable;
10
use Illuminate\Database\Eloquent\Relations\HasOne;
11
use Illuminate\Database\Eloquent\Relations\MorphTo;
12
use Illuminate\Database\Eloquent\Relations\MorphOne;
13
use Illuminate\Database\Eloquent\Relations\Relation;
14
use Illuminate\Database\Eloquent\Relations\BelongsTo;
15
use Illuminate\Database\Eloquent\Model as EloquentModel;
16
17
/**
18
 * @property array $maps
19
 */
20
trait Mappable
21
{
22
    /**
23
     * Flat array representation of mapped attributes.
24
     *
25
     * @var array
26
     */
27
    protected $mappedAttributes;
28
29
    /**
30
     * Related mapped objects to save along with the mappable instance.
31
     *
32
     * @var array
33
     */
34
    protected $targetsToSave = [];
35
36
    /**
37
     * Register hooks for the trait.
38
     *
39
     * @codeCoverageIgnore
40
     *
41
     * @return void
42
     */
43
    public static function bootMappable()
44
    {
45
        $hooks = new Hooks;
46
47
        foreach ([
48
                'getAttribute',
49
                'setAttribute',
50
                'save',
51
                '__isset',
52
                '__unset',
53
                'queryHook',
54
            ] as $method) {
55
            static::hook($method, $hooks->{$method}());
56
        }
57
    }
58
59
    /**
60
     * Custom query handler for querying mapped attributes.
61
     *
62
     * @param  \Sofa\Eloquence\Builder $query
63
     * @param  string $method
64
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
65
     * @return mixed
66
     */
67
    protected function mappedQuery(Builder $query, $method, ArgumentBag $args)
68
    {
69
        $mapping = $this->getMappingForAttribute($args->get('column'));
70
71
        if ($this->relationMapping($mapping)) {
72
            return $this->mappedRelationQuery($query, $method, $args, $mapping);
73
        }
74
75
        $args->set('column', $mapping);
76
77
        return $query->callParent($method, $args->all());
78
    }
79
80
    /**
81
     * Adjust mapped columns for select statement.
82
     *
83
     * @param  \Sofa\Eloquence\Builder $query
84
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
85
     * @return void
86
     */
87
    protected function mappedSelect(Builder $query, ArgumentBag $args)
88
    {
89
        $columns = $args->get('columns');
90
91
        foreach ($columns as $key => $column) {
92
            list($column, $as) = $this->extractColumnAlias($column);
0 ignored issues
show
Bug introduced by
It seems like extractColumnAlias() 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...
93
94
            // Each mapped column will be selected appropriately. If it's alias
95
            // then prefix it with current table and use original field name
96
            // otherwise join required mapped tables and select the field.
97
            if ($this->hasMapping($column)) {
98
                $mapping = $this->getMappingForAttribute($column);
99
100
                if ($this->relationMapping($mapping)) {
101
                    list($target, $mapped) = $this->parseMappedColumn($mapping);
0 ignored issues
show
Bug introduced by
It seems like parseMappedColumn() 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...
102
103
                    $table = $this->joinMapped($query, $target);
104
                } else {
105
                    list($table, $mapped) = [$this->getTable(), $mapping];
0 ignored issues
show
Bug introduced by
It seems like getTable() 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...
106
                }
107
108
                $columns[$key] = "{$table}.{$mapped}";
109
110
                if ($as !== $column) {
111
                    $columns[$key] .= " as {$as}";
112
                }
113
114
                // For non mapped columns present on this table we will simply
115
            // add the prefix, in order to avoid any column collisions,
116
            // that are likely to happen when we are joining tables.
117
            } elseif ($this->hasColumn($column)) {
0 ignored issues
show
Bug introduced by
It seems like hasColumn() 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...
118
                $columns[$key] = "{$this->getTable()}.{$column}";
0 ignored issues
show
Bug introduced by
It seems like getTable() 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...
119
            }
120
        }
121
122
        $args->set('columns', $columns);
123
    }
124
125
    /**
126
     * Handle querying relational mappings.
127
     *
128
     * @param  \Sofa\Eloquence\Builder $query
129
     * @param  string $method
130
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
131
     * @param  string $mapping
132
     * @return mixed
133
     */
134
    protected function mappedRelationQuery($query, $method, ArgumentBag $args, $mapping)
135
    {
136
        list($target, $column) = $this->parseMappedColumn($mapping);
0 ignored issues
show
Bug introduced by
It seems like parseMappedColumn() 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...
137
138
        if (in_array($method, ['pluck', 'value', 'aggregate', 'orderBy', 'lists'])) {
139
            return $this->mappedJoinQuery($query, $method, $args, $target, $column);
140
        }
141
142
        return $this->mappedHasQuery($query, $method, $args, $target, $column);
143
    }
144
145
    /**
146
     * Join mapped table(s) in order to call given method.
147
     *
148
     * @param  \Sofa\Eloquence\Builder $query
149
     * @param  string $method
150
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
151
     * @param  string $target
152
     * @param  string $column
153
     * @return mixed
154
     */
155
    protected function mappedJoinQuery($query, $method, ArgumentBag $args, $target, $column)
156
    {
157
        $table = $this->joinMapped($query, $target);
158
159
        // For aggregates we need the actual function name
160
        // so it can be called directly on the builder.
161
        $method = $args->get('function') ?: $method;
162
163
        return (in_array($method, ['orderBy', 'lists', 'pluck']))
164
            ? $this->{"{$method}Mapped"}($query, $args, $table, $column, $target)
165
            : $this->mappedSingleResult($query, $method, "{$table}.{$column}");
166
    }
167
168
    /**
169
     * Order query by mapped attribute.
170
     *
171
     * @param  \Sofa\Eloquence\Builder $query
172
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
173
     * @param  string $table
174
     * @param  string $column
175
     * @param  string $target
176
     * @return \Sofa\Eloquence\Builder
177
     */
178
    protected function orderByMapped(Builder $query, ArgumentBag $args, $table, $column, $target)
179
    {
180
        $query->with($target)->getQuery()->orderBy("{$table}.{$column}", $args->get('direction'));
181
182
        return $query;
183
    }
184
185
    /**
186
     * @param  \Sofa\Eloquence\Builder $query
187
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
188
     * @param  string $table
189
     * @param  string $column
190
     *
191
     * @return array
192
     */
193
    protected function listsMapped(Builder $query, ArgumentBag $args, $table, $column)
194
    {
195
        return $this->pluckMapped($query, $args, $table, $column);
196
    }
197
198
    /**
199
     * Get an array with the values of given mapped attribute.
200
     *
201
     * @param  \Sofa\Eloquence\Builder $query
202
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
203
     * @param  string $table
204
     * @param  string $column
205
     * @return array
206
     */
207
    protected function pluckMapped(Builder $query, ArgumentBag $args, $table, $column)
208
    {
209
        $query->select("{$table}.{$column}");
210
211
        if (!is_null($args->get('key'))) {
212
            $this->mappedSelectListsKey($query, $args->get('key'));
213
        }
214
215
        $args->set('column', $column);
216
217
        return $query->callParent('pluck', $args->all());
218
    }
219
220
    /**
221
     * Add select clause for key of the list array.
222
     *
223
     * @param  \Sofa\Eloquence\Builder $query
224
     * @param  string $key
225
     * @return \Sofa\Eloquence\Builder
226
     */
227
    protected function mappedSelectListsKey(Builder $query, $key)
228
    {
229
        if ($this->hasColumn($key)) {
0 ignored issues
show
Bug introduced by
It seems like hasColumn() 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...
230
            return $query->addSelect($this->getTable() . '.' . $key);
0 ignored issues
show
Bug introduced by
It seems like getTable() 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...
Bug introduced by
The method addSelect() does not exist on Sofa\Eloquence\Builder. Did you maybe mean select()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
231
        }
232
233
        return $query->addSelect($key);
0 ignored issues
show
Bug introduced by
The method addSelect() does not exist on Sofa\Eloquence\Builder. Did you maybe mean select()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
234
    }
235
236
    /**
237
     * Join mapped table(s).
238
     *
239
     * @param  \Sofa\Eloquence\Builder $query
240
     * @param  string $target
241
     * @return string
242
     */
243
    protected function joinMapped(Builder $query, $target)
244
    {
245
        $query->prefixColumnsForJoin();
246
247
        $parent = $this;
248
249
        foreach (explode('.', $target) as $segment) {
250
            list($table, $parent) = $this->joinSegment($query, $segment, $parent);
251
        }
252
253
        return $table;
0 ignored issues
show
Bug introduced by
The variable $table does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
254
    }
255
256
    /**
257
     * Join relation's table accordingly.
258
     *
259
     * @param  \Sofa\Eloquence\Builder $query
260
     * @param  string $segment
261
     * @param  \Illuminate\Database\Eloquent\Model $parent
262
     * @return array
263
     */
264
    protected function joinSegment(Builder $query, $segment, EloquentModel $parent)
265
    {
266
        $relation = $parent->{$segment}();
267
        $related = $relation->getRelated();
268
        $table = $related->getTable();
269
270
        // If the table has been already joined let's skip it. Otherwise we will left join
271
        // it in order to allow using some query methods on mapped columns. Polymorphic
272
        // relations require also additional constraints, so let's handle it as well.
273
        if (!$this->alreadyJoined($query, $table)) {
274
            list($fk, $pk) = $this->getJoinKeys($relation);
275
276
            $query->leftJoin($table, function ($join) use ($fk, $pk, $relation, $parent, $related) {
0 ignored issues
show
Bug introduced by
The call to leftJoin() misses some required arguments starting with $operator.
Loading history...
277
                $join->on($fk, '=', $pk);
278
279
                if ($relation instanceof MorphOne || $relation instanceof MorphTo) {
280
                    $morphClass = ($relation instanceof MorphOne)
281
                        ? $parent->getMorphClass()
282
                        : $related->getMorphClass();
283
284
                    $join->where($relation->getQualifiedMorphType(), '=', $morphClass);
0 ignored issues
show
Bug introduced by
The method getQualifiedMorphType does only exist in Illuminate\Database\Eloquent\Relations\MorphOne, but not in Illuminate\Database\Eloquent\Relations\MorphTo.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
285
                }
286
            });
287
        }
288
289
        return [$table, $related];
290
    }
291
292
    /**
293
     * Determine whether given table has been already joined.
294
     *
295
     * @param  \Sofa\Eloquence\Builder $query
296
     * @param  string  $table
297
     * @return bool
298
     */
299
    protected function alreadyJoined(Builder $query, $table)
300
    {
301
        $joined = Arr::pluck((array) $query->getQuery()->joins, 'table');
0 ignored issues
show
Documentation introduced by
(array) $query->getQuery()->joins is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
302
303
        return in_array($table, $joined);
304
    }
305
306
    /**
307
     * Get the keys from relation in order to join the table.
308
     *
309
     * @param  \Illuminate\Database\Eloquent\Relations\Relation $relation
310
     * @return array
311
     *
312
     * @throws \LogicException
313
     */
314
    protected function getJoinKeys(Relation $relation)
315
    {
316
        if ($relation instanceof HasOne || $relation instanceof MorphOne) {
317
            return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedParentKeyName()];
318
        }
319
320
        if ($relation instanceof BelongsTo && !$relation instanceof MorphTo) {
321
            return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedOwnerKeyName()];
322
        }
323
324
        $class = get_class($relation);
325
326
        throw new LogicException(
327
            "Only HasOne, MorphOne and BelongsTo mappings can be queried. {$class} given."
328
        );
329
    }
330
331
    /**
332
     * Get single value result from the mapped attribute.
333
     *
334
     * @param  \Sofa\Eloquence\Builder $query
335
     * @param  string $method
336
     * @param  string $qualifiedColumn
337
     * @return mixed
338
     */
339
    protected function mappedSingleResult(Builder $query, $method, $qualifiedColumn)
340
    {
341
        return $query->getQuery()->select("{$qualifiedColumn}")->{$method}("{$qualifiedColumn}");
342
    }
343
344
    /**
345
     * Add whereHas subquery on the mapped attribute relation.
346
     *
347
     * @param  \Sofa\Eloquence\Builder $query
348
     * @param  string $method
349
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
350
     * @param  string $target
351
     * @param  string $column
352
     * @return \Sofa\Eloquence\Builder
353
     */
354
    protected function mappedHasQuery(Builder $query, $method, ArgumentBag $args, $target, $column)
355
    {
356
        $boolean = $this->getMappedBoolean($args);
357
358
        $operator = $this->getMappedOperator($method, $args);
359
360
        $args->set('column', $column);
361
362
        return $query
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloq...ns\QueriesRelationships.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
363
            ->has($target, $operator, 1, $boolean, $this->getMappedWhereConstraint($method, $args))
364
            ->with($target);
365
    }
366
367
    /**
368
     * Get the relation constraint closure.
369
     *
370
     * @param  string $method
371
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
372
     * @return \Closure
373
     */
374
    protected function getMappedWhereConstraint($method, ArgumentBag $args)
375
    {
376
        return function ($query) use ($method, $args) {
377
            call_user_func_array([$query, $method], $args->all());
378
        };
379
    }
380
381
    /**
382
     * Get boolean called on the original method and set it to default.
383
     *
384
     * @param  \Sofa\EloquenceArgumentBag $args
385
     * @return string
386
     */
387
    protected function getMappedBoolean(ArgumentBag $args)
388
    {
389
        $boolean = $args->get('boolean');
390
391
        $args->set('boolean', 'and');
392
393
        return $boolean;
394
    }
395
396
    /**
397
     * Determine the operator for count relation query and set 'not' appropriately.
398
     *
399
     * @param  string $method
400
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
401
     * @return string
402
     */
403
    protected function getMappedOperator($method, ArgumentBag $args)
404
    {
405
        if ($not = $args->get('not')) {
406
            $args->set('not', false);
407
        }
408
409
        if ($null = $this->isWhereNull($method, $args)) {
0 ignored issues
show
Bug introduced by
It seems like isWhereNull() 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...
410
            $args->set('not', true);
411
        }
412
413
        return ($not ^ $null) ? '<' : '>=';
414
    }
415
416
    /**
417
     * Get the mapping key.
418
     *
419
     * @param  string $key
420
     * @return string|null
421
     */
422
    public function getMappingForAttribute($key)
423
    {
424
        if ($this->hasMapping($key)) {
425
            return $this->mappedAttributes[$key];
426
        }
427
    }
428
429
    /**
430
     * Determine whether the mapping points to relation.
431
     *
432
     * @param  string $mapping
433
     * @return bool
434
     */
435
    protected function relationMapping($mapping)
436
    {
437
        return strpos($mapping, '.') !== false;
438
    }
439
440
    /**
441
     * Determine whether a mapping exists for an attribute.
442
     *
443
     * @param  string $key
444
     * @return bool
445
     */
446
    public function hasMapping($key)
447
    {
448
        if (is_null($this->mappedAttributes)) {
449
            $this->parseMappings();
450
        }
451
452
        return array_key_exists((string) $key, $this->mappedAttributes);
453
    }
454
455
    /**
456
     * Parse defined mappings into flat array.
457
     *
458
     * @return void
459
     */
460
    protected function parseMappings()
461
    {
462
        $this->mappedAttributes = [];
463
464
        foreach ($this->getMaps() as $attribute => $mapping) {
465
            if (is_array($mapping)) {
466
                $this->parseImplicitMapping($mapping, $attribute);
467
            } else {
468
                $this->mappedAttributes[$attribute] = $mapping;
469
            }
470
        }
471
    }
472
473
    /**
474
     * Parse implicit mappings.
475
     *
476
     * @param  array  $attributes
477
     * @param  string $target
478
     * @return void
479
     */
480
    protected function parseImplicitMapping($attributes, $target)
481
    {
482
        foreach ($attributes as $attribute) {
483
            $this->mappedAttributes[$attribute] = "{$target}.{$attribute}";
484
        }
485
    }
486
487
    /**
488
     * Map an attribute to a value.
489
     *
490
     * @param  string $key
491
     * @return mixed
492
     */
493
    protected function mapAttribute($key)
494
    {
495
        $segments = explode('.', $this->getMappingForAttribute($key));
496
497
        return $this->getTarget($this, $segments);
498
    }
499
500
    /**
501
     * Get mapped value.
502
     *
503
     * @param  \Illuminate\Database\Eloquent\Model $target
504
     * @param  array  $segments
505
     * @return mixed
506
     */
507
    protected function getTarget($target, array $segments)
508
    {
509
        foreach ($segments as $segment) {
510
            if (!$target) {
511
                return;
512
            }
513
514
            $target = $target->{$segment};
515
        }
516
517
        return $target;
518
    }
519
520
    /**
521
     * Set value of a mapped attribute.
522
     *
523
     * @param string $key
524
     * @param mixed  $value
525
     */
526 View Code Duplication
    protected function setMappedAttribute($key, $value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
527
    {
528
        $segments = explode('.', $this->getMappingForAttribute($key));
529
530
        $attribute = array_pop($segments);
531
532
        if ($target = $this->getTarget($this, $segments)) {
533
            $this->addTargetToSave($target);
534
535
            $target->{$attribute} = $value;
536
        }
537
    }
538
539
    /**
540
     * Flag mapped model to be saved along with this model.
541
     *
542
     * @param \Illuminate\Database\Eloquent\Model $target
543
     */
544
    protected function addTargetToSave($target)
545
    {
546
        if ($this !== $target) {
547
            $this->targetsToSave[] = $target;
548
        }
549
    }
550
551
    /**
552
     * Save mapped relations.
553
     *
554
     * @return void
555
     */
556
    protected function saveMapped()
557
    {
558
        foreach (array_unique($this->targetsToSave) as $target) {
559
            $target->save();
560
        }
561
562
        $this->targetsToSave = [];
563
    }
564
565
    /**
566
     * Unset mapped attribute.
567
     *
568
     * @param  string $key
569
     * @return void
570
     */
571 View Code Duplication
    protected function forget($key)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
572
    {
573
        $mapping = $this->getMappingForAttribute($key);
574
575
        list($target, $attribute) = $this->parseMappedColumn($mapping);
0 ignored issues
show
Bug introduced by
It seems like parseMappedColumn() 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...
576
577
        $target = $target ? $this->getTarget($this, explode('.', $target)) : $this;
578
579
        unset($target->{$attribute});
580
    }
581
582
    /**
583
     * @codeCoverageIgnore
584
     *
585
     * @param  string  $key
586
     * @param  mixed  $value
587
     *
588
     * @inheritdoc
589
     */
590
    protected function mutateAttributeForArray($key, $value)
591
    {
592
        if ($this->hasMapping($key)) {
593
            $value = $this->mapAttribute($key);
594
595
            return $value instanceof Arrayable ? $value->toArray() : $value;
596
        }
597
598
        return parent::mutateAttributeForArray($key, $value);
599
    }
600
601
    /**
602
     * Get the array of attribute mappings.
603
     *
604
     * @return array
605
     */
606
    public function getMaps()
607
    {
608
        return (property_exists($this, 'maps')) ? $this->maps : [];
609
    }
610
}
611