Completed
Pull Request — master (#8)
by Omid
02:46 queued 18s
created

AccessorTrait   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 14
lcom 0
cbo 0
dl 0
loc 73
ccs 0
cts 40
cp 0
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
C __call() 0 22 7
A get() 0 7 2
A set() 0 5 1
A checkArguments() 0 6 3
A getContainer() 0 4 1
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
        // are we getting or setting?
22
        if (preg_match('~^(set|get|is)([A-Z])(.*)$~', $methodName, $matches)) {
23
            $property = strtolower($matches[2]) . $matches[3];
24
            if (!property_exists($this, $property)) {
25
                throw new \InvalidArgumentException('Property ' . $property . ' is not exist');
26
            }
27
            switch($matches[1]) {
28
                case 'set':
29
                    $this->checkArguments($args, 1, 1, $methodName);
30
                    return $this->set($property, $args[0]);
31
                case 'is':
32
                case 'get':
33
                    $this->checkArguments($args, 0, 0, $methodName);
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
        if (isset($this->container[$property])) {
50
            return $this->container[$property];
51
        }
52
53
        return null;
54
    }
55
56
    /**
57
     * @param $property string Key
58
     * @param $value    string Value
59
     *
60
     * @return self
61
     */
62
    public function set($property, $value) {
63
        $this->container[$property] = $value;
64
65
        return $this;
66
    }
67
68
    protected function checkArguments(array $args, $min, $max, $methodName) {
69
        $argc = count($args);
70
        if ($argc < $min || $argc > $max) {
71
            throw new \BadMethodCallException('Method ' . $methodName . ' is not exist');
72
        }
73
    }
74
75
    /**
76
     * @return array
77
     */
78
    public function getContainer()
79
    {
80
        return $this->container;
81
    }
82
}