Completed
Pull Request — master (#71)
by
unknown
01:53
created

HasBinaryUuid::setUuidTextAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Spatie\BinaryUuid;
4
5
use Exception;
6
use Ramsey\Uuid\Uuid;
7
use Illuminate\Database\Eloquent\Model;
8
9
trait HasBinaryUuid
10
{
11
    protected static function bootHasBinaryUuid()
12
    {
13
        static::creating(function (Model $model) {
14
            $uuidAttributes = $model->getUuidAttributes();
15
16
            foreach ($uuidAttributes as $key) {
17
                if ($model->{$key}) {
18
                    continue;
19
                }
20
21
                $model->{$key} = static::encodeUuid(static::generateUuid());
22
            }
23
        });
24
    }
25
26
    public static function scopeWithUuid(Builder $builder, $uuid, $field = null): Builder
27
    {
28
        if ($field) {
29
            return static::scopeWithUuidRelation($builder, $uuid, $field);
30
        }
31
32
        if ($uuid instanceof Uuid) {
33
            $uuid = (string) $uuid;
34
        }
35
36
        $uuid = (array) $uuid;
37
38
        return $builder->whereKey(array_map(function (string $modelUuid) {
39
            return static::encodeUuid($modelUuid);
40
        }, $uuid));
41
    }
42
43
    public static function scopeWithUuidRelation(Builder $builder, $uuid, string $field): Builder
44
    {
45
        if ($uuid instanceof Uuid) {
46
            $uuid = (string) $uuid;
47
        }
48
49
        $uuid = (array) $uuid;
50
51
        return $builder->whereIn($field, array_map(function (string $modelUuid) {
0 ignored issues
show
Documentation Bug introduced by
The method whereIn does not exist on object<Spatie\BinaryUuid\Builder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
52
            return static::encodeUuid($modelUuid);
53
        }, $uuid));
54
    }
55
56
    public static function generateUuid() : string
57
    {
58
        return Uuid::uuid1();
59
    }
60
61
    public static function encodeUuid($uuid): string
62
    {
63
        if (! Uuid::isValid($uuid)) {
64
            return $uuid;
65
        }
66
67
        if (! $uuid instanceof Uuid) {
68
            $uuid = Uuid::fromString($uuid);
69
        }
70
71
        return $uuid->getBytes();
72
    }
73
74
    public static function decodeUuid(string $binaryUuid): string
75
    {
76
        if (Uuid::isValid($binaryUuid)) {
77
            return $binaryUuid;
78
        }
79
80
        return Uuid::fromBytes($binaryUuid)->toString();
81
    }
82
83
    public function getUuidKeys()
84
    {
85
        return (property_exists($this, 'uuids') && is_array($this->uuids)) ? $this->uuids : [];
0 ignored issues
show
Bug introduced by
The property uuids 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...
86
    }
87
88
    public function toArray()
89
    {
90
        $uuidAttributes = $this->getUuidAttributes();
91
92
        $array = parent::toArray();
93
        $pivotUuids = [];
0 ignored issues
show
Unused Code introduced by
$pivotUuids 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...
94
95
        if (! $this->exists || ! is_array($uuidAttributes)) {
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...
96
            return $array;
97
        }
98
99
        foreach ($uuidAttributes as $attributeKey) {
100
            if (! array_key_exists($attributeKey, $array)) {
101
                continue;
102
            }
103
            $uuidKey = $this->getRelatedBinaryKeyName($attributeKey);
104
            $array[$attributeKey] = $this->{$uuidKey};
105
        }
106
107
        if (isset($array['pivot'])) {
108
            $pivotUuids = $array['pivot'];
109
110
            if (! is_array($pivotUuids)) {
111
                $pivotUuids = get_object_vars($pivotUuids);
112
            }
113
114
            foreach ($pivotUuids as $key => $uuid) {
115
                $pivotUuids[$key] = $this->decodeUuid($uuid);
116
            }
117
118
            $array['pivot'] = $pivotUuids;
119
        }
120
121
        return $array;
122
    }
123
124
    public function getRelatedBinaryKeyName($attribute): string
125
    {
126
        $suffix = $this->getUuidSuffix();
127
128
        return preg_match('/(?:[a-zA-Z_]+)?id/i', $attribute) ? "{$attribute}{$suffix}" : $attribute;
129
    }
130
131
    public function getAttribute($key)
132
    {
133
        $uuidKey = $this->uuidTextAttribute($key);
134
135
        if ($uuidKey && $this->{$uuidKey} !== null) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uuidKey of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
136
            return static::decodeUuid($this->{$uuidKey});
137
        }
138
139
        return parent::getAttribute($key);
140
    }
141
142
    public function setAttribute($key, $value)
143
    {
144
        if ($this->uuidTextAttribute($key)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->uuidTextAttribute($key) of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
145
            $value = static::encodeUuid($value);
146
        }
147
148
        return parent::setAttribute($key, $value);
149
    }
150
151
    protected function getUuidSuffix()
152
    {
153
        return (property_exists($this, 'uuidSuffix')) ? $this->uuidSuffix : '_text';
0 ignored issues
show
Bug introduced by
The property uuidSuffix 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...
154
    }
155
156
    protected function uuidTextAttribute($key)
157
    {
158
        $uuidAttributes = $this->getUuidAttributes();
159
        $suffix = $this->getUuidSuffix();
160
        $offset = -(strlen($suffix));
161
162
        if (substr($key, $offset) == $suffix && in_array(($uuidKey = substr($key, 0, $offset)), $uuidAttributes)) {
163
            return $uuidKey;
164
        }
165
166
        return false;
167
    }
168
169
    public function getUuidAttributes()
170
    {
171
        $uuidKeys = $this->getUuidKeys();
172
173
        // non composite primary keys will return a string so casting required
174
        $key = (array) $this->getKeyName();
175
176
        $uuidAttributes = array_unique(array_merge($uuidKeys, $key));
177
178
        return $uuidAttributes;
179
    }
180
181
    public function getUuidTextAttribute(): ?string
182
    {
183
        $key = $this->getKeyName();
184
185
        if (! $this->exists || is_array($key)) {
186
            return null;
187
        }
188
189
        return static::decodeUuid($this->{$key});
190
    }
191
192
    public function setUuidTextAttribute(string $uuid)
193
    {
194
        $key = $this->getKeyName();
195
196
        if (! is_string($key)) {
197
            throw new Exception('composite keys not allowed for attribute mutation');
198
        }
199
200
        $this->{$key} = static::encodeUuid($uuid);
201
    }
202
203
    public function getQueueableId()
204
    {
205
        return base64_encode($this->{$this->getKeyName()});
206
    }
207
208
    public function newQueryForRestoration($id)
209
    {
210
        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...
211
    }
212
213
    public function newEloquentBuilder($query)
214
    {
215
        return new Builder($query);
216
    }
217
218
    public function getRouteKeyName()
219
    {
220
        $keyName = $this->getKeyName();
221
222
        $routeKeyName = is_string($keyName) ? $this->strUuidSuffix($keyName) : array_map([&$this, 'strUuidSuffix'], $keyName);
223
224
        return $routeKeyName;
225
    }
226
227
    public function getKeyName()
228
    {
229
        return (! property_exists($this, 'primaryKey') || $this->primaryKey === 'id') ? 'uuid' : $this->primaryKey;
0 ignored issues
show
Bug introduced by
The property primaryKey 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...
230
    }
231
232
    public function getIncrementing()
233
    {
234
        return false;
235
    }
236
237
    public function resolveRouteBinding($value)
238
    {
239
        $keyName = $this->getKeyName();
240
241
        if (is_array($keyName)) {
242
            $parsed = explode(':', strval($value), count($keyName));
243
244
            $value = array_combine($keyName, $parsed);
245
        }
246
247
        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...
248
    }
249
250
    public function strUuidSuffix($str)
251
    {
252
        $suffix = $this->getUuidSuffix();
253
254
        return "{$str}{$suffix}";
255
    }
256
}
257