Completed
Pull Request — master (#8)
by Omid
02:30
created

AccessorTrait::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
3
namespace MovingImage\Util;
4
5
trait AccessorTrait
6
{
7
    private $container = [];
8
9
    /**
10
     * @param $methodName string Key
11
     * @param $args       array  Method Arguments
12
     *
13
     * @return mixed
14
     */
15
    public function __call($methodName, $args) {
16
        // are we getting or setting?
17
        if (preg_match('~^(set|get|is)([A-Z])(.*)$~', $methodName, $matches)) {
18
            $property = strtolower($matches[2]) . $matches[3];
19
            if (!property_exists($this, $property)) {
20
                throw new \InvalidArgumentException('Property ' . $property . ' is not exist');
21
            }
22
            switch($matches[1]) {
23
                case 'set':
24
                    $this->checkArguments($args, 1, 1, $methodName);
25
                    return $this->set($property, $args[0]);
26
                case 'is':
27
                case 'get':
28
                    $this->checkArguments($args, 0, 0, $methodName);
29
                    return $this->get($property);
30
                case 'default':
31
                    throw new \BadMethodCallException('Method ' . $methodName . ' is not exist');
32
            }
33
        }
34
35
        return null;
36
    }
37
38
    /**
39
     * @param $property string Key
40
     *
41
     * @return mixed
42
     */
43
    public function get($property) {
44
        if (isset($this->container[$property])) {
45
            return $this->container[$property];
46
        }
47
48
        return null;
49
    }
50
51
    /**
52
     * @param $property string Key
53
     * @param $value    string Value
54
     *
55
     * @return self
56
     */
57
    public function set($property, $value) {
58
        $this->container[$property] = $value;
59
60
        return $this;
61
    }
62
63
    protected function checkArguments(array $args, $min, $max, $methodName) {
64
        $argc = count($args);
65
        if ($argc < $min || $argc > $max) {
66
            throw new \BadMethodCallException('Method ' . $methodName . ' is not exist');
67
        }
68
    }
69
70
    /**
71
     * @return array
72
     */
73
    public function getContainer()
74
    {
75
        return $this->container;
76
    }
77
}