Completed
Push — master ( 237044...0042b8 )
by Michael
9s
created

GeneratesUuid::castAttribute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 2
crap 3.1406
1
<?php
2
3
namespace Dyrynda\Database\Support;
4
5
use Ramsey\Uuid\Uuid;
6
use Illuminate\Support\Str;
7
8
/**
9
 * UUID generation trait.
10
 *
11
 * Include this trait in any Eloquent model where you wish to automatically set
12
 * a UUID field. When saving, if the UUID field has not been set, generate a
13
 * new UUID value, which will be set on the model and saved by Eloquent.
14
 *
15
 * @copyright 2017 Michael Dyrynda
16
 * @author    Michael Dyrynda <[email protected]>
17
 * @license   MIT
18
 *
19
 * @property  string  $uuidVersion
20
 */
21
trait GeneratesUuid
22
{
23
    /**
24
     * The UUID versions.
25
     *
26
     * @var array
27
     */
28
    protected $uuidVersions = [
29
        'uuid1',
30
        'uuid3',
31
        'uuid4',
32
        'uuid5',
33
        'ordered',
34
    ];
35
36
    /**
37
     * Determine whether an attribute should be cast to a native type.
38
     *
39
     * @param  string  $key
40
     * @param  array|string|null  $types
41
     * @return bool
42
     */
43
    abstract public function hasCast($key, $types = null);
44
45
    /**
46
     * Boot the trait, adding a creating observer.
47
     *
48
     * When persisting a new model instance, we resolve the UUID field, then set
49
     * a fresh UUID, taking into account if we need to cast to binary or not.
50
     *
51
     * @return void
52
     */
53
    public static function bootGeneratesUuid()
54
    {
55 7
        static::creating(function ($model) {
56
            /* @var \Illuminate\Database\Eloquent\Model|static $model */
57 7
            $uuid = $model->resolveUuid();
0 ignored issues
show
Bug introduced by
The method resolveUuid does only exist in Dyrynda\Database\Support\GeneratesUuid, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
58
59 7
            if (isset($model->attributes['uuid']) && ! is_null($model->attributes['uuid'])) {
60
                /* @var \Ramsey\Uuid\Uuid $uuid */
61 4
                $uuid = $uuid->fromString(strtolower($model->attributes['uuid']));
62
            }
63
64 7
            $model->attributes['uuid'] = $model->hasCast('uuid') ? $uuid->getBytes() : $uuid->toString();
65 7
        });
66 3
    }
67
68
    /**
69
     * Resolve a UUID instance for the configured version.
70
     *
71
     * @return \Ramsey\Uuid\Uuid
72
     */
73 7
    public function resolveUuid()
74
    {
75 7
        if (($version = $this->resolveUuidVersion()) == 'ordered') {
76 1
            return Str::orderedUuid();
77
        }
78
79 6
        return call_user_func([Uuid::class, $version]);
80
    }
81
82
    /**
83
     * Resolve the UUID version to use when setting the UUID value. Default to uuid4.
84
     *
85
     * @return string
86
     */
87 13
    public function resolveUuidVersion()
88
    {
89 13
        if (property_exists($this, 'uuidVersion') && in_array($this->uuidVersion, $this->uuidVersions)) {
90 6
            return $this->uuidVersion;
91
        }
92
93 7
        return 'uuid4';
94
    }
95
96
    /**
97
     * Scope queries to find by UUID.
98
     *
99
     * @param  \Illuminate\Database\Eloquent\Builder  $query
100
     * @param  string  $uuid
101
     *
102
     * @return \Illuminate\Database\Eloquent\Builder
103
     */
104 2
    public function scopeWhereUuid($query, $uuid)
105
    {
106 2
        if ($this->hasCast('uuid')) {
107 1
            $uuid = $this->resolveUuid()->fromString($uuid)->getBytes();
108
        }
109
110 2
        return $query->where('uuid', $uuid);
111
    }
112
113
    /**
114
     * Cast an attribute to a native PHP type.
115
     *
116
     * @param  string  $key
117
     * @param  mixed  $value
118
     * @return mixed
119
     */
120 3
    protected function castAttribute($key, $value)
121
    {
122 3
        if ($key === 'uuid' && ! is_null($value)) {
123 3
            return $this->resolveUuid()->fromBytes($value)->toString();
124
        }
125
126
        return parent::castAttribute($key, $value);
127
    }
128
}
129