Enumerable   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 43
c 0
b 0
f 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A bootEnumerable() 0 7 1
A setAttributeEnum() 0 17 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