Completed
Pull Request — master (#49)
by
unknown
01:26
created

HasBinaryUuid::setAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Spatie\BinaryUuid;
4
5
use Ramsey\Uuid\Uuid;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
8
9
trait HasBinaryUuid
10
{
11
    protected static function bootHasBinaryUuid()
12
    {
13
        static::creating(function (Model $model) {
14
            if ($model->{$model->getKeyName()}) {
15
                return;
16
            }
17
18
            $model->{$model->getKeyName()} = static::encodeUuid(Uuid::uuid1());
19
        });
20
    }
21
22
    public static function scopeWithUuid(Builder $builder, $uuid, $field = null): Builder
23
    {
24
        if ($field) {
25
            return static::scopeWithUuidRelation($builder, $uuid, $field);
26
        }
27
28
        if ($uuid instanceof Uuid) {
29
            $uuid = (string) $uuid;
30
        }
31
32
        $uuid = (array) $uuid;
33
34
        return $builder->whereKey(array_map(function (string $modelUuid) {
35
            return static::encodeUuid($modelUuid);
36
        }, $uuid));
37
    }
38
39
    public static function scopeWithUuidRelation(Builder $builder, $uuid, string $field): Builder
40
    {
41
        if ($uuid instanceof Uuid) {
42
            $uuid = (string) $uuid;
43
        }
44
45
        $uuid = (array) $uuid;
46
47
        return $builder->whereIn($field, array_map(function (string $modelUuid) {
48
            return static::encodeUuid($modelUuid);
49
        }, $uuid));
50
    }
51
52
    public static function encodeUuid($uuid): string
53
    {
54
        if (! Uuid::isValid($uuid)) {
55
            return $uuid;
56
        }
57
58
        if (! $uuid instanceof Uuid) {
59
            $uuid = Uuid::fromString($uuid);
60
        }
61
62
        return $uuid->getBytes();
63
    }
64
65
    public static function decodeUuid(string $binaryUuid): string
66
    {
67
        if (Uuid::isValid($binaryUuid)) {
68
            return $binaryUuid;
69
        }
70
71
        return Uuid::fromBytes($binaryUuid)->toString();
72
    }
73
74
    public function toArray()
75
    {
76
        $uuidAttributes = $this->getUuidAttributes();
77
78
        $array = parent::toArray();
79
80
        // if (! $this->exists) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
81
        // return $array;
82
        // }
83
84
        if (is_array($uuidAttributes)) {
85
            foreach ($uuidAttributes as $attributeKey) {
86
                if (array_key_exists($attributeKey, $array)) {
87
                    $uuidKey = $this->getRelatedBinaryKeyName($attributeKey);
88
                    $array[$attributeKey] = $this->{$uuidKey};
89
                }
90
            }
91
        }
92
93
        return $array;
94
    }
95
96
    public function getRelatedBinaryKeyName($attrib)
97
    {
98
        $suffix = $this->getUuidTextAttributeSuffix();
99
100
        return "{$attrib}{$suffix}";
101
    }
102
103
    public function getAttribute($key)
104
    {
105
        if (($uuidKey = $this->uuidTextAttribute($key)) && $this->{$uuidKey} !== null) {
106
            return static::decodeUuid($this->{$uuidKey});
107
        }
108
109
        return parent::getAttribute($key);
110
    }
111
112
    public function setAttribute($key, $value)
113
    {
114
        if ($uuidKey = $this->uuidTextAttribute($key)) {
0 ignored issues
show
Unused Code introduced by
$uuidKey is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
115
            $value = static::encodeUuid($value);
116
        }
117
118
        return parent::setAttribute($key, $value);
119
    }
120
121
    protected function getUuidTextAttributeSuffix()
122
    {
123
        return (property_exists($this, 'uuidTextAttribSuffix')) ? $this->uuidTextAttribSuffix : '_text';
0 ignored issues
show
Bug introduced by
The property uuidTextAttribSuffix 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...
124
    }
125
126
    protected function uuidTextAttribute($key)
127
    {
128
129
        $attribute_s = $this->getKeyName();
130
        $suffix = $this->getUuidTextAttributeSuffix();
131
        $offset = -(strlen($suffix));
132
133
        if (is_string($attribute_s)) {
134
            $attribute_s = [$attribute_s];
135
        }
136
137
        if (substr($key, $offset) == $suffix && in_array(($uuidKey = substr($key, 0, $offset)), $attribute_s)) {
138
            return $uuidKey;
139
        }
140
141
        return false;
142
    }
143
144
    public function getUuidAttributes()
145
    {
146
147
        $uuidAttributes = [];
148
149
        if (property_exists($this, 'uuidAttributes')) {
150
            $uuidAttributes = $this->uuidAttributes === null ? [] : $this->uuidAttributes;
0 ignored issues
show
Bug introduced by
The property uuidAttributes 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...
151
        }
152
153
        $key = $this->getKeyName(); // ! composite primary keys will return an array
154
155
        if (is_string($key)) {
156
            $uuidAttributes = array_merge($uuidAttributes, [$key]); 
157
        } elseif (is_array($key)) {
158
            $uuidAttributes = array_merge($uuidAttributes, $key);
159
        }
160
161
        return $uuidAttributes;
162
    }
163
164
    public function getUuidTextAttribute(): ?string
165
    {
166
        if (! $this->exists) {
0 ignored issues
show
Bug introduced by
The property exists 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...
167
            return null;
168
        }
169
170
        return static::decodeUuid($this->{$this->getKeyName()});
171
    }
172
173
    public function setUuidTextAttribute(string $uuid)
174
    {
175
        $this->{$this->getKeyName()} = static::encodeUuid($uuid);
176
    }
177
178
    public function getQueueableId()
179
    {
180
        return base64_encode($this->{$this->getKeyName()});
181
    }
182
183
    public function newQueryForRestoration($id)
184
    {
185
        return $this->newQueryWithoutScopes()->whereKey(base64_decode($id));
0 ignored issues
show
Bug introduced by
It seems like newQueryWithoutScopes() 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...
186
    }
187
188
    public function getRouteKeyName()
189
    {
190
        $suffix = $this->getUuidTextAttributeSuffix();
191
192
        return "uuid{$suffix}";
193
    }
194
195
    public function getKeyName()
196
    {
197
        return 'uuid';
198
    }
199
200
    public function getIncrementing()
201
    {
202
        return false;
203
    }
204
205
    public function resolveRouteBinding($value)
206
    {
207
        return $this->withUuid($value)->first();
0 ignored issues
show
Bug introduced by
The method withUuid() does not exist on Spatie\BinaryUuid\HasBinaryUuid. Did you maybe mean scopeWithUuid()?

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...
208
    }
209
}
210