Completed
Pull Request — master (#604)
by Stig
06:52 queued 03:02
created

DeployPlanDispatcher::deploysummary()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 37
rs 8.5806
cc 4
eloc 22
nc 4
nop 1
1
<?php
2
3
4
class DeployPlanDispatcher extends Dispatcher {
5
6
	const ACTION_PLAN = 'plan';
7
8
	/**
9
	 * @var array
10
	 */
11
	private static $action_types = [
12
		self::ACTION_PLAN
13
	];
14
15
	/**
16
	 * @var array
17
	 */
18
	public static $allowed_actions = [
19
		'gitupdate',
20
		'gitrefs',
21
		'deploysummary'
22
	];
23
24
	/**
25
	 * @var \DNProject
26
	 */
27
	protected $project = null;
28
29
	/**
30
	 * @var \DNEnvironment
31
	 */
32
	protected $environment = null;
33
34
	public function init() {
35
		parent::init();
36
37
		$this->project = $this->getCurrentProject();
38
39
		if(!$this->project) {
40
			return $this->project404Response();
41
		}
42
43
		// Performs canView permission check by limiting visible projects
44
		$this->environment = $this->getCurrentEnvironment($this->project);
45
		if(!$this->environment) {
46
			return $this->environment404Response();
47
		}
48
	}
49
50
	/**
51
	 * @return string
52
	 */
53
	public function Link() {
54
		return \Controller::join_links($this->environment->Link(), self::ACTION_PLAN);
55
	}
56
57
	/**
58
	 *
59
	 * @param \SS_HTTPRequest $request
60
	 *
61
	 * @return \HTMLText|\SS_HTTPResponse
62
	 */
63
	public function index(\SS_HTTPRequest $request) {
64
		$this->setCurrentActionType(self::ACTION_PLAN);
65
		return $this->customise([
66
			'Environment' => $this->environment
67
		])->renderWith(['Plan', 'DNRoot']);
68
	}
69
70
	/**
71
	 * @param SS_HTTPRequest $request
72
	 * @return SS_HTTPResponse
73
	 */
74
	public function gitupdate(SS_HTTPRequest $request) {
75
		switch($request->httpMethod()) {
76
			case 'POST':
77
				return $this->createFetch();
78
			case 'GET':
79
				return $this->getFetch($this->getRequest()->param('ID'));
80
			default:
81
				return $this->getAPIResponse('Method not allowed, requires POST or GET/{id}', 405);
82
		}
83
	}
84
85
	/**
86
	 * @param SS_HTTPRequest $request
87
	 *
88
	 * @return string
89
	 */
90
	public function gitrefs(\SS_HTTPRequest $request) {
91
92
		$refs = [];
93
		$order = 0;
94
		$refs[] = [
95
			'id' => ++$order,
96
			'label' => "Branch version",
97
			"description" => "Deploy the latest version of a branch",
98
			"list" => $this->getGitBranches($this->project)
99
		];
100
101
		$refs[] = [
102
			'id' => ++$order,
103
			'label' => "Tag version",
104
			"description" => "Deploy a tagged release",
105
			"list" => $this->getGitTags($this->project)
106
		];
107
108
		// @todo: the original was a tree that was keyed by environment, the
109
		// front-end dropdown needs to be changed to support that. brrrr.
110
		$prevDeploys = [];
111
		foreach($this->getGitPrevDeploys($this->project) as $env) {
112
			foreach($env as $deploy) {
113
				$prevDeploys[] = $deploy;
114
			}
115
		}
116
		$refs[] = [
117
			'id' => ++$order,
118
			'label' => "Redeploy a release that was previously deployed (to any environment",
119
			"description" => "Deploy a previous release",
120
			"list" => $prevDeploys
121
		];
122
123
		$body = json_encode($refs, JSON_PRETTY_PRINT);
124
		$this->getResponse()->addHeader('Content-Type', 'application/json');
125
		$this->getResponse()->setBody($body);
126
		return $body;
127
	}
128
129
	/**
130
	 * Generate the data structure used by the frontend component.
131
	 *
132
	 * @param string $name of the component
133
	 *
134
	 * @return array
135
	 */
136
	public function getModel($name) {
137
		return [
138
			'APIEndpoint' => Director::absoluteBaseURL().$this->Link()
139
		];
140
	}
141
142
	/**
143
	 * @param int $ID
144
	 * @return SS_HTTPResponse
145
	 */
146
	protected function getFetch($ID) {
147
		$ping = DNGitFetch::get()->byID($ID);
148
		if(!$ping) {
149
			return $this->getAPIResponse('Fetch not found', 404);
150
		}
151
		$output = [
152
			'id' => $ID,
153
			'status' => $ping->ResqueStatus(),
154
			'message' => array_filter(explode(PHP_EOL, $ping->LogContent()))
155
		];
156
157
		return $this->getAPIResponse($output, 200);
0 ignored issues
show
Documentation introduced by
$output is of type array<string,?,{"id":"in..."?","message":"array"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
158
	}
159
160
	/**
161
	 * @return SS_HTTPResponse
162
	 */
163 View Code Duplication
	protected function createFetch() {
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...
164
		/** @var DNGitFetch $fetch */
165
		$fetch = DNGitFetch::create();
166
		$fetch->ProjectID = $this->project->ID;
167
		$fetch->write();
168
		$fetch->start();
169
170
		$location = Director::absoluteBaseURL() . $this->Link() . '/gitupdate/' . $fetch->ID;
171
		$output = array(
172
			'message' => 'Fetch queued as job ' . $fetch->ResqueToken,
173
			'href' => $location,
174
		);
175
176
		$response = $this->getAPIResponse($output, 201);
0 ignored issues
show
Documentation introduced by
$output is of type array<string,string,{"me...ring","href":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
177
		$response->addHeader('Location', $location);
178
		return $response;
179
	}
180
181
	/**
182
	 * @param SS_HTTPRequest $request
183
	 *
184
	 * @return SS_HTTPResponse
185
	 */
186
	public function deploysummary(SS_HTTPRequest $request) {
187
188
		if(!trim($request->getBody())) {
189
			return $this->getAPIResponse('no body was sent in the request', 400);
190
		}
191
192
		$jsonBody = json_decode($request->getBody(), true);
193
		if(empty($jsonBody)) {
194
			return $this->getAPIResponse('request did not contain a parsable JSON payload', 400);
195
		}
196
197
		$options = [
198
			'sha' => $jsonBody['sha']
199
		];
200
201
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
202
		$data = $strategy->toArray();
203
204
		$interface = $this->project->getRepositoryInterface();
205
		if($this->canCompareCodeVersions($interface, $data['changes']['Code version'])) {
0 ignored issues
show
Bug introduced by
It seems like $interface defined by $this->project->getRepositoryInterface() on line 204 can be null; however, DeployPlanDispatcher::canCompareCodeVersions() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
206
			$compareurl = sprintf(
207
				'%s/compare/%s...%s',
208
				$interface->URL,
209
				$data['changes']['Code version']['from'],
210
				$data['changes']['Code version']['to']
211
			);
212
			$data['changes']['Code version']['compareUrl'] = $compareurl;
213
		}
214
215
		// Append json to response
216
		$token = SecurityToken::inst();
217
		$data['SecurityID'] = $token->getValue();
218
219
		$this->extend('updateDeploySummary', $data);
220
221
		return json_encode($data);
222
	}
223
224
	/**
225
	 * @param $project
226
	 *
227
	 * @return array
228
	 */
229
	protected function getGitBranches($project) {
230
		$branches = [];
231
		foreach($project->DNBranchList() as $branch) {
232
			$branches[] = [
233
				'key' => $branch->SHA(),
234
				'value' => $branch->Name(),
235
			];
236
		}
237
		return $branches;
238
	}
239
240
	/**
241
	 * @param $project
242
	 *
243
	 * @return array
244
	 */
245
	protected function getGitTags($project) {
246
		$tags = [];
247
		foreach($project->DNTagList()->setLimit(null) as $tag) {
248
			$tags[] = [
249
				'key' => $tag->SHA(),
250
				'value' => $tag->Name(),
251
			];
252
		}
253
		return $tags;
254
	}
255
256
	/**
257
	 * @param $project
258
	 *
259
	 * @return array
260
	 */
261
	protected function getGitPrevDeploys($project) {
262
		$redeploy = [];
263 View Code Duplication
		foreach($project->DNEnvironmentList() as $dnEnvironment) {
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...
264
			$envName = $dnEnvironment->Name;
265
			$perEnvDeploys = [];
266
			foreach($dnEnvironment->DeployHistory() as $deploy) {
267
				$sha = $deploy->SHA;
268
269
				// Check if exists to make sure the newest deployment date is used.
270
				if(!isset($perEnvDeploys[$sha])) {
271
					$pastValue = sprintf(
272
						"%s (deployed %s)",
273
						substr($sha, 0, 8),
274
						$deploy->obj('LastEdited')->Ago()
275
					);
276
					$perEnvDeploys[$sha] = [
277
						'key' => $sha,
278
						'value' => $pastValue
279
					];
280
				}
281
			}
282
			if(!empty($perEnvDeploys)) {
283
				$redeploy[$envName] = array_values($perEnvDeploys);
284
			}
285
		}
286
		return $redeploy;
287
	}
288
289
	/**
290
	 * Return a simple response with a message
291
	 *
292
	 * @param string $message
293
	 * @param int $statusCode
294
	 * @return SS_HTTPResponse
295
	 */
296
	protected function getAPIResponse($message, $statusCode) {
297
		$output = [
298
			'message' => $message,
299
			'status_code' => $statusCode
300
		];
301
		$body = json_encode($output, JSON_PRETTY_PRINT);
302
		$response = $this->getResponse();
303
		$response->addHeader('Content-Type', 'application/json');
304
		$response->setBody($body);
305
		$response->setStatusCode($statusCode);
306
		return $response;
307
	}
308
309
	/**
310
	 * @param ArrayData $interface
311
	 * @param array $codeVersion
312
	 *
313
	 * @return bool
314
	 */
315
	protected function canCompareCodeVersions(\ArrayData $interface, $codeVersion) {
316
		if(empty($interface)) {
317
			return false;
318
		}
319
		if(empty($interface->URL)) {
320
			return false;
321
		}
322
		if(empty($codeVersion['from']) || empty($codeVersion['to'])) {
323
			return false;
324
		}
325
		if(strlen($codeVersion['from']) !== 40 || strlen($codeVersion['to']) !== 40) {
326
			return false;
327
		}
328
		return true;
329
	}
330
}
331