1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MovingImage\Util; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* AccessorTrait for general purposes. |
7
|
|
|
* |
8
|
|
|
* @author Omid Rad <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
trait AccessorTrait |
11
|
|
|
{ |
12
|
|
|
private $container = []; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @param $methodName string Key |
16
|
|
|
* @param $args array Method Arguments |
17
|
|
|
* |
18
|
|
|
* @return mixed |
19
|
|
|
*/ |
20
|
|
|
public function __call($methodName, $args) |
21
|
|
|
{ |
22
|
|
|
// are we getting or setting? |
23
|
|
|
if (preg_match('~^(set|get|is)([A-Z])(.*)$~', $methodName, $matches)) { |
24
|
|
|
$property = strtolower($matches[2]) . $matches[3]; |
25
|
|
|
if (!property_exists($this, $property)) { |
26
|
|
|
throw new \InvalidArgumentException('Property ' . $property . ' is not exist'); |
27
|
|
|
} |
28
|
|
|
switch ($matches[1]) { |
29
|
|
|
case 'set': |
30
|
|
|
$this->checkArguments($args, 1, 1, $methodName); |
31
|
|
|
|
32
|
|
|
return $this->set($property, $args[0]); |
33
|
|
|
case 'is': |
34
|
|
|
case 'get': |
35
|
|
|
$this->checkArguments($args, 0, 0, $methodName); |
36
|
|
|
|
37
|
|
|
return $this->get($property); |
38
|
|
|
case 'default': |
39
|
|
|
throw new \BadMethodCallException('Method ' . $methodName . ' is not exist'); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param $property string Key |
48
|
|
|
* |
49
|
|
|
* @return mixed |
50
|
|
|
*/ |
51
|
|
|
public function get($property) |
52
|
|
|
{ |
53
|
|
|
if (isset($this->container[$property])) { |
54
|
|
|
return $this->container[$property]; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return null; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param $property string Key |
62
|
|
|
* @param $value string Value |
63
|
|
|
* |
64
|
|
|
* @return self |
65
|
|
|
*/ |
66
|
|
|
public function set($property, $value) |
67
|
|
|
{ |
68
|
|
|
$this->container[$property] = $value; |
69
|
|
|
|
70
|
|
|
return $this; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Check if args are valid or not. |
75
|
|
|
* |
76
|
|
|
* @param array $args List of arguments |
77
|
|
|
* @param integer $min integer Minimum valid params |
78
|
|
|
* @param integer $max Maximum valid params |
79
|
|
|
* @param string $methodName Method name |
80
|
|
|
*/ |
81
|
|
|
protected function checkArguments(array $args, $min, $max, $methodName) |
82
|
|
|
{ |
83
|
|
|
$argc = count($args); |
84
|
|
|
if ($argc < $min || $argc > $max) { |
85
|
|
|
throw new \BadMethodCallException('Method ' . $methodName . ' is not exist'); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* @return array |
91
|
|
|
*/ |
92
|
|
|
public function getContainer() |
93
|
|
|
{ |
94
|
|
|
return $this->container; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|