Environment   B
last analyzed

Complexity

Total Complexity 46

Size/Duplication

Total Lines 263
Duplicated Lines 2.66 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 46
lcom 1
cbo 1
dl 7
loc 263
ccs 133
cts 133
cp 1
rs 8.3999
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 3
B validate() 0 14 7
A validateName() 0 6 3
B validateNodes() 7 26 6
B validateRoles() 0 19 5
A __toString() 0 4 1
C addNode() 0 47 9
A addNodes() 0 8 2
B getNode() 0 30 6
B getNodes() 0 23 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Environment often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Environment, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Assimtech\Tempo;
4
5
use Assimtech\Tempo\ArrayObject\ValidatableArrayObject;
6
use InvalidArgumentException;
7
use OutOfBoundsException;
8
9
class Environment extends ValidatableArrayObject
10
{
11
    /**
12
     * {@inheritdoc}
13
     * Example:
14
     *  // $node1, $node2, $node3, $node4 are instances of \Assimtech\Tempo\Node\NodeInterface
15
     *  new Environment(array(
16
     *      'name' => 'test',
17
     *      'nodes' => array(
18
     *          $node1,
19
     *          $node2,
20
     *          $node3,
21
     *          $node4,
22
     *      ),
23
     *      'roles' => array(
24
     *          'role1' => array(
25
     *              $node1,
26
     *              $node2,
27
     *          ),
28
     *          'role2' => array(
29
     *              $node3,
30
     *          ),
31
     *      ),
32
     *  ))
33
     */
34 25
    public function __construct($input = array(), $flags = 0, $iteratorClass = 'ArrayIterator')
35
    {
36
        // Handle string shortcut setup
37 25
        if (is_string($input)) {
38
            $input = array(
39 17
                'name' => $input,
40 17
            );
41 17
        }
42
43
        // Defaults
44 25
        if (is_array($input)) {
45 25
            $input = array_replace_recursive(array(
46 25
                'nodes' => array(),
47 25
                'roles' => array(),
48 25
            ), $input);
49 25
        }
50
51 25
        parent::__construct($input, $flags, $iteratorClass);
52 23
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 25
    protected function validate($index = null)
58
    {
59 25
        if ($index === null || $index === 'name') {
60 25
            $this->validateName();
61 23
        }
62
63 23
        if ($index === null || $index === 'nodes') {
64 23
            $this->validateNodes();
65 23
        }
66
67 23
        if ($index === null || $index === 'roles') {
68 23
            $this->validateRoles();
69 23
        }
70 23
    }
71
72
    /**
73
     * @throws \InvalidArgumentException
74
     */
75 25
    protected function validateName()
76
    {
77 25
        if (!isset($this['name']) || empty($this['name'])) {
78 3
            throw new InvalidArgumentException('property: [name] is mandatory');
79
        }
80 23
    }
81
82
    /**
83
     * @throws \InvalidArgumentException
84
     */
85 23
    protected function validateNodes()
86
    {
87 23
        if (!isset($this['nodes'])) {
88 1
            throw new InvalidArgumentException('property: [nodes] is mandatory');
89
        }
90
91 23
        $foundNodes = array();
92 23
        foreach ($this['nodes'] as $idx => $node) {
93 7 View Code Duplication
            if (!$node instanceof Node\NodeInterface) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94 1
                throw new InvalidArgumentException(sprintf(
95 1
                    'property: [nodes] must implement \Assimtech\Tempo\Node\NodeInterface, [nodes][%s] is a %s',
96 1
                    $idx,
97 1
                    is_object($node) ? get_class($node) : gettype($node)
98 1
                ));
99
            }
100
101 6
            if (in_array((string)$node, $foundNodes)) {
102 1
                throw new InvalidArgumentException(sprintf(
103 1
                    'property: [nodes][] contains a duplicate node: %s',
104
                    (string)$node
105 1
                ));
106
            }
107
108 6
            $foundNodes[] = (string)$node;
109 23
        }
110 23
    }
111
112
    /**
113
     * @throws \InvalidArgumentException
114
     */
115 23
    protected function validateRoles()
116
    {
117 23
        if (!isset($this['roles'])) {
118 1
            throw new InvalidArgumentException('property: [roles] is mandatory');
119
        }
120
121 23
        foreach ($this['roles'] as $role => $nodes) {
122 3
            foreach ($nodes as $idx => $node) {
123 3
                if (!in_array($node, $this['nodes'])) {
124 1
                    throw new InvalidArgumentException(sprintf(
125 1
                        'property: [roles][%s][%s] (%s) is not a member of [nodes][]',
126 1
                        $role,
127 1
                        $idx,
128
                        $node
129 1
                    ));
130
                }
131 2
            }
132 23
        }
133 23
    }
134
135
    /**
136
     * @return string
137
     */
138 8
    public function __toString()
139
    {
140 8
        return $this['name'];
141
    }
142
143
    /**
144
     * @param \Assimtech\Tempo\Node\NodeInterface $node
145
     * @param string|array $roles Optional for grouping of like nodes e.g. fep, web, db
146
     * @return self
147
     * @throws \InvalidArgumentException
148
     */
149 6
    public function addNode(Node\NodeInterface $node, $roles = array())
150
    {
151 6
        if (is_string($roles)) {
152
            $roles = array(
153 2
                $roles,
154 2
            );
155 2
        }
156
157 6
        if (!is_array($roles)) {
158 1
            throw new InvalidArgumentException(sprintf(
159 1
                'Environment: %s, roles must be a string or an array of strings',
160
                $this
161 1
            ));
162
        }
163
164 5
        foreach ($roles as $role) {
165 3
            if (!is_string($role)) {
166 1
                throw new InvalidArgumentException(sprintf(
167 1
                    'Environment: %s, roles must be a string or an array of strings',
168
                    $this
169 1
                ));
170
            }
171 4
        }
172
173 4
        $knownNodeNames = array();
174 4
        foreach ($this['nodes'] as $knownNode) {
175 3
            $knownNodeNames[] = (string)$knownNode;
176 4
        }
177 4
        if (in_array((string)$node, $knownNodeNames)) {
178 1
            throw new InvalidArgumentException(sprintf(
179 1
                'Environment: %s, Node: %s already exists',
180 1
                $this,
181
                $node
182 1
            ));
183
        }
184
185 4
        $this['nodes'][] = $node;
186
187 4
        foreach ($roles as $role) {
188 2
            if (!isset($this['roles'][$role])) {
189 2
                $this['roles'][$role] = array();
190 2
            }
191 2
            $this['roles'][$role][] = $node;
192 4
        }
193
194 4
        return $this;
195
    }
196
197
    /**
198
     * @param \Assimtech\Tempo\Node\NodeInterface[] $nodes
199
     * @param string|array $roles Optional for grouping of like nodes e.g. fep, web, db
200
     * @return self
201
     */
202 2
    public function addNodes($nodes, $roles = array())
203
    {
204 2
        foreach ($nodes as $node) {
205 2
            $this->addNode($node, $roles);
206 2
        }
207
208 2
        return $this;
209
    }
210
211
    /**
212
     * @param string $name Name is optional if exactly one node is in the environment
213
     * @return \Assimtech\Tempo\Node\NodeInterface
214
     * @throws \InvalidArgumentException
215
     * @throws \OutOfBoundsException
216
     */
217 5
    public function getNode($name = null)
218
    {
219 5
        if ($name === null) {
220 2
            if (count($this['nodes']) !== 1) {
221 1
                $nodeNames = array();
222 1
                foreach ($this['nodes'] as $node) {
223 1
                    $nodeNames[] = (string)$node;
224 1
                }
225 1
                throw new InvalidArgumentException(sprintf(
226 1
                    'You must specify the node name because environment %s has more than 1 node: %s',
227 1
                    $this,
228 1
                    implode(', ', $nodeNames)
229 1
                ));
230
            }
231
232 1
            return $this['nodes'][0];
233
        }
234
235 3
        foreach ($this['nodes'] as $node) {
236 2
            if (((string)$node) === $name) {
237 2
                return $node;
238
            }
239 1
        }
240
241 1
        throw new OutOfBoundsException(sprintf(
242 1
            'Environment: %s, Node: %s doesn\'t exist',
243 1
            $this,
244
            $name
245 1
        ));
246
    }
247
248 5
    public function getNodes($role = null)
249
    {
250 5
        if ($role === null) {
251 1
            return $this['nodes'];
252
        }
253
254 4
        if (!is_string($role)) {
255 1
            throw new InvalidArgumentException(sprintf(
256 1
                'Environment: %s, role must be a string or null for all nodes',
257
                $this
258 1
            ));
259
        }
260
261 3
        if (!isset($this['roles'][$role])) {
262 1
            throw new OutOfBoundsException(sprintf(
263 1
                'Environment: %s, Role: %s doesn\'t exist',
264 1
                $this,
265
                $role
266 1
            ));
267
        }
268
269 2
        return $this['roles'][$role];
270
    }
271
}
272