Completed
Push — master ( a1a721...b83280 )
by Stig
01:16
created

DeployDispatcher::redeploy()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 13
nc 2
nop 1
1
<?php
2
3
/**
4
 * This dispatcher takes care of updating and returning information about this
5
 * projects git repository
6
 */
7
class DeployDispatcher extends Dispatcher {
0 ignored issues
show
Coding Style introduced by
The property $allowed_actions 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 $action_types 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 Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
8
9
	const ACTION_DEPLOY = 'deploys';
10
11
	/**
12
	 * @var array
13
	 */
14
	private static $allowed_actions = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
15
		'history',
16
		'show',
17
		'delete',
18
		'log',
19
		'redeploy',
20
		'summary',
21
		'createdeployment',
22
		'start'
23
	];
24
25
	private static $dependencies = [
26
		'formatter' => '%$DeploynautAPIFormatter'
27
	];
28
29
	/**
30
	 * @var \DNProject
31
	 */
32
	protected $project = null;
33
34
	/**
35
	 * @var \DNEnvironment
36
	 */
37
	protected $environment = null;
38
39
	/**
40
	 * @var array
41
	 */
42
	private static $action_types = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $action_types is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
43
		self::ACTION_DEPLOY
44
	];
45
46
	public function init() {
47
		parent::init();
48
49
		$this->project = $this->getCurrentProject();
50
51
		if (!$this->project) {
52
			return $this->project404Response();
53
		}
54
55
		// Performs canView permission check by limiting visible projects
56
		$this->environment = $this->getCurrentEnvironment($this->project);
57
		if (!$this->environment) {
58
			return $this->environment404Response();
59
		}
60
	}
61
62
	/**
63
	 * @param \SS_HTTPRequest $request
64
	 * @return \HTMLText|\SS_HTTPResponse
65
	 */
66
	public function index(\SS_HTTPRequest $request) {
67
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
68
	}
69
70
	/**
71
	 * @param \SS_HTTPRequest $request
72
	 * @return \SS_HTTPResponse
73
	 */
74
	public function history(\SS_HTTPRequest $request) {
75
		$data = [];
76
77
		$list = $this->environment->DeployHistory('DeployStarted');
78
79
		$fromTimestamp = $request->requestVar('from');
80
		if ($fromTimestamp) {
81
			$from = SS_Datetime::create();
82
			$from->setValue($fromTimestamp);
83
			$list = $list->filter('LastEdited:GreaterThan', $from->Format('Y-m-d H:i:s'));
84
		}
85
86
		foreach ($list as $deployment) {
87
			$data[] = $this->formatter->getDeploymentData($deployment);
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
88
		}
89
90
		return $this->getAPIResponse([
91
			'list' => $data,
92
		], 200);
93
	}
94
95
	/**
96
	 * @param \SS_HTTPRequest $request
97
	 * @return \SS_HTTPResponse
98
	 */
99
	public function show(\SS_HTTPRequest $request) {
100
		$deployment = \DNDeployment::get()->byId($request->param('ID'));
101
		$errorResponse = $this->validateDeployment($deployment);
0 ignored issues
show
Documentation introduced by
$deployment is of type object<DataObject>|null, but the function expects a object<DNDeployment>.

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...
102
		if ($errorResponse instanceof \SS_HTTPResponse) {
103
			return $errorResponse;
104
		}
105
		return $this->getAPIResponse(['deployment' => $this->formatter->getDeploymentData($deployment)], 200);
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
106
	}
107
108
	/**
109
	 * @param \SS_HTTPRequest $request
110
	 * @return \SS_HTTPResponse
111
	 */
112
	public function delete(\SS_HTTPRequest $request) {
113
		if ($request->httpMethod() !== 'POST') {
114
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
115
		}
116
117
		$this->checkSecurityToken();
118
119
		$deployment = \DNDeployment::get()->byId($request->postVar('id'));
120
		$errorResponse = $this->validateDeployment($deployment);
0 ignored issues
show
Documentation introduced by
$deployment is of type object<DataObject>|null, but the function expects a object<DNDeployment>.

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...
121
		if ($errorResponse instanceof \SS_HTTPResponse) {
122
			return $errorResponse;
123
		}
124
125
		$id = $deployment->ID;
126
		$deployment->delete();
127
128
		return $this->getAPIResponse([
129
			'id' => $id,
130
			'message' => 'Deployment has been deleted'
131
		], 201);
132
	}
133
134
	/**
135
	 * @param \SS_HTTPRequest $request
136
	 * @return \SS_HTTPResponse
137
	 */
138
	public function log(\SS_HTTPRequest $request) {
139
		$deployment = \DNDeployment::get()->byId($request->param('ID'));
140
		$errorResponse = $this->validateDeployment($deployment);
0 ignored issues
show
Documentation introduced by
$deployment is of type object<DataObject>|null, but the function expects a object<DNDeployment>.

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...
141
		if ($errorResponse instanceof \SS_HTTPResponse) {
142
			return $errorResponse;
143
		}
144
		$log = $deployment->log();
145
		$lines = [];
146
		if ($log->exists()) {
147
			$lines = explode(PHP_EOL, $log->content());
148
		}
149
150
		return $this->getAPIResponse([
151
			'message' => $lines,
152
			'status' => $deployment->Status,
153
			'deployment' => $this->formatter->getDeploymentData($deployment),
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
154
		], 200);
155
	}
156
157
	/**
158
	 * @param \SS_HTTPRequest $request
159
	 * @return \SS_HTTPResponse
160
	 */
161
	public function redeploy(\SS_HTTPRequest $request) {
162
		$currentBuild = $this->environment->CurrentBuild();
163
		if (!$currentBuild || !$currentBuild->exists()) {
164
			return $this->redirect(Controller::join_links(
165
				$this->environment->Link(\EnvironmentOverview::ACTION_OVERVIEW),
166
				'deployment',
167
				'new'
168
			));
169
		}
170
171
		$strategy = $this->environment->Backend()->planDeploy($this->environment, [
172
			'sha' => $currentBuild->SHA,
173
			'ref_type' => \GitDispatcher::REF_TYPE_PREVIOUS,
174
			'branch' => $currentBuild->Branch
0 ignored issues
show
Documentation introduced by
The property Branch 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...
175
		]);
176
		$deployment = $strategy->createDeployment();
177
178
		return $this->redirect($deployment->Link());
179
	}
180
181
	/**
182
	 * Return a summary of the deployment changes without creating the deployment.
183
	 *
184
	 * @param \SS_HTTPRequest $request
185
	 * @return \SS_HTTPResponse
186
	 */
187
	public function summary(\SS_HTTPRequest $request) {
188
		if ($request->httpMethod() !== 'POST') {
189
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
190
		}
191
		$this->checkSecurityToken();
192
193
		$options = ['sha' => $request->postVar('ref')];
194 View Code Duplication
		if ($request->requestVar('options')) {
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...
195
			foreach (explode(',', $request->postVar('options')) as $option) {
196
				$options[$option] = true;
197
			}
198
		}
199
200
		$strategy = $this->createStrategy($options);
201
		return $this->getAPIResponse($strategy->toArray(), 201);
202
	}
203
204
	/**
205
	 * Create deployment. Can't use {@link create()} as it's taken by Object.
206
	 *
207
	 * @param \SS_HTTPRequest $request
208
	 * @return \SS_HTTPResponse
209
	 */
210
	public function createdeployment(\SS_HTTPRequest $request) {
211
		if ($request->httpMethod() !== 'POST') {
212
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
213
		}
214
215
		$this->checkSecurityToken();
216
217
		// @todo the strategy should have been saved when there has been a request for an
218
		// approval or a bypass. This saved state needs to be checked if it's invalidated
219
		// if another deploy happens before this one
220
		$isBranchDeploy = (int) $request->postVar('ref_type') === GitDispatcher::REF_TYPE_BRANCH;
221
222
		$options = [
223
			'sha' => $request->postVar('ref'),
224
			'ref_type' => $request->postVar('ref_type'),
225
			'branch' => $isBranchDeploy ? $request->postVar('ref_name') : null,
226
			'title' => $request->postVar('title'),
227
			'summary' => $request->postVar('summary')
228
		];
229
230 View Code Duplication
		if ($request->postVar('options')) {
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...
231
			foreach (explode(',', $request->postVar('options')) as $option) {
232
				$options[$option] = true;
233
			}
234
		}
235
236
		$strategy = $this->createStrategy($options);
237
238
		$approver = Member::get()->byId($request->postVar('approver_id'));
239
		if ($approver && $approver->exists()) {
240
			if (!$this->project->allowed(ApprovalsDispatcher::ALLOW_APPROVAL, $approver)) {
0 ignored issues
show
Documentation introduced by
$approver is of type object<DataObject>, but the function expects a object<Member>|null.

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...
241
				return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
242
			}
243
		}
244
245
		$deployment = $strategy->createDeployment();
246
		if ($approver && $approver->exists()) {
247
			$deployment->ApproverID = $approver->ID;
0 ignored issues
show
Documentation introduced by
The property ApproverID 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...
248
			$deployment->write();
249
		}
250
251
		$deploymentLink = \Controller::join_links(Director::absoluteBaseURL(), $deployment->Link());
252
253
		$response = $this->getAPIResponse([
254
			'message' => 'Deployment has been created',
255
			'location' => $deploymentLink,
256
			'deployment' => $this->formatter->getDeploymentData($deployment),
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
257
		], 201);
258
259
		$response->addHeader('Location', $deploymentLink);
260
261
		return $response;
262
	}
263
264
	/**
265
	 * @param \SS_HTTPRequest $request
266
	 * @return \SS_HTTPResponse
267
	 */
268
	public function start(\SS_HTTPRequest $request) {
269
		if ($request->httpMethod() !== 'POST') {
270
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
271
		}
272
273
		$this->checkSecurityToken();
274
275
		$deployment = \DNDeployment::get()->byId($request->postVar('id'));
276
		$errorResponse = $this->validateDeployment($deployment);
0 ignored issues
show
Documentation introduced by
$deployment is of type object<DataObject>|null, but the function expects a object<DNDeployment>.

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...
277
		if ($errorResponse instanceof \SS_HTTPResponse) {
278
			return $errorResponse;
279
		}
280
281
		// The deployment cannot be started until it has been approved, or bypassed straight to approved state
282
		if ($deployment->State !== \DNDeployment::STATE_APPROVED) {
283
			return $this->getAPIResponse(['message' => 'This deployment has not been approved. Cannot deploy'], 403);
284
		}
285
286
		// until we have a system that can invalidate currently scheduled deployments due
287
		// to emergency deploys etc, replan the deployment to check if it's still valid.
288
		$options = $deployment->getDeploymentStrategy()->getOptions();
289
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
290
		$deployment->Strategy = $strategy->toJSON();
291
292
		// if the person starting is not the one who created the deployment, update the deployer
293
		if (Member::currentUserID() !== $deployment->DeployerID) {
294
			$deployment->DeployerID = Member::currentUserID();
295
		}
296
297
		try {
298
			$deployment->getMachine()->apply(\DNDeployment::TR_QUEUE);
299
		} catch (\Exception $e) {
300
			return $this->getAPIResponse([
301
				'message' => $e->getMessage()
302
			], 400);
303
		}
304
305
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
306
307
		$response = $this->getAPIResponse([
308
			'message' => 'Deployment has been queued',
309
			'location' => $location,
310
			'deployment' => $this->formatter->getDeploymentData($deployment),
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
311
		], 201);
312
313
		$response->addHeader('Location', $location);
314
315
		return $response;
316
	}
317
318
	/**
319
	 * @param string $action
320
	 * @return string
321
	 */
322
	public function Link($action = '') {
323
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
324
	}
325
326
	/**
327
	 * @param string $name
328
	 * @return array
329
	 */
330
	public function getModel($name = '') {
331
		return [];
332
	}
333
334
	/**
335
	 * @var array
336
	 * @return \DeploymentStrategy
337
	 */
338
	protected function createStrategy($options) {
339
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
340
		$data = $strategy->toArray();
341
342
		$interface = $this->project->getRepositoryInterface();
343
		if ($this->canCompareCodeVersions($interface, $data['changes'])) {
0 ignored issues
show
Bug introduced by
It seems like $interface defined by $this->project->getRepositoryInterface() on line 342 can be null; however, DeployDispatcher::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...
344
			$compareurl = sprintf(
345
				'%s/compare/%s...%s',
346
				$interface->URL,
347
				$data['changes']['Code version']['from'],
348
				$data['changes']['Code version']['to']
349
			);
350
			$data['changes']['Code version']['compareUrl'] = $compareurl;
351
352
			// special case for .platform.yml field so we don't show a huge blob of changes,
353
			// but rather a link to where the .platform.yml changes were made in the code
354
			if (isset($data['changes']['.platform.yml other'])) {
355
				$data['changes']['.platform.yml other']['compareUrl'] = $compareurl;
356
				$data['changes']['.platform.yml other']['description'] = '';
357
			}
358
		}
359
		$this->extend('updateDeploySummary', $data);
360
361
		// Ensure changes that would have been updated are persisted in the object,
362
		// such as the comparison URL, so that they will be written to the Strategy
363
		// field on the DNDeployment object as part of {@link createDeployment()}
364
		$strategy->setChanges($data['changes']);
365
366
		return $strategy;
367
	}
368
369
	/**
370
	 * @param ArrayData $interface
371
	 * @param $changes
372
	 * @return bool
373
	 */
374
	protected function canCompareCodeVersions(\ArrayData $interface, $changes) {
375
		if (empty($changes['Code version'])) {
376
			return false;
377
		}
378
		$codeVersion = $changes['Code version'];
379
		if (empty($interface)) {
380
			return false;
381
		}
382
		if (empty($interface->URL)) {
383
			return false;
384
		}
385
		if (empty($codeVersion['from']) || empty($codeVersion['to'])) {
386
			return false;
387
		}
388
		if (strlen($codeVersion['from']) !== 40 || strlen($codeVersion['to']) !== 40) {
389
			return false;
390
		}
391
		return true;
392
	}
393
394
	/**
395
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
396
	 * an APIResponse with the error, otherwise null.
397
	 *
398
	 * @param \DNDeployment $deployment
399
	 *
400
	 * @return null|SS_HTTPResponse
401
	 */
402 View Code Duplication
	protected function validateDeployment($deployment) {
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...
403
		if (!$deployment || !$deployment->exists()) {
404
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
405
		}
406
		if ($deployment->EnvironmentID != $this->environment->ID) {
407
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
408
		}
409
		if (!$deployment->canView()) {
410
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
411
		}
412
		return null;
413
	}
414
415
}
416