Issues (107)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Mappable.php (18 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 View Code Duplication
    public static function bootMappable()
0 ignored issues
show
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...
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
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
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
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
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
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
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 View Code Duplication
        if (in_array($method, ['pluck', 'value', 'aggregate', 'orderBy', 'lists'])) {
0 ignored issues
show
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...
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
    protected function listsMapped(Builder $query, ArgumentBag $args, $table, $column)
186
    {
187
        return $this->pluckMapped($query, $args, $table, $column);
188
    }
189
190
    /**
191
     * Get an array with the values of given mapped attribute.
192
     *
193
     * @param  \Sofa\Eloquence\Builder $query
194
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
195
     * @param  string $table
196
     * @param  string $column
197
     * @return array
198
     */
199
    protected function pluckMapped(Builder $query, ArgumentBag $args, $table, $column)
200
    {
201
        $query->select("{$table}.{$column}");
202
203
        if (!is_null($args->get('key'))) {
204
            $this->mappedSelectListsKey($query, $args->get('key'));
205
        }
206
207
        $args->set('column', $column);
208
209
        return $query->callParent('pluck', $args->all());
210
    }
211
212
    /**
213
     * Add select clause for key of the list array.
214
     *
215
     * @param  \Sofa\Eloquence\Builder $query
216
     * @param  string $key
217
     * @return \Sofa\Eloquence\Builder
218
     */
219
    protected function mappedSelectListsKey(Builder $query, $key)
220
    {
221
        if ($this->hasColumn($key)) {
0 ignored issues
show
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...
222
            return $query->addSelect($this->getTable() . '.' . $key);
0 ignored issues
show
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...
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...
223
        }
224
225
        return $query->addSelect($key);
0 ignored issues
show
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...
226
    }
227
228
    /**
229
     * Join mapped table(s).
230
     *
231
     * @param  \Sofa\Eloquence\Builder $query
232
     * @param  string $target
233
     * @return string
234
     */
235
    protected function joinMapped(Builder $query, $target)
236
    {
237
        $query->prefixColumnsForJoin();
238
239
        $parent = $this;
240
241
        foreach (explode('.', $target) as $segment) {
242
            list($table, $parent) = $this->joinSegment($query, $segment, $parent);
243
        }
244
245
        return $table;
0 ignored issues
show
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...
246
    }
247
248
    /**
249
     * Join relation's table accordingly.
250
     *
251
     * @param  \Sofa\Eloquence\Builder $query
252
     * @param  string $segment
253
     * @param  \Illuminate\Database\Eloquent\Model $parent
254
     * @return array
255
     */
256
    protected function joinSegment(Builder $query, $segment, EloquentModel $parent)
257
    {
258
        $relation = $parent->{$segment}();
259
        $related  = $relation->getRelated();
260
        $table    = $related->getTable();
261
262
        // If the table has been already joined let's skip it. Otherwise we will left join
263
        // it in order to allow using some query methods on mapped columns. Polymorphic
264
        // relations require also additional constraints, so let's handle it as well.
265
        if (!$this->alreadyJoined($query, $table)) {
266
            list($fk, $pk) = $this->getJoinKeys($relation);
267
268
            $query->leftJoin($table, function ($join) use ($fk, $pk, $relation, $parent, $related) {
0 ignored issues
show
The call to leftJoin() misses some required arguments starting with $operator.
Loading history...
269
                $join->on($fk, '=', $pk);
270
271
                if ($relation instanceof MorphOne || $relation instanceof MorphTo) {
272
                    $morphClass = ($relation instanceof MorphOne)
273
                        ? $parent->getMorphClass()
274
                        : $related->getMorphClass();
275
276
                    $join->where($relation->getMorphType(), '=', $morphClass);
277
                }
278
            });
279
        }
280
281
        return [$table, $related];
282
    }
283
284
    /**
285
     * Determine whether given table has been already joined.
286
     *
287
     * @param  \Sofa\Eloquence\Builder $query
288
     * @param  string  $table
289
     * @return boolean
290
     */
291
    protected function alreadyJoined(Builder $query, $table)
292
    {
293
        $joined = Arr::pluck((array) $query->getQuery()->joins, 'table');
294
295
        return in_array($table, $joined);
296
    }
297
298
    /**
299
     * Get the keys from relation in order to join the table.
300
     *
301
     * @param  \Illuminate\Database\Eloquent\Relations\Relation $relation
302
     * @return array
303
     *
304
     * @throws \LogicException
305
     */
306
    protected function getJoinKeys(Relation $relation)
307
    {
308
        if ($relation instanceof HasOne || $relation instanceof MorphOne) {
309
            return [$relation->getForeignKey(), $relation->getQualifiedParentKeyName()];
310
        }
311
312
        if ($relation instanceof BelongsTo && !$relation instanceof MorphTo) {
313
            return [$relation->getQualifiedForeignKey(), $relation->getQualifiedOtherKeyName()];
314
        }
315
316
        $class = get_class($relation);
317
318
        throw new LogicException(
319
            "Only HasOne, MorphOne and BelongsTo mappings can be queried. {$class} given."
320
        );
321
    }
322
323
    /**
324
     * Get single value result from the mapped attribute.
325
     *
326
     * @param  \Sofa\Eloquence\Builder $query
327
     * @param  string $method
328
     * @param  string $qualifiedColumn
329
     * @return mixed
330
     */
331
    protected function mappedSingleResult(Builder $query, $method, $qualifiedColumn)
332
    {
333
        return $query->getQuery()->select("{$qualifiedColumn}")->{$method}("{$qualifiedColumn}");
334
    }
335
336
    /**
337
     * Add whereHas subquery on the mapped attribute relation.
338
     *
339
     * @param  \Sofa\Eloquence\Builder $query
340
     * @param  string $method
341
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
342
     * @param  string $target
343
     * @param  string $column
344
     * @return \Sofa\Eloquence\Builder
345
     */
346
    protected function mappedHasQuery(Builder $query, $method, ArgumentBag $args, $target, $column)
347
    {
348
        $boolean = $this->getMappedBoolean($args);
349
350
        $operator = $this->getMappedOperator($method, $args);
351
352
        $args->set('column', $column);
353
354
        return $query
355
            ->has($target, $operator, 1, $boolean, $this->getMappedWhereConstraint($method, $args))
356
            ->with($target);
357
    }
358
359
    /**
360
     * Get the relation constraint closure.
361
     *
362
     * @param  string $method
363
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
364
     * @return \Closure
365
     */
366
    protected function getMappedWhereConstraint($method, ArgumentBag $args)
367
    {
368
        return function ($query) use ($method, $args) {
369
            call_user_func_array([$query, $method], $args->all());
370
        };
371
    }
372
373
    /**
374
     * Get boolean called on the original method and set it to default.
375
     *
376
     * @param  \Sofa\EloquenceArgumentBag $args
377
     * @return string
378
     */
379
    protected function getMappedBoolean(ArgumentBag $args)
380
    {
381
        $boolean = $args->get('boolean');
382
383
        $args->set('boolean', 'and');
384
385
        return $boolean;
386
    }
387
388
    /**
389
     * Determine the operator for count relation query and set 'not' appropriately.
390
     *
391
     * @param  string $method
392
     * @param  \Sofa\Hookable\Contracts\ArgumentBag $args
393
     * @return string
394
     */
395
    protected function getMappedOperator($method, ArgumentBag $args)
396
    {
397
        if ($not = $args->get('not')) {
398
            $args->set('not', false);
399
        }
400
401
        if ($null = $this->isWhereNull($method, $args)) {
0 ignored issues
show
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...
402
            $args->set('not', true);
403
        }
404
405
        return ($not ^ $null) ? '<' : '>=';
406
    }
407
408
    /**
409
     * Get the mapping key.
410
     *
411
     * @param  string $key
412
     * @return string|null
413
     */
414
    public function getMappingForAttribute($key)
415
    {
416
        if ($this->hasMapping($key)) {
417
            return $this->mappedAttributes[$key];
418
        }
419
    }
420
421
    /**
422
     * Determine whether the mapping points to relation.
423
     *
424
     * @param  string $mapping
425
     * @return boolean
426
     */
427
    protected function relationMapping($mapping)
428
    {
429
        return strpos($mapping, '.') !== false;
430
    }
431
432
    /**
433
     * Determine whether a mapping exists for an attribute.
434
     *
435
     * @param  string $key
436
     * @return boolean
437
     */
438
    public function hasMapping($key)
439
    {
440
        if (is_null($this->mappedAttributes)) {
441
            $this->parseMappings();
442
        }
443
444
        return array_key_exists((string) $key, $this->mappedAttributes);
445
    }
446
447
    /**
448
     * Parse defined mappings into flat array.
449
     *
450
     * @return void
451
     */
452
    protected function parseMappings()
453
    {
454
        $this->mappedAttributes = [];
455
456
        foreach ($this->getMaps() as $attribute => $mapping) {
457
            if (is_array($mapping)) {
458
                $this->parseImplicitMapping($mapping, $attribute);
459
            } else {
460
                $this->mappedAttributes[$attribute] = $mapping;
461
            }
462
        }
463
    }
464
465
    /**
466
     * Parse implicit mappings.
467
     *
468
     * @param  array  $attributes
469
     * @param  string $target
470
     * @return void
471
     */
472
    protected function parseImplicitMapping($attributes, $target)
473
    {
474
        foreach ($attributes as $attribute) {
475
            $this->mappedAttributes[$attribute] = "{$target}.{$attribute}";
476
        }
477
    }
478
479
    /**
480
     * Map an attribute to a value.
481
     *
482
     * @param  string $key
483
     * @return mixed
484
     */
485
    protected function mapAttribute($key)
486
    {
487
        $segments = explode('.', $this->getMappingForAttribute($key));
488
489
        return $this->getTarget($this, $segments);
490
    }
491
492
    /**
493
     * Get mapped value.
494
     *
495
     * @param  \Illuminate\Database\Eloquent\Model $target
496
     * @param  array  $segments
497
     * @return mixed
498
     */
499
    protected function getTarget($target, array $segments)
500
    {
501
        foreach ($segments as $segment) {
502
            if (!$target) {
503
                return;
504
            }
505
506
            $target = $target->{$segment};
507
        }
508
509
        return $target;
510
    }
511
512
    /**
513
     * Set value of a mapped attribute.
514
     *
515
     * @param string $key
516
     * @param mixed  $value
517
     */
518 View Code Duplication
    protected function setMappedAttribute($key, $value)
0 ignored issues
show
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...
519
    {
520
        $segments = explode('.', $this->getMappingForAttribute($key));
521
522
        $attribute = array_pop($segments);
523
524
        if ($target = $this->getTarget($this, $segments)) {
525
            $this->addTargetToSave($target);
526
527
            $target->{$attribute} = $value;
528
        }
529
    }
530
531
    /**
532
     * Flag mapped model to be saved along with this model.
533
     *
534
     * @param \Illuminate\Database\Eloquent\Model $target
535
     */
536
    protected function addTargetToSave($target)
537
    {
538
        if ($this !== $target) {
539
            $this->targetsToSave[] = $target;
540
        }
541
    }
542
543
    /**
544
     * Save mapped relations.
545
     *
546
     * @return void
547
     */
548
    protected function saveMapped()
549
    {
550
        foreach (array_unique($this->targetsToSave) as $target) {
551
            $target->save();
552
        }
553
554
        $this->targetsToSave = [];
555
    }
556
557
    /**
558
     * Unset mapped attribute.
559
     *
560
     * @param  string $key
561
     * @return void
562
     */
563 View Code Duplication
    protected function forget($key)
0 ignored issues
show
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...
564
    {
565
        $mapping = $this->getMappingForAttribute($key);
566
567
        list($target, $attribute) = $this->parseMappedColumn($mapping);
0 ignored issues
show
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...
568
569
        $target = $target ? $this->getTarget($this, explode('.', $target)) : $this;
570
571
        unset($target->{$attribute});
572
    }
573
574
    /**
575
     * @codeCoverageIgnore
576
     *
577
     * @inheritdoc
578
     */
579
    protected function mutateAttributeForArray($key, $value)
580
    {
581
        if ($this->hasMapping($key)) {
582
            $value = $this->mapAttribute($key);
583
584
            return $value instanceof Arrayable ? $value->toArray() : $value;
585
        }
586
587
        return parent::mutateAttributeForArray($key, $value);
588
    }
589
590
    /**
591
     * Get the array of attribute mappings.
592
     *
593
     * @return array
594
     */
595
    public function getMaps()
596
    {
597
        return (property_exists($this, 'maps')) ? $this->maps : [];
598
    }
599
}
600