Passed
Push — master ( ff83e3...5f4a5c )
by Ehsan
03:54
created

AbstractCommandContainer::getAllAsObject()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 10
cts 10
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 2
nop 1
crap 5
1
<?php
2
3
namespace Botonomous;
4
5
/**
6
 * Class AbstractCommandContainer.
7
 */
8
abstract class AbstractCommandContainer
9
{
10
    protected static $commands;
11
12
    /**
13
     * @param $key
14
     *
15
     * @return Command|void
16
     */
17 6
    public function getAsObject($key)
18
    {
19 6
        $commands = $this->getAllAsObject($key);
20
21 6
        if (!array_key_exists($key, $commands)) {
22
            /* @noinspection PhpInconsistentReturnPointsInspection */
23 1
            return;
24
        }
25
26 6
        return $commands[$key];
27
    }
28
29
    /**
30
     * @param $commands
31
     */
32 2
    public function setAll($commands)
33
    {
34 2
        static::$commands = $commands;
35 2
    }
36
37
    /**
38
     * @return array
39
     */
40 10
    public function getAll()
41
    {
42 10
        return static::$commands;
43
    }
44
45
    /**
46
     * @param null $key
47
     *
48
     * @throws \Exception
49
     *
50
     * @return mixed
51
     */
52 10
    public function getAllAsObject($key = null)
53
    {
54 10
        $commands = $this->getAll();
55
56 10
        if (!empty($commands)) {
57 9
            foreach ($commands as $commandKey => $commandDetails) {
58 9
                if (!empty($key) && $commandKey !== $key) {
59 6
                    continue;
60
                }
61
62 9
                $commandDetails['key'] = $commandKey;
63
64 9
                $mappedObject = $this->mapToCommandObject($commandDetails);
65
66 9
                $commands[$commandKey] = $mappedObject;
67
            }
68
        }
69
70 10
        return $commands;
71
    }
72
73
    /**
74
     * @param array $row
75
     *
76
     * @throws \Exception
77
     *
78
     * @return Command
79
     */
80 9
    private function mapToCommandObject(array $row)
81
    {
82 9
        $mappedObject = new Command($row['key']);
83
84 9
        unset($row['key']);
85
86 9
        if (!empty($row)) {
87 9
            foreach ($row as $key => $value) {
88 9
                $methodName = 'set'.ucwords($key);
89
90
                // check setter exists
91 9
                if (!method_exists($mappedObject, $methodName)) {
92 1
                    continue;
93
                }
94
95 9
                $mappedObject->$methodName($value);
96
            }
97
        }
98
99 9
        return $mappedObject;
100
    }
101
}
102