Enumerable::setAttributeEnum()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
rs 9.7
cc 3
nc 3
nop 3
1
<?php
2
3
namespace mindtwo\LaravelEnumerable\Models\Traits;
4
5
use Mindtwo\DynamicMutators\Facades\Handler;
6
use mindtwo\LaravelEnumerable\Exceptions\EnumException;
7
use mindtwo\LaravelEnumerable\Exceptions\InvalidEnumValueException;
8
9
trait Enumerable
10
{
11
    /**
12
     * The "booting" method of the trait.
13
     */
14
    public static function bootEnumerable()
15
    {
16
        static::registerMutationHandler(Handler::make([
17
            'name'        => 'enums',
18
            'set_mutator' => ['setAttributeEnum'],
19
        ]));
20
    }
21
22
    /**
23
     * Set an enumerable attribute value.
24
     *
25
     * @param string $key
26
     * @param $value
27
     * @param string $class
28
     *
29
     * @throws EnumException
30
     * @throws InvalidEnumValueException
31
     *
32
     * @return $this
33
     */
34
    public function setAttributeEnum(string $key, $value, string $class)
35
    {
36
        if (! class_exists($class)) {
37
            throw new EnumException(sprintf('Enumerable class "%s" doesn\'t exist', $class));
38
        }
39
40
        if (! $class::hasValue($value)) {
41
            throw new InvalidEnumValueException(sprintf(
42
                'Value "%s" is not allowed for attribute "%s"',
43
                $value, $key
44
            ));
45
        }
46
47
        $this->attributes[$key] = $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...
48
49
        return $this;
50
    }
51
}
52