AbstractCommandContainer::getAllAsObject()   A
last analyzed

Complexity

Conditions 5
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

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