Completed
Pull Request — master (#604)
by Stig
04:49 queued 01:18
created

DeployPlanDispatcher::createFetch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 12

Duplication

Lines 17
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 17
loc 17
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 12
nc 1
nop 0
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
		// Plan the deployment.
202
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
203
		$data = $strategy->toArray();
204
205
		// Add in a URL for comparing from->to code changes. Ensure that we have
206
		// two proper 40 character SHAs, otherwise we can't show the compare link.
207
		$interface = $this->project->getRepositoryInterface();
208
		if($this->canCompareCodeVersion($interface, $data['changes']['Code version'])) {
0 ignored issues
show
Bug introduced by
It seems like $interface defined by $this->project->getRepositoryInterface() on line 207 can be null; however, DeployPlanDispatcher::canCompareCodeVersion() 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...
209
			$compareurl = sprintf(
210
				'%s/compare/%s...%s',
211
				$interface->URL,
212
				$data['changes']['Code version']['from'],
213
				$data['changes']['Code version']['to']
214
			);
215
			$data['changes']['Code version']['compareUrl'] = $compareurl;
216
		}
217
218
		// Append json to response
219
		$token = SecurityToken::inst();
220
		$data['SecurityID'] = $token->getValue();
221
222
		$this->extend('updateDeploySummary', $data);
223
224
		return json_encode($data);
225
	}
226
227
	/**
228
	 * @param $project
229
	 *
230
	 * @return array
231
	 */
232
	protected function getGitBranches($project) {
233
		$branches = [];
234
		foreach($project->DNBranchList() as $branch) {
235
			$branches[] = [
236
				'key' => $branch->SHA(),
237
				'value' => $branch->Name(),
238
			];
239
		}
240
		return $branches;
241
	}
242
243
	/**
244
	 * @param $project
245
	 *
246
	 * @return array
247
	 */
248
	protected function getGitTags($project) {
249
		$tags = [];
250
		foreach($project->DNTagList()->setLimit(null) as $tag) {
251
			$tags[] = [
252
				'key' => $tag->SHA(),
253
				'value' => $tag->Name(),
254
			];
255
		}
256
		return $tags;
257
	}
258
259
	/**
260
	 * @param $project
261
	 *
262
	 * @return array
263
	 */
264
	protected function getGitPrevDeploys($project) {
265
		$redeploy = [];
266 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...
267
			$envName = $dnEnvironment->Name;
268
			$perEnvDeploys = [];
269
			foreach($dnEnvironment->DeployHistory() as $deploy) {
270
				$sha = $deploy->SHA;
271
272
				// Check if exists to make sure the newest deployment date is used.
273
				if(!isset($perEnvDeploys[$sha])) {
274
					$pastValue = sprintf(
275
						"%s (deployed %s)",
276
						substr($sha, 0, 8),
277
						$deploy->obj('LastEdited')->Ago()
278
					);
279
					$perEnvDeploys[$sha] = [
280
						'key' => $sha,
281
						'value' => $pastValue
282
					];
283
				}
284
			}
285
			if(!empty($perEnvDeploys)) {
286
				$redeploy[$envName] = array_values($perEnvDeploys);
287
			}
288
		}
289
		return $redeploy;
290
	}
291
292
	/**
293
	 * Return a simple response with a message
294
	 *
295
	 * @param string $message
296
	 * @param int $statusCode
297
	 * @return SS_HTTPResponse
298
	 */
299
	protected function getAPIResponse($message, $statusCode) {
300
		$output = [
301
			'message' => $message,
302
			'status_code' => $statusCode
303
		];
304
		$body = json_encode($output, JSON_PRETTY_PRINT);
305
		$response = $this->getResponse();
306
		$response->addHeader('Content-Type', 'application/json');
307
		$response->setBody($body);
308
		$response->setStatusCode($statusCode);
309
		return $response;
310
	}
311
312
	/**
313
	 * @param ArrayData $interface
314
	 * @param array $codeVersion
315
	 *
316
	 * @return bool
317
	 */
318
	protected function canCompareCodeVersion(\ArrayData $interface, $codeVersion) {
319
		if(empty($interface)) {
320
			return false;
321
		}
322
		if(empty($interface->URL)) {
323
			return false;
324
		}
325
		if(empty($codeVersion['from']) || empty($codeVersion['to'])) {
326
			return false;
327
		}
328
		if(strlen($codeVersion['from']) !== 40 || strlen($codeVersion['to']) !== 40) {
329
			return false;
330
		}
331
		return true;
332
	}
333
}
334