DeploymentStrategy   B
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 354
Duplicated Lines 18.08 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 41
lcom 1
cbo 7
dl 64
loc 354
rs 8.2769
c 0
b 0
f 0

26 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setActionTitle() 0 3 1
A getActionTitle() 0 3 1
A setActionCode() 0 3 1
A getActionCode() 0 3 1
A setEstimatedTime() 0 3 1
A getEstimatedTime() 0 3 1
B setChange() 0 12 5
A setChanges() 0 3 1
A setChangeDescriptionOnly() 0 5 1
B getChangesModificationNeeded() 0 15 6
A getChanges() 0 3 1
A getChange() 0 7 2
A setOption() 0 3 1
A getOption() 0 5 2
A getOptions() 0 3 1
A setValidationCode() 0 3 1
A getValidationCode() 0 3 1
A setMessage() 0 16 2
A getMessages() 0 3 1
A toArray() 17 17 2
A toJSON() 0 3 1
A fromJSON() 0 4 1
A fromArray() 17 17 3
A createDeployment() 15 15 1
A updateDeployment() 15 15 1

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 DeploymentStrategy 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 DeploymentStrategy, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
class DeploymentStrategy extends ViewableData {
4
5
	const SUCCESS_CODE = 'success';
6
7
	const WARNING_CODE = 'warning';
8
9
	const ERROR_CODE = 'error';
10
11
	/**
12
	 * @var DNEnvironment
13
	 */
14
	protected $environment;
15
16
	/**
17
	 * @var string
18
	 */
19
	protected $actionTitle = 'Deploy';
20
21
	/**
22
	 * @var string
23
	 */
24
	protected $actionCode = 'default';
25
26
	/**
27
	 * @var int
28
	 */
29
	protected $estimatedTime = 0;
30
31
	/**
32
	 * @var array
33
	 */
34
	protected $changes = [];
35
36
	/**
37
	 * @var array
38
	 */
39
	protected $options;
40
41
	/**
42
	 * Validation code
43
	 *
44
	 * @var string
45
	 */
46
	protected $validationCode = DeploymentStrategy::SUCCESS_CODE;
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
47
48
	/**
49
	 * @var array
50
	 */
51
	protected $messages = [];
52
53
54
	/**
55
	 * @param \DNEnvironment $environment
56
	 * @param array $options
57
	 */
58
	public function __construct(\DNEnvironment $environment, $options = array()) {
59
		$this->environment = $environment;
60
		$this->options = $options;
61
	}
62
63
	/**
64
	 * @param string $title
65
	 */
66
	public function setActionTitle($title) {
67
		$this->actionTitle = $title;
68
	}
69
70
	/**
71
	 * @return string
72
	 */
73
	public function getActionTitle() {
74
		return $this->actionTitle;
75
	}
76
77
	/**
78
	 */
79
	public function setActionCode($code) {
80
		$this->actionCode = $code;
81
	}
82
83
	/**
84
	 * @return string
85
	 */
86
	public function getActionCode() {
87
		return $this->actionCode;
88
	}
89
90
	/**
91
	 * @param int
92
	 */
93
	public function setEstimatedTime($seconds) {
94
		$this->estimatedTime = $seconds;
95
	}
96
97
	/**
98
	 * @return int Time in minutes
99
	 */
100
	public function getEstimatedTime() {
101
		return $this->estimatedTime;
102
	}
103
104
	/**
105
	 * @param string $title
106
	 * @param string $from
107
	 * @param string $to
108
	 */
109
	public function setChange($title, $from, $to) {
110
		// Normalise "empty" values into dashes so comparisons are done properly.
111
		// This means there is no diference between an empty string and a null
112
		// but "0" is considered to be non-empty.
113
		if(empty($from) && !strlen($from)) $from = '-';
114
		if(empty($to) && !strlen($to)) $to = '-';
115
116
		return $this->changes[$title] = array(
117
			'from' => $from,
118
			'to' => $to
119
		);
120
	}
121
122
	/**
123
	 * @param array $data
124
	 */
125
	public function setChanges($data) {
126
		$this->changes = $data;
127
	}
128
129
	/**
130
	 * @param string $title
131
	 * @param string $desc
132
	 */
133
	public function setChangeDescriptionOnly($title, $desc) {
134
		return $this->changes[$title] = array(
135
			'description' => $desc
136
		);
137
	}
138
139
	/**
140
	 * Filter the changeset where modification was not required.
141
	 *
142
	 * @return array
143
	 */
144
	public function getChangesModificationNeeded() {
145
		$filtered = [];
146
		foreach ($this->changes as $change => $details) {
147
			if (!empty($details['description'])) {
148
				$filtered[$change] = $details;
149
			} else if (
150
				(array_key_exists('from', $details) || array_key_exists('to', $details))
151
				&& $details['from'] !== $details['to']
152
			) {
153
				$filtered[$change] = $details;
154
			}
155
		}
156
157
		return $filtered;
158
	}
159
160
	/**
161
	 * @return array Associative array of changes, e.g.
162
	 *	array(
163
	 *		'SHA' => array(
164
	 *			'from' => 'abc',
165
	 *			'to' => 'def'
166
	 *		)
167
	 *	)
168
	 */
169
	public function getChanges() {
170
		return $this->changes;
171
	}
172
173
	/**
174
	 * Returns a change or a given key.
175
	 *
176
	 * @return ArrayData|null
177
	 */
178
	public function getChange($key) {
179
		$changes = $this->getChanges();
180
		if(array_key_exists($key, $changes)) {
181
			return new ArrayData($changes[$key]);
182
		}
183
		return null;
184
	}
185
186
	/**
187
	 * @param string $option
188
	 * @param string $value
189
	 */
190
	public function setOption($option, $value) {
191
		$this->options[$option] = $value;
192
	}
193
194
	/**
195
	 * @param string $option
196
	 * @return string|null
197
	 */
198
	public function getOption($option) {
199
		if(!empty($this->options[$option])) {
200
			return $this->options[$option];
201
		}
202
	}
203
204
	/**
205
	 * @return string
206
	 */
207
	public function getOptions() {
208
		return $this->options;
209
	}
210
211
	/**
212
	 * @param string $code
213
	 */
214
	public function setValidationCode($code) {
215
		$this->validationCode = $code;
216
	}
217
218
	/**
219
	 * @return string
220
	 */
221
	public function getValidationCode() {
222
		return $this->validationCode;
223
	}
224
225
	/**
226
	 * @param string $msg
227
	 */
228
	public function setMessage($msg, $code = self::ERROR_CODE) {
229
		$this->messages[] = [
230
			'text' => $msg,
231
			'code' => $code
232
		];
233
234
		$current = $this->getValidationCode();
235
		$map = [
236
			DeploymentStrategy::SUCCESS_CODE => 0,
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
237
			DeploymentStrategy::WARNING_CODE => 1,
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
238
			DeploymentStrategy::ERROR_CODE => 2
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
239
		];
240
		if($map[$current] < $map[$code]) {
241
			$this->setValidationCode($code);
242
		}
243
	}
244
245
	/**
246
	 * @return array
247
	 */
248
	public function getMessages() {
249
		return $this->messages;
250
	}
251
252
	/**
253
	 * Transform the deployment strategy to an array.
254
	 *
255
	 * @return array
256
	 */
257 View Code Duplication
	public function toArray() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
258
		$fields = array(
259
			'actionTitle',
260
			'actionCode',
261
			'estimatedTime',
262
			'changes',
263
			'options',
264
			'validationCode',
265
			'messages'
266
		);
267
268
		$output = array();
269
		foreach($fields as $field) {
270
			$output[$field] = $this->$field;
271
		}
272
		return $output;
273
	}
274
275
	/**
276
	 * @return string
277
	 */
278
	public function toJSON() {
279
		return json_encode($this->toArray(), JSON_PRETTY_PRINT);
280
	}
281
282
	/**
283
	 * Load from JSON associative array.
284
	 * Environment must be set by the callee when creating this object.
285
	 *
286
	 * @param string $json
287
	 */
288
	public function fromJSON($json) {
289
		$decoded = json_decode($json, true);
290
		return $this->fromArray($decoded);
291
	}
292
293
	/**
294
	 * Load from array.
295
	 * Environment must be set by the callee when creating this object.
296
	 *
297
	 * @param string $data
298
	 */
299 View Code Duplication
	public function fromArray($data) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
300
		$fields = array(
301
			'actionTitle',
302
			'actionCode',
303
			'estimatedTime',
304
			'changes',
305
			'options',
306
			'validationCode',
307
			'messages'
308
		);
309
310
		foreach($fields as $field) {
311
			if(!empty($data[$field])) {
312
				$this->$field = $data[$field];
313
			}
314
		}
315
	}
316
317
	/**
318
	 * @return DNDeployment
319
	 */
320 View Code Duplication
	public function createDeployment() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
321
		$deployment = \DNDeployment::create();
322
		$deployment->EnvironmentID = $this->environment->ID;
323
		$deployment->SHA = $this->getOption('sha');
324
		$deployment->RefType = $this->getOption('ref_type');
325
		$deployment->RefName = $this->getOption('ref_name');
326
		$deployment->Summary = $this->getOption('summary');
0 ignored issues
show
Bug introduced by
The property Summary does not seem to exist. Did you mean summary_fields?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
327
		$deployment->Title = $this->getOption('title');
0 ignored issues
show
Documentation introduced by
The property Title does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
328
		$deployment->Strategy = $this->toJSON();
0 ignored issues
show
Documentation introduced by
The property Strategy does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
329
		$deployment->DeployerID = \Member::currentUserID();
330
		$deployment->write();
331
332
		// re-get and return the deployment so we have the correct state
333
		return \DNDeployment::get()->byId($deployment->ID);
334
	}
335
336
	/**
337
	 * @param int $deploymentID
338
	 * @return \DNDeployment
339
	 */
340 View Code Duplication
	public function updateDeployment($deploymentID) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
341
		$deployment = \DNDeployment::get()->byId($deploymentID);
342
		$deployment->EnvironmentID = $this->environment->ID;
343
		$deployment->SHA = $this->getOption('sha');
344
		$deployment->RefType = $this->getOption('ref_type');
345
		$deployment->RefName = $this->getOption('ref_name');
346
		$deployment->Summary = $this->getOption('summary');
0 ignored issues
show
Bug introduced by
The property Summary does not seem to exist. Did you mean summary_fields?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
347
		$deployment->Title = $this->getOption('title');
348
		$deployment->Strategy = $this->toJSON();
349
		$deployment->DeployerID = \Member::currentUserID();
350
		$deployment->write();
351
352
		// re-get and return the deployment so we have the correct state
353
		return \DNDeployment::get()->byId($deployment->ID);
354
	}
355
356
}
357
358