Completed
Pull Request — master (#53)
by
unknown
02:07
created

HasBinaryUuid::generateUuid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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 find($id, $columns = ['*'])
23
    {
24
        if (\is_array($id) || $id instanceof Arrayable) {
0 ignored issues
show
Bug introduced by
The class Spatie\BinaryUuid\Arrayable does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
25
            return static::findMany($id, $columns);
26
        }
27
28
        return static::withUuid($id)->first($columns);
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...
29
    }
30
31
    public static function findMany($ids, $columns = ['*'])
32
    {
33
        if (empty($ids)) {
34
            return static::newModelInstance()->newCollection();
35
        }
36
37
        return static::withUuid($ids)->get($columns);
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...
38
    }
39
40
    public static function scopeWithUuid(Builder $builder, $uuid, $field = null): Builder
41
    {
42
        if ($field) {
43
            return static::scopeWithUuidRelation($builder, $uuid, $field);
44
        }
45
46
        if ($uuid instanceof Uuid) {
47
            $uuid = (string) $uuid;
48
        }
49
50
        $uuid = (array) $uuid;
51
52
        return $builder->whereKey(array_map(function (string $modelUuid) {
53
            return static::encodeUuid($modelUuid);
54
        }, $uuid));
55
    }
56
57
    public static function scopeWithUuidRelation(Builder $builder, $uuid, string $field): Builder
58
    {
59
        if ($uuid instanceof Uuid) {
60
            $uuid = (string) $uuid;
61
        }
62
63
        $uuid = (array) $uuid;
64
65
        return $builder->whereIn($field, array_map(function (string $modelUuid) {
66
            return static::encodeUuid($modelUuid);
67
        }, $uuid));
68
    }
69
70
    public static function generateUuid() : string
71
    {
72
        return Uuid::uuid1();
73
    }
74
75
    public static function encodeUuid($uuid): string
76
    {
77
        if (! Uuid::isValid($uuid)) {
78
            return $uuid;
79
        }
80
81
        if (! $uuid instanceof Uuid) {
82
            $uuid = Uuid::fromString($uuid);
83
        }
84
85
        return $uuid->getBytes();
86
    }
87
88
    public static function decodeUuid(string $binaryUuid): string
89
    {
90
        if (Uuid::isValid($binaryUuid)) {
91
            return $binaryUuid;
92
        }
93
94
        return Uuid::fromBytes($binaryUuid)->toString();
95
    }
96
97
    public function toArray()
98
    {
99
        $uuidAttributes = $this->getUuidAttributes();
100
101
        $array = parent::toArray();
102
103
        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...
104
            return $array;
105
        }
106
107
        foreach ($uuidAttributes as $attributeKey) {
108
            if (! array_key_exists($attributeKey, $array)) {
109
                continue;
110
            }
111
            $uuidKey = $this->getRelatedBinaryKeyName($attributeKey);
112
            $array[$attributeKey] = $this->{$uuidKey};
113
        }
114
115
        return $array;
116
    }
117
118
    public function getRelatedBinaryKeyName($attribute)
119
    {
120
        $suffix = $this->getUuidSuffix();
121
122
        return preg_match('/(?:uu)?id/i', $attribute) ? "{$attribute}{$suffix}" : $attribute;
123
    }
124
125
    public function getAttribute($key)
126
    {
127
        $uuidKey = $this->uuidTextAttribute($key);
128
129
        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...
130
            return static::decodeUuid($this->{$uuidKey});
131
        }
132
133
        return parent::getAttribute($key);
134
    }
135
136
    public function setAttribute($key, $value)
137
    {
138
        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...
139
            $value = static::encodeUuid($value);
140
        }
141
142
        return parent::setAttribute($key, $value);
143
    }
144
145
    protected function getUuidSuffix()
146
    {
147
        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...
148
    }
149
150
    protected function uuidTextAttribute($key)
151
    {
152
        $uuidAttributes = $this->getUuidAttributes();
153
        $suffix = $this->getUuidSuffix();
154
        $offset = -(strlen($suffix));
155
156
        if (substr($key, $offset) == $suffix && in_array(($uuidKey = substr($key, 0, $offset)), $uuidAttributes)) {
157
            return $uuidKey;
158
        }
159
160
        return false;
161
    }
162
163
    public function getUuidAttributes()
164
    {
165
        $uuidAttributes = [];
166
167
        if (property_exists($this, 'uuids') && is_array($this->uuids)) {
168
            $uuidAttributes = array_merge($uuidAttributes, $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...
169
        }
170
171
        // non composite primary keys will return a string so casting required
172
        $key = (array) $this->getKeyName();
173
174
        $uuidAttributes = array_unique(array_merge($uuidAttributes, $key));
175
176
        return $uuidAttributes;
177
    }
178
179
    public function getUuidTextAttribute(): ?string
180
    {
181
        $key = $this->getKeyName();
182
183
        if (! $this->exists || is_array($key)) {
184
            return null;
185
        }
186
187
        return static::decodeUuid($this->{$key});
188
    }
189
190
    public function setUuidTextAttribute(string $uuid)
191
    {
192
        $key = $this->getKeyName();
193
194
        if (is_array($key)) {
195
            return;
196
        }
197
198
        $this->{$key} = static::encodeUuid($uuid);
199
    }
200
201
    public function getQueueableId()
202
    {
203
        return base64_encode($this->{$this->getKeyName()});
204
    }
205
206
    public function newQueryForRestoration($id)
207
    {
208
        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...
209
    }
210
211
    public function getRouteKeyName()
212
    {
213
        $suffix = $this->getUuidSuffix();
214
215
        return "uuid{$suffix}";
216
    }
217
218
    public function getKeyName()
219
    {
220
        return 'uuid';
221
    }
222
223
    public function getIncrementing()
224
    {
225
        return false;
226
    }
227
228
    public function resolveRouteBinding($value)
229
    {
230
        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...
231
    }
232
}
233