Completed
Push — master ( 879860...fb1c6d )
by Stig
10:58 queued 06:25
created

DNDeployment   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 388
Duplicated Lines 8.76 %

Coupling/Cohesion

Components 2
Dependencies 15

Importance

Changes 0
Metric Value
wmc 53
lcom 2
cbo 15
dl 34
loc 388
rs 6.8582
c 0
b 0
f 0

24 Methods

Rating   Name   Duplication   Size   Complexity  
A setResqueToken() 0 3 1
A getFiniteState() 0 3 1
A setFiniteState() 0 4 1
A getStatus() 0 3 1
A getMachine() 0 3 1
A Link() 0 7 2
A LogLink() 0 3 1
A canView() 0 3 1
A logfile() 0 7 1
A log() 0 3 1
A LogContent() 0 3 1
A ResqueStatus() 0 3 1
A getRepository() 0 6 2
A getCommit() 12 12 3
A getCommitURL() 0 15 4
A getCommitMessage() 11 11 3
A getTags() 0 16 4
B getFullDeployMessages() 0 27 5
A getTag() 0 7 2
A getDeploymentStrategy() 0 6 1
D getChanges() 0 26 10
B enqueueDeployment() 11 39 3
A getSigFile() 0 12 2
A setSignal() 0 5 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 DNDeployment 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 DNDeployment, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Class representing a single deplyoment (passed or failed) at a time to a particular environment
5
 *
6
 * @property string $SHA
7
 * @property string $ResqueToken
8
 * @property string $State
9
 * @property int $RefType
10
 * @property SS_Datetime $DeployStarted
11
 * @property SS_Datetime $DeployRequested
12
 *
13
 * @method DNEnvironment Environment()
14
 * @property int EnvironmentID
15
 * @method Member Deployer()
16
 * @property int DeployerID
17
 */
18
class DNDeployment extends DataObject implements Finite\StatefulInterface, HasStateMachine {
0 ignored issues
show
Coding Style introduced by
The property $has_one is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $default_sort is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $summary_fields is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
19
20
	const STATE_NEW = 'New';
21
	const STATE_SUBMITTED = 'Submitted';
22
	const STATE_INVALID = 'Invalid';
23
	const STATE_APPROVED = 'Approved';
24
	const STATE_REJECTED = 'Rejected';
25
	const STATE_QUEUED = 'Queued';
26
	const STATE_DEPLOYING = 'Deploying';
27
	const STATE_ABORTING = 'Aborting';
28
	const STATE_COMPLETED = 'Completed';
29
	const STATE_FAILED = 'Failed';
30
31
	const TR_NEW = 'new';
32
	const TR_SUBMIT = 'submit';
33
	const TR_INVALIDATE = 'invalidate';
34
	const TR_APPROVE = 'approve';
35
	const TR_REJECT = 'reject';
36
	const TR_QUEUE = 'queue';
37
	const TR_DEPLOY = 'deploy';
38
	const TR_ABORT = 'abort';
39
	const TR_COMPLETE = 'complete';
40
	const TR_FAIL = 'fail';
41
42
	/**
43
	 * @var array
44
	 */
45
	private static $db = array(
46
		"SHA" => "GitSHA",
47
		"ResqueToken" => "Varchar(255)",
48
		// The branch that was used to deploy this. Can't really be inferred from Git history because
49
		// the commit could appear in lots of branches that are irrelevant to the user when it comes
50
		// to deployment history, and the branch may have been deleted.
51
		"Branch" => "Varchar(255)",
52
		// is it a branch, tag etc, see GitDispatcher REF_TYPE_* constants
53
		"RefType" => "Int",
54
		"State" => "Enum('New, Submitted, Invalid, Approved, Rejected, Queued, Deploying, Aborting, Completed, Failed', 'New')",
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
55
		// JSON serialised DeploymentStrategy.
56
		"Strategy" => "Text",
57
		"Title" => "Varchar(255)",
58
		"Summary" => "Text",
59
		// the date and time the deploy was queued
60
		"DeployStarted" => "SS_Datetime",
61
		// the date and time a deployment was requested to be approved
62
		"DeployRequested" => "SS_Datetime"
63
	);
64
65
	/**
66
	 * @var array
67
	 */
68
	private static $has_one = array(
69
		"Environment" => "DNEnvironment",
70
		"Deployer" => "Member",
71
		"Approver" => "Member",
72
		"BackupDataTransfer" => "DNDataTransfer" // denotes an automated backup done for this deployment
73
	);
74
75
	private static $default_sort = '"LastEdited" DESC';
76
77
	private static $dependencies = [
78
		'stateMachineFactory' => '%$StateMachineFactory'
79
	];
80
81
	private static $summary_fields = array(
82
		'LastEdited' => 'Last Edited',
83
		'SHA' => 'SHA',
84
		'State' => 'State',
85
		'Deployer.Name' => 'Deployer'
86
	);
87
88
	public function setResqueToken($token) {
89
		$this->ResqueToken = $token;
90
	}
91
92
	public function getFiniteState() {
93
		return $this->State;
94
	}
95
96
	public function setFiniteState($state) {
97
		$this->State = $state;
98
		$this->write();
99
	}
100
101
	public function getStatus() {
102
		return $this->State;
103
	}
104
105
	public function getMachine() {
106
		return $this->stateMachineFactory->forDNDeployment($this);
0 ignored issues
show
Documentation introduced by
The property stateMachineFactory does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
107
	}
108
109
	public function Link() {
110
		if ($this->Environment()->IsNewDeployEnabled()) {
111
			return \Controller::join_links($this->Environment()->Link(\EnvironmentOverview::ACTION_OVERVIEW), 'deployment', $this->ID);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
112
		} else {
113
			return \Controller::join_links($this->Environment()->Link(), 'deploy', $this->ID);
114
		}
115
	}
116
117
	public function LogLink() {
118
		return $this->Link() . '/log';
119
	}
120
121
	public function canView($member = null) {
122
		return $this->Environment()->canView($member);
123
	}
124
125
	/**
126
	 * Return a path to the log file.
127
	 * @return string
128
	 */
129
	protected function logfile() {
130
		return sprintf(
131
			'%s.%s.log',
132
			$this->Environment()->getFullName('.'),
133
			$this->ID
134
		);
135
	}
136
137
	/**
138
	 * @return DeploynautLogFile
139
	 */
140
	public function log() {
141
		return Injector::inst()->createWithArgs('DeploynautLogFile', array($this->logfile()));
142
	}
143
144
	public function LogContent() {
145
		return $this->log()->content();
146
	}
147
148
	/**
149
	 * This remains here for backwards compatibility - we don't want to expose Resque status in here.
150
	 * Resque job (DeployJob) will change statuses as part of its execution.
151
	 *
152
	 * @return string
153
	 */
154
	public function ResqueStatus() {
155
		return $this->State;
156
	}
157
158
	/**
159
	 * Fetch the git repository
160
	 *
161
	 * @return \Gitonomy\Git\Repository|null
162
	 */
163
	public function getRepository() {
164
		if(!$this->SHA) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->SHA of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
165
			return null;
166
		}
167
		return $this->Environment()->Project()->getRepository();
168
	}
169
170
	/**
171
	 * Gets the commit from source. The result is cached upstream in Repository.
172
	 *
173
	 * @return \Gitonomy\Git\Commit|null
174
	 */
175 View Code Duplication
	public function getCommit() {
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...
176
		$repo = $this->getRepository();
177
		if($repo) {
178
			try {
179
				return $this->Environment()->getCommit($this->SHA);
180
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $ex) {
181
				return null;
182
			}
183
		}
184
185
		return null;
186
	}
187
188
	/**
189
	 * Get the commit URL to the commit associated with this deployment.
190
	 * @return null|string
191
	 */
192
	public function getCommitURL() {
193
		$environment = $this->Environment();
194
		if (!$environment) {
195
			return null;
196
		}
197
		$project = $environment->Project();
198
		if (!$project) {
199
			return null;
200
		}
201
		$interface = $project->getRepositoryInterface();
202
		if (!$interface) {
203
			return null;
204
		}
205
		return $interface->CommitURL . '/' . $this->SHA;
206
	}
207
208
	/**
209
	 * Gets the commit message.
210
	 *
211
	 * @return string|null
212
	 */
213 View Code Duplication
	public function getCommitMessage() {
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...
214
		$commit = $this->getCommit();
215
		if($commit) {
216
			try {
217
				return Convert::raw2xml($this->Environment()->getCommitMessage($commit));
218
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $e) {
219
				return null;
220
			}
221
		}
222
		return null;
223
	}
224
225
	/**
226
	 * Return all tags for the deployed commit.
227
	 *
228
	 * @return ArrayList
229
	 */
230
	public function getTags() {
231
		$commit = $this->Environment()->getCommit($this->SHA);
232
		if(!$commit) {
233
			return new ArrayList([]);
234
		}
235
		$tags = $this->Environment()->getCommitTags($commit);
236
		$returnTags = [];
237
		if (!empty($tags)) {
238
			foreach($tags as $tag) {
239
				$field = Varchar::create('Tag', '255');
240
				$field->setValue($tag->getName());
241
				$returnTags[] = $field;
242
			}
243
		}
244
		return new ArrayList($returnTags);
245
	}
246
247
	/**
248
	 * Collate the list of additional flags to affix to this deployment.
249
	 * Elements of the array will be rendered literally.
250
	 *
251
	 * @return ArrayList
252
	 */
253
	public function getFullDeployMessages() {
254
		$strategy = $this->getDeploymentStrategy();
255
		if ($strategy->getActionCode()!=='full') return null;
256
257
		$changes = $strategy->getChangesModificationNeeded();
258
		$messages = [];
259
		foreach ($changes as $change => $details) {
260
			if ($change==='Code version') continue;
261
262
			$messages[] = [
263
				'Flag' => sprintf(
264
					'<span class="label label-default full-deploy-info-item">%s</span>',
265
					$change[0]
266
				),
267
				'Text' => sprintf('%s changed', $change)
268
			];
269
		}
270
271
		if (empty($messages)) {
272
			$messages[] = [
273
				'Flag' => '',
274
				'Text' => '<i>Environment changes have been made.</i>'
275
			];
276
		}
277
278
		return new ArrayList($messages);
279
	}
280
281
	/**
282
	 * Fetches the latest tag for the deployed commit
283
	 *
284
	 * @return \Varchar|null
285
	 */
286
	public function getTag() {
287
		$tags = $this->getTags();
288
		if($tags->count() > 0) {
289
			return $tags->last();
290
		}
291
		return null;
292
	}
293
294
	/**
295
	 * @return DeploymentStrategy
296
	 */
297
	public function getDeploymentStrategy() {
298
		$environment = $this->Environment();
299
		$strategy = new DeploymentStrategy($environment);
300
		$strategy->fromJSON($this->Strategy);
0 ignored issues
show
Documentation introduced by
The property Strategy does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
301
		return $strategy;
302
	}
303
304
	/**
305
	 * Return a list of things that are going to be deployed, such
306
	 * as the code version, and any infrastructural changes.
307
	 *
308
	 * @return ArrayList
309
	 */
310
	public function getChanges() {
311
		$list = new ArrayList();
312
		$strategy = $this->getDeploymentStrategy();
313
		foreach($strategy->getChanges() as $name => $change) {
314
			$changed = (isset($change['from']) && isset($change['to'])) ? $change['from'] != $change['to'] : null;
315
			$description = isset($change['description']) ? $change['description'] : '';
316
			$compareUrl = null;
317
318
			// if there is a compare URL, and a description or a change (something actually changed)
319
			// then show the URL. Otherwise don't show anything, as there is no comparison to be made.
320
			if ($changed || $description) {
321
				$compareUrl = isset($change['compareUrl']) ? $change['compareUrl'] : '';
322
			}
323
324
			$list->push(new ArrayData([
325
				'Name' => $name,
326
				'From' => isset($change['from']) ? $change['from'] : null,
327
				'To' => isset($change['to']) ? $change['to'] : null,
328
				'Description' => $description,
329
				'Changed' => $changed,
330
				'CompareUrl' => $compareUrl
331
			]));
332
		}
333
334
		return $list;
335
	}
336
337
	/**
338
	 * Start a resque job for this deployment
339
	 *
340
	 * @return string Resque token
341
	 */
342
	public function enqueueDeployment() {
343
		$environment = $this->Environment();
344
		$project = $environment->Project();
345
		$log = $this->log();
346
347
		$args = array(
348
			'environmentName' => $environment->Name,
349
			'repository' => $project->getLocalCVSPath(),
350
			'logfile' => $this->logfile(),
351
			'projectName' => $project->Name,
352
			'env' => $project->getProcessEnv(),
353
			'deploymentID' => $this->ID,
354
			'sigFile' => $this->getSigFile(),
355
		);
356
357
		$strategy = $this->getDeploymentStrategy();
358
		// Inject options.
359
		$args = array_merge($args, $strategy->getOptions());
360
		// Make sure we use the SHA as it was written into this DNDeployment.
361
		$args['sha'] = $this->SHA;
362
363
		if(!$this->DeployerID) {
364
			$this->DeployerID = Member::currentUserID();
365
		}
366
367 View Code Duplication
		if($this->DeployerID) {
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...
368
			$deployer = $this->Deployer();
369
			$message = sprintf(
370
				'Deploy to %s initiated by %s (%s), with IP address %s',
371
				$environment->getFullName(),
372
				$deployer->getName(),
373
				$deployer->Email,
374
				\Controller::curr()->getRequest()->getIP()
375
			);
376
			$log->write($message);
377
		}
378
379
		return Resque::enqueue('deploy', 'DeployJob', $args, true);
380
	}
381
382
	public function getSigFile() {
383
		$dir = DNData::inst()->getSignalDir();
384
		if (!is_dir($dir)) {
385
			`mkdir $dir`;
386
		}
387
		return sprintf(
388
			'%s/deploynaut-signal-%s-%s',
389
			DNData::inst()->getSignalDir(),
390
			$this->ClassName,
391
			$this->ID
392
		);
393
	}
394
395
	/**
396
	 * Signal the worker to self-abort. If we had a reliable way of figuring out the right PID,
397
	 * we could posix_kill directly, but Resque seems to not provide a way to find out the PID
398
	 * from the job nor worker.
399
	 */
400
	public function setSignal($signal) {
401
		$sigFile = $this->getSigFile();
402
		// 2 is SIGINT - we can't use SIGINT constant in the Apache context, only available in workers.
403
		file_put_contents($sigFile, $signal);
404
	}
405
}
406