GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 2e6be7...b9f299 )
by Andrei
01:24
created

rollbackPivotedRelationToRevision()   B

Complexity

Conditions 7
Paths 18

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
c 0
b 0
f 0
rs 8.3946
cc 7
nc 18
nop 2
1
<?php
2
3
namespace Neurony\Revisions\Traits;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Database\Eloquent\SoftDeletes;
7
use Neurony\Revisions\Contracts\RevisionModelContract;
8
use Neurony\Revisions\Helpers\RelationHelper;
9
10
trait RollbackRevisionJsonRepresentation
11
{
12
    /**
13
     * Only rollback the model instance to the given revision.
14
     *
15
     * Loop through the revision's data.
16
     * If the revision's field name matches one from the model's attributes.
17
     * Replace the value from the model's attribute with the one from the revision.
18
     *
19
     * @param RevisionModelContract $revision
20
     * @return void
21
     */
22
    protected function rollbackModelToRevision(RevisionModelContract $revision): void
23
    {
24
        foreach ($revision->metadata as $field => $value) {
0 ignored issues
show
Bug introduced by
Accessing metadata on the interface Neurony\Revisions\Contracts\RevisionModelContract suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
25
            if (array_key_exists($field, $this->getAttributes())) {
0 ignored issues
show
Bug introduced by
It seems like getAttributes() 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...
26
                $this->attributes[$field] = $value;
0 ignored issues
show
Bug introduced by
The property attributes does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
27
            }
28
        }
29
30
        $this->save();
0 ignored issues
show
Bug introduced by
It seems like save() 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...
31
    }
32
33
    /**
34
     * Only rollback the model's direct relations to the given revision.
35
     *
36
     * Loop through the stored revision's relation items.
37
     * If the relation exists, then update it with the data from the revision.
38
     * If the relation does not exist, then create a new one with the data from the revision.
39
     *
40
     * Please note that when creating a new relation, the primary key (id) will be the old one from the revision's data.
41
     * This way, the correspondence between the model and it's relation is kept.
42
     *
43
     * @param string $relation
44
     * @param array $attributes
45
     * @return void
46
     */
47
    protected function rollbackDirectRelationToRevision(string $relation, array $attributes): void
48
    {
49
        $relatedPrimaryKey = $attributes['records']['primary_key'];
50
        $relatedRecords = $attributes['records']['items'];
51
52
        // delete extra added child related records after the revision checkpoint
53
        if (RelationHelper::isChild($attributes['type'])) {
54
            $oldRelated = $this->{$relation}()->pluck($relatedPrimaryKey)->toArray();
55
            $currentRelated = array_map(function ($item) use ($relatedPrimaryKey) {
56
                return $item[$relatedPrimaryKey];
57
            }, $relatedRecords);
58
59
            $extraRelated = array_diff($oldRelated, $currentRelated);
60
61
            if (!empty($extraRelated)) {
62
                $this->{$relation}()->whereIn($relatedPrimaryKey, $extraRelated)->delete();
63
            }
64
        }
65
66
        // rollback each related record to its revision checkpoint
67
        foreach ($relatedRecords as $item) {
68
            $related = $this->{$relation}();
69
70
            if (array_key_exists(SoftDeletes::class, class_uses($this->{$relation}))) {
71
                $related = $related->withTrashed();
72
            }
73
74
            $rel = $related->findOrNew($item[$relatedPrimaryKey] ?? null);
75
76
            foreach ($item as $field => $value) {
77
                $rel->attributes[$field] = $value;
78
            }
79
80
            if (array_key_exists(SoftDeletes::class, class_uses($rel))) {
81
                $rel->{$rel->getDeletedAtColumn()} = null;
82
            }
83
84
            $rel->save();
85
        }
86
    }
87
88
    /**
89
     * Rollback a model's pivoted relations to the given revision.
90
     *
91
     * Loop through the stored revision's relation items.
92
     * If the relation's related model exists, then leave it as is (maybe modified) because other records or entities might be using it.
93
     * If the relation's related model does not exist, then create a new one with the data from the revision.
94
     *
95
     * Please note that when creating a new relation related instance, the primary key (id) will be the old one from the revision's data.
96
     * This way, the correspondence between the model and it's relation is kept.
97
     *
98
     * Loop through the stored revision's relation pivots.
99
     * Sync the model's pivot values with the ones from the revision.
100
     *
101
     * @param string $relation
102
     * @param array $attributes
103
     * @return void
104
     */
105
    protected function rollbackPivotedRelationToRevision(string $relation, array $attributes): void
106
    {
107
        foreach ($attributes['records']['items'] as $item) {
108
            $related = $this->{$relation}()->getRelated();
109
110
            if (array_key_exists(SoftDeletes::class, class_uses($related))) {
111
                $related = $related->withTrashed();
112
            }
113
114
            $rel = $related->findOrNew($item[$attributes['records']['primary_key']] ?? null);
115
116
            if ($rel->exists === false) {
117
                foreach ($item as $field => $value) {
118
                    $rel->attributes[$field] = $value;
119
                }
120
121
                $rel->save();
122
            }
123
            if (array_key_exists(SoftDeletes::class, class_uses($rel))) {
124
                $rel->{$rel->getDeletedAtColumn()} = null;
125
                $rel->save();
126
            }
127
        }
128
129
        $this->{$relation}()->detach();
130
131
        foreach ($attributes['pivots']['items'] as $item) {
132
            $this->{$relation}()->attach(
133
                $item[$attributes['pivots']['related_key']],
134
                Arr::except((array) $item, [
135
                    $attributes['pivots']['primary_key'],
136
                    $attributes['pivots']['foreign_key'],
137
                    $attributes['pivots']['related_key'],
138
                ])
139
            );
140
        }
141
    }
142
}
143