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

UpdatesModelRelations::isFillableRelation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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