Completed
Pull Request — master (#9)
by Omid
03:34
created

AccessorTrait::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 6
1
<?php
2
3
namespace MovingImage\VMProApiClient\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
            switch ($matches[1]) {
26
                case 'set':
27
                    $this->checkArguments($args, 1, 1, $methodName);
28
29
                    return $this->set($property, $args[0]);
30
                case 'is':
31
                case 'get':
32
                    $this->checkArguments($args, 0, 0, $methodName);
33
34
                    return $this->get($property);
35
                case 'default':
36
                    throw new \BadMethodCallException("Method $methodName is not exist");
37
            }
38
        }
39
40
        return null;
41
    }
42
43
    /**
44
     * @param $property string Key
45
     *
46
     * @return mixed
47
     */
48
    public function get($property)
49
    {
50
        if (isset($this->container[$property])) {
51
            return $this->container[$property];
52
        }
53
54
        return null;
55
    }
56
57
    /**
58
     * @param $property string Key
59
     * @param $value    string Value
60
     *
61
     * @return self
62
     */
63
    public function set($property, $value)
64
    {
65
        $this->container[$property] = $value;
66
67
        return $this;
68
    }
69
70
    /**
71
     * Check if args are valid or not.
72
     *
73
     * @param array  $args       List of arguments
74
     * @param int    $min        integer Minimum valid params
75
     * @param int    $max        Maximum valid params
76
     * @param string $methodName Method name
77
     */
78
    protected function checkArguments(array $args, $min, $max, $methodName)
79
    {
80
        $argc = count($args);
81
        if ($argc < $min || $argc > $max) {
82
            throw new \BadMethodCallException("Method $methodName is not exist");
83
        }
84
    }
85
86
    /**
87
     * @return array
88
     */
89
    public function getContainer()
90
    {
91
        return $this->container;
92
    }
93
}
94