HasDynamicMutators   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 1
dl 0
loc 83
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setAttribute() 0 15 4
A getAttribute() 0 11 3
A registerMutationHandler() 0 4 1
A __call() 0 14 4
1
<?php
2
3
namespace Mindtwo\DynamicMutators\Traits;
4
5
use Illuminate\Support\Str;
6
use Mindtwo\DynamicMutators\Handler\Handler;
7
use Mindtwo\DynamicMutators\Interfaces\MutationHandlerInterface;
8
9
trait HasDynamicMutators
10
{
11
    /**
12
     * Registered mutation handler.
13
     *
14
     * @var MutationHandlerInterface[]
15
     */
16
    private static $mutation_handlers = [];
17
18
    /**
19
     * Set attribute.
20
     *
21
     * @param string $name
22
     * @param mixed  $value
23
     */
24
    public function setAttribute($name, $value)
25
    {
26
        foreach (self::$mutation_handlers as $handler) {
27
            $handler->setModel($this);
28
            if ($handler->hasSetMutator($name)) {
29
                $result = $handler->callSetMutator($name, $value);
30
31
                if (! $handler->shouldStack(MutationHandlerInterface::OPERATOR_SET)) {
32
                    return $result;
33
                }
34
            }
35
        }
36
37
        return parent::setAttribute($name, $value);
38
    }
39
40
    /**
41
     * Get attribute.
42
     *
43
     * @param mixed $name
44
     *
45
     * @return mixed
46
     */
47
    public function getAttribute($name)
48
    {
49
        foreach (self::$mutation_handlers as $controller) {
50
            $controller->setModel($this);
51
            if ($controller->hasGetMutator($name)) {
52
                return $controller->callGetMutator($name);
53
            }
54
        }
55
56
        return parent::getAttribute($name);
57
    }
58
59
    /**
60
     * Register a mutation handler.
61
     *
62
     * @param MutationHandlerInterface $handler
63
     */
64
    public static function registerMutationHandler(MutationHandlerInterface $handler)
65
    {
66
        self::$mutation_handlers[] = $handler;
67
    }
68
69
    /**
70
     * Magic call method.
71
     *
72
     * @param $name
73
     * @param $arguments
74
     *
75
     * @return mixed
76
     */
77
    public function __call($name, $arguments)
78
    {
79
        if (preg_match('/^(set|get)(.+)Attribute$/', $name, $matches)) {
80
            $key = Str::snake($matches[2]);
81
            foreach (self::$mutation_handlers as $handler) {
82
                $handler->setModel($this);
83
                if ($handler->hasGetMutator($key)) {
84
                    return $handler->callGetMutator($key);
85
                }
86
            }
87
        }
88
89
        return parent::__call($name, $arguments);
90
    }
91
}
92