Passed
Push — controller-updates ( 6ebb88...d6e495 )
by Alex
02:48
created

UpdatesModelRelations   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 44
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isFillableRelation() 0 4 1
A updateResourceRelationships() 0 15 4
1
<?php
2
3
namespace Huntie\JsonApi\Http\Concerns;
4
5
use Illuminate\Database\Eloquent\Relations\BelongsTo;
6
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
7
8
trait UpdatesModelRelations
9
{
10
    /**
11
     * The model relationships that can be updated.
12
     *
13
     * @var array
14
     */
15
    protected $fillableRelations = [];
16
17
    /**
18
     * Determine whether the given named relation can be updated on the model.
19
     *
20
     * @param string $relation
21
     */
22
    protected function isFillableRelation($relation): bool
23
    {
24
        return array_key_exists($relation, $this->fillableRelations);
25
    }
26
27
    /**
28
     * Update one or more relationships on a model instance from an array of
29
     * named relationships and associated resource identifiers.
30
     *
31
     * http://jsonapi.org/format/#crud-updating-resource-relationships
32
     *
33
     * @param Model $record
34
     * @param array $relationships
35
     */
36
    protected function updateResourceRelationships($record, array $relationships)
37
    {
38
        $relationships = array_intersect_key($relationships, array_flip($this->fillableRelations));
39
40
        foreach ($relationships as $name => $relationship) {
41
            $relation = $record->{$name}();
42
43
            if ($relation instanceof BelongsTo) {
44
                $record->{$name}()->associate(array_get($relationship, 'data.id'));
45
                $record->save();
46
            } else if ($relation instanceof BelongsToMany) {
47
                $record->{$name}()->sync(array_pluck($relationship['data'], 'id'));
48
            }
49
        }
50
    }
51
}
52