Completed
Pull Request — 5.1 (#45)
by
unknown
04:59
created

Mappable::getMappedBoolean()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4286
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Sofa\Eloquence;
4
5
use LogicException;
6
use Sofa\Eloquence\Mappable\Hooks;
7
use Sofa\Hookable\Contracts\ArgumentBag;
8
use Illuminate\Contracts\Support\Arrayable;
9
use Illuminate\Database\Eloquent\Relations\HasOne;
10
use Illuminate\Database\Eloquent\Relations\MorphTo;
11
use Illuminate\Database\Eloquent\Relations\MorphOne;
12
use Illuminate\Database\Eloquent\Relations\Relation;
13
use Illuminate\Database\Eloquent\Relations\BelongsTo;
14
use Illuminate\Database\Eloquent\Model as EloquentModel;
15
16
/**
17
 * @property array $maps
18
 */
19
trait Mappable
20
{
21
    /**
22
     * Flat array representation of mapped attributes.
23
     *
24
     * @var array
25
     */
26
    protected static $mappedAttributes;
27
28
    /**
29
     * Related mapped objects to save along with the mappable instance.
30
     *
31
     * @var array
32
     */
33
    protected $targetsToSave = [];
34
35
    /**
36
     * Register hooks for the trait.
37
     *
38
     * @codeCoverageIgnore
39
     *
40
     * @return void
41
     */
42 View Code Duplication
    public static function bootMappable()
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...
43
    {
44
        $hooks = new Hooks;
45
46
        foreach ([
47
                'getAttribute',
48
                'setAttribute',
49
                'save',
50
                '__isset',
51
                '__unset',
52
                'queryHook',
53
                'toArray'
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\Eloquence\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\Eloquence\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) = $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
            // For non mapped columns present on this table we will simply
111
            // add the prefix, in order to avoid any column collisions,
112
            // that are likely to happen when we are joining tables.
113
            } 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...
114
                $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...
115
            }
116
        }
117
118
        $args->set('columns', $columns);
119
    }
120
121
    /**
122
     * Handle querying relational mappings.
123
     *
124
     * @param  \Sofa\Eloquence\Builder $query
125
     * @param  string $method
126
     * @param  \Sofa\Eloquence\ArgumentBag $args
127
     * @param  string $mapping
128
     * @return mixed
129
     */
130
    protected function mappedRelationQuery($query, $method, ArgumentBag $args, $mapping)
131
    {
132
        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...
133
134 View Code Duplication
        if (in_array($method, ['pluck', 'value', 'aggregate', 'orderBy', 'lists'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
135
            return $this->mappedJoinQuery($query, $method, $args, $target, $column);
136
        }
137
138
        return $this->mappedHasQuery($query, $method, $args, $target, $column);
139
    }
140
141
    /**
142
     * Join mapped table(s) in order to call given method.
143
     *
144
     * @param  \Sofa\Eloquence\Builder $query
145
     * @param  string $method
146
     * @param  \Sofa\Eloquence\ArgumentBag $args
147
     * @param  string $target
148
     * @param  string $column
149
     * @return mixed
150
     */
151
    protected function mappedJoinQuery($query, $method, ArgumentBag $args, $target, $column)
152
    {
153
        $table = $this->joinMapped($query, $target);
154
155
        // For aggregates we need the actual function name
156
        // so it can be called directly on the builder.
157
        $method = $args->get('function') ?: $method;
158
159
        return (in_array($method, ['orderBy', 'lists']))
160
            ? $this->{"{$method}Mapped"}($query, $args, $table, $column, $target)
161
            : $this->mappedSingleResult($query, $method, "{$table}.{$column}");
162
    }
163
164
    /**
165
     * Order query by mapped attribute.
166
     *
167
     * @param  \Sofa\Eloquence\Builder $query
168
     * @param  \Sofa\Eloquence\ArgumentBag $args
169
     * @param  string $table
170
     * @param  string $column
171
     * @param  string $target
172
     * @return \Sofa\Eloquence\Builder
173
     */
174
    protected function orderByMapped(Builder $query, ArgumentBag $args, $table, $column, $target)
175
    {
176
        $query->with($target)->getQuery()->orderBy("{$table}.{$column}", $args->get('direction'));
177
178
        return $query;
179
    }
180
181
    /**
182
     * Get an array with the values of given mapped attribute.
183
     *
184
     * @param  \Sofa\Eloquence\Builder $query
185
     * @param  \Sofa\Eloquence\ArgumentBag $args
186
     * @param  string $table
187
     * @param  string $column
188
     * @return array
189
     */
190
    protected function listsMapped(Builder $query, ArgumentBag $args, $table, $column)
191
    {
192
        $query->select("{$table}.{$column}");
193
194
        if (!is_null($args->get('key'))) {
195
            $this->mappedSelectListsKey($query, $args->get('key'));
196
        }
197
198
        $args->set('column', $column);
199
200
        return $query->callParent('lists', $args->all());
201
    }
202
203
    /**
204
     * Add select clause for key of the list array.
205
     *
206
     * @param  \Sofa\Eloquence\Builder $query
207
     * @param  string $key
208
     * @return \Sofa\Eloquence\Builder
209
     */
210
    protected function mappedSelectListsKey(Builder $query, $key)
211
    {
212
        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...
213
            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...
214
        }
215
216
        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...
217
    }
218
219
    /**
220
     * Join mapped table(s).
221
     *
222
     * @param  \Sofa\Eloquence\Builder $query
223
     * @param  string $target
224
     * @return string
225
     */
226
    protected function joinMapped(Builder $query, $target)
227
    {
228
        $query->prefixColumnsForJoin();
229
230
        $parent = $this;
231
232
        foreach (explode('.', $target) as $segment) {
233
            list($table, $parent) = $this->joinSegment($query, $segment, $parent);
234
        }
235
236
        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...
237
    }
238
239
    /**
240
     * Join relation's table accordingly.
241
     *
242
     * @param  \Sofa\Eloquence\Builder $query
243
     * @param  string $segment
244
     * @param  \Illuminate\Database\Eloquent\Model $parent
245
     * @return array
246
     */
247
    protected function joinSegment(Builder $query, $segment, EloquentModel $parent)
248
    {
249
        $relation = $parent->{$segment}();
250
        $related  = $relation->getRelated();
251
        $table    = $related->getTable();
252
253
        // If the table has been already joined let's skip it. Otherwise we will left join
254
        // it in order to allow using some query methods on mapped columns. Polymorphic
255
        // relations require also additional constraints, so let's handle it as well.
256
        if (!$this->alreadyJoined($query, $table)) {
257
            list($fk, $pk) = $this->getJoinKeys($relation);
258
259
            $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...
260
                $join->on($fk, '=', $pk);
261
262
                if ($relation instanceof MorphOne || $relation instanceof MorphTo) {
263
                    $morphClass = ($relation instanceof MorphOne)
264
                        ? $parent->getMorphClass()
265
                        : $related->getMorphClass();
266
267
                    $join->where($relation->getMorphType(), '=', $morphClass);
268
                }
269
            });
270
        }
271
272
        return [$table, $related];
273
    }
274
275
    /**
276
     * Determine whether given table has been already joined.
277
     *
278
     * @param  \Sofa\Eloquence\Builder $query
279
     * @param  string  $table
280
     * @return boolean
281
     */
282
    protected function alreadyJoined(Builder $query, $table)
283
    {
284
        $joined = array_fetch((array) $query->getQuery()->joins, 'table');
0 ignored issues
show
Deprecated Code introduced by
The function array_fetch() has been deprecated with message: since version 5.1. Use array_pluck instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
285
286
        return in_array($table, $joined);
287
    }
288
289
    /**
290
     * Get the keys from relation in order to join the table.
291
     *
292
     * @param  \Illuminate\Database\Eloquent\Relations\Relation $relation
293
     * @return array
294
     *
295
     * @throws \LogicException
296
     */
297
    protected function getJoinKeys(Relation $relation)
298
    {
299
        if ($relation instanceof HasOne || $relation instanceof MorphOne) {
300
            return [$relation->getForeignKey(), $relation->getQualifiedParentKeyName()];
301
        }
302
303
        if ($relation instanceof BelongsTo && !$relation instanceof MorphTo) {
304
            return [$relation->getQualifiedForeignKey(), $relation->getQualifiedOtherKeyName()];
305
        }
306
307
        $class = get_class($relation);
308
309
        throw new LogicException(
310
            "Only HasOne, MorphOne and BelongsTo mappings can be queried. {$class} given."
311
        );
312
    }
313
314
    /**
315
     * Get single value result from the mapped attribute.
316
     *
317
     * @param  \Sofa\Eloquence\Builder $query
318
     * @param  string $method
319
     * @param  string $qualifiedColumn
320
     * @return mixed
321
     */
322
    protected function mappedSingleResult(Builder $query, $method, $qualifiedColumn)
323
    {
324
        return $query->getQuery()->select("{$qualifiedColumn}")->{$method}("{$qualifiedColumn}");
325
    }
326
327
    /**
328
     * Add whereHas subquery on the mapped attribute relation.
329
     *
330
     * @param  \Sofa\Eloquence\Builder $query
331
     * @param  string $method
332
     * @param  \Sofa\Eloquence\ArgumentBag $args
333
     * @param  string $target
334
     * @param  string $column
335
     * @return \Sofa\Eloquence\Builder
336
     */
337
    protected function mappedHasQuery(Builder $query, $method, ArgumentBag $args, $target, $column)
338
    {
339
        $boolean = $this->getMappedBoolean($args);
340
341
        $operator = $this->getMappedOperator($method, $args);
342
343
        $args->set('column', $column);
344
345
        return $query
346
            ->has($target, $operator, 1, $boolean, $this->getMappedWhereConstraint($method, $args))
347
            ->with($target);
348
    }
349
350
    /**
351
     * Get the relation constraint closure.
352
     *
353
     * @param  string $method
354
     * @param  \Sofa\Eloquence\ArgumentBag $args
355
     * @return \Closure
356
     */
357
    protected function getMappedWhereConstraint($method, ArgumentBag $args)
358
    {
359
        return function ($query) use ($method, $args) {
360
            call_user_func_array([$query, $method], $args->all());
361
        };
362
    }
363
364
    /**
365
     * Get boolean called on the original method and set it to default.
366
     *
367
     * @param  \Sofa\EloquenceArgumentBag $args
368
     * @return string
369
     */
370
    protected function getMappedBoolean(ArgumentBag $args)
371
    {
372
        $boolean = $args->get('boolean');
373
374
        $args->set('boolean', 'and');
375
376
        return $boolean;
377
    }
378
379
    /**
380
     * Determine the operator for count relation query and set 'not' appropriately.
381
     *
382
     * @param  string $method
383
     * @param  \Sofa\Eloquence\ArgumentBag $args
384
     * @return string
385
     */
386
    protected function getMappedOperator($method, ArgumentBag $args)
387
    {
388
        if ($not = $args->get('not')) {
389
            $args->set('not', false);
390
        }
391
392
        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...
393
            $args->set('not', true);
394
        }
395
396
        return ($not ^ $null) ? '<' : '>=';
397
    }
398
399
    /**
400
     * Get the mapping key.
401
     *
402
     * @param  string $key
403
     * @return string|null
404
     */
405
    public function getMappingForAttribute($key)
406
    {
407
        if ($this->hasMapping($key)) {
408
            return static::$mappedAttributes[$key];
409
        }
410
    }
411
412
    /**
413
     * Determine whether the mapping points to relation.
414
     *
415
     * @param  string $mapping
416
     * @return boolean
417
     */
418
    protected function relationMapping($mapping)
419
    {
420
        return strpos($mapping, '.') !== false;
421
    }
422
423
    /**
424
     * Determine whether a mapping exists for an attribute.
425
     *
426
     * @param  string $key
427
     * @return boolean
428
     */
429
    public function hasMapping($key)
430
    {
431
        if (is_null(static::$mappedAttributes)) {
432
            $this->parseMappings();
433
        }
434
435
        return array_key_exists((string)$key, static::$mappedAttributes);
436
    }
437
438
    /**
439
     * Parse defined mappings into flat array.
440
     *
441
     * @return void
442
     */
443
    protected function parseMappings()
444
    {
445
        static::$mappedAttributes = [];
446
447
        foreach ($this->getMaps() as $attribute => $mapping) {
448
            if (is_array($mapping)) {
449
                $this->parseImplicitMapping($mapping, $attribute);
450
            } else {
451
                static::$mappedAttributes[$attribute] = $mapping;
452
            }
453
        }
454
    }
455
456
    /**
457
     * Parse implicit mappings.
458
     *
459
     * @param  array  $attributes
460
     * @param  string $target
461
     * @return void
462
     */
463
    protected function parseImplicitMapping($attributes, $target)
464
    {
465
        foreach ($attributes as $attribute) {
466
            static::$mappedAttributes[$attribute] = "{$target}.{$attribute}";
467
        }
468
    }
469
470
    /**
471
     * Map an attribute to a value.
472
     *
473
     * @param  string $key
474
     * @return mixed
475
     */
476
    protected function mapAttribute($key)
477
    {
478
        $segments = explode('.', $this->getMappingForAttribute($key));
479
480
        return $this->getTarget($this, $segments);
481
    }
482
483
    /**
484
     * Determine whether a column is mapped.
485
     *
486
     * @param $column
487
     * @return string
488
     */
489
    public function isMapping($column)
490
    {
491
        if (is_null(static::$mappedAttributes)) {
492
            $this->parseMappings();
493
        }
494
        return array_search($column, static::$mappedAttributes);
495
    }
496
    /**
497
     * Get mapped value.
498
     *
499
     * @param  \Illuminate\Database\Eloquent\Model $target
500
     * @param  array  $segments
501
     * @return mixed
502
     */
503
    protected function getTarget($target, array $segments)
504
    {
505
        foreach ($segments as $segment) {
506
            if (!$target) {
507
                return;
508
            }
509
510
            $target = $target->{$segment};
511
        }
512
513
        return $target;
514
    }
515
516
    /**
517
     * Set value of a mapped attribute.
518
     *
519
     * @param string $key
520
     * @param mixed  $value
521
     */
522 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...
523
    {
524
        $segments = explode('.', $this->getMappingForAttribute($key));
525
526
        $attribute = array_pop($segments);
527
528
        if ($target = $this->getTarget($this, $segments)) {
529
            $this->addTargetToSave($target);
530
531
            $target->{$attribute} = $value;
532
        }
533
    }
534
535
    /**
536
     * Flag mapped model to be saved along with this model.
537
     *
538
     * @param \Illuminate\Database\Eloquent\Model $target
539
     */
540
    protected function addTargetToSave($target)
541
    {
542
        if ($this !== $target) {
543
            $this->targetsToSave[] = $target;
544
        }
545
    }
546
547
    /**
548
     * Save mapped relations.
549
     *
550
     * @return void
551
     */
552
    protected function saveMapped()
553
    {
554
        foreach (array_unique($this->targetsToSave) as $target) {
555
            $target->save();
556
        }
557
558
        $this->targetsToSave = [];
559
    }
560
561
    /**
562
     * Unset mapped attribute.
563
     *
564
     * @param  string $key
565
     * @return void
566
     */
567 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...
568
    {
569
        $mapping = $this->getMappingForAttribute($key);
570
571
        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...
572
573
        $target = $target ? $this->getTarget($this, explode('.', $target)) : $this;
574
575
        unset($target->{$attribute});
576
    }
577
578
    /**
579
     * @codeCoverageIgnore
580
     *
581
     * @inheritdoc
582
     */
583
    protected function mutateAttributeForArray($key, $value)
584
    {
585
        if ($this->hasMapping($key)) {
586
            $value = $this->mapAttribute($key);
587
588
            return $value instanceof Arrayable ? $value->toArray() : $value;
589
        }
590
591
        return parent::mutateAttributeForArray($key, $value);
592
    }
593
594
    /**
595
     * Get the array of attribute mappings.
596
     *
597
     * @return array
598
     */
599
    public function getMaps()
600
    {
601
        return (property_exists($this, 'maps')) ? $this->maps : [];
602
    }
603
}
604