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
|
|
|
|