Completed
Pull Request — master (#844)
by Sean
03:39
created

DeployDispatcher::summary()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 15

Duplication

Lines 5
Ratio 22.73 %

Importance

Changes 0
Metric Value
dl 5
loc 22
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 15
nc 4
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
		$sha = $this->project->resolveRevision($request->postVar('ref'));
194
		if (!$sha) {
195
			return $this->getAPIResponse([
196
				'message' => 'The given reference could not be resolved. Does it exist in the repository?'
197
			], 400);
198
		}
199
200
		$options = ['sha' => $sha];
201 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...
202
			foreach (explode(',', $request->postVar('options')) as $option) {
203
				$options[$option] = true;
204
			}
205
		}
206
		$strategy = $this->createStrategy($options);
207
		return $this->getAPIResponse($strategy->toArray(), 201);
208
	}
209
210
	/**
211
	 * Create deployment. Can't use {@link create()} as it's taken by Object.
212
	 *
213
	 * @param \SS_HTTPRequest $request
214
	 * @return \SS_HTTPResponse
215
	 */
216
	public function createdeployment(\SS_HTTPRequest $request) {
217
		if ($request->httpMethod() !== 'POST') {
218
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
219
		}
220
221
		$this->checkSecurityToken();
222
223
		// @todo the strategy should have been saved when there has been a request for an
224
		// approval or a bypass. This saved state needs to be checked if it's invalidated
225
		// if another deploy happens before this one
226
		$isBranchDeploy = (int) $request->postVar('ref_type') === GitDispatcher::REF_TYPE_BRANCH;
227
228
		$options = [
229
			'sha' => $request->postVar('ref'),
230
			'ref_type' => $request->postVar('ref_type'),
231
			'branch' => $isBranchDeploy ? $request->postVar('ref_name') : null,
232
			'title' => $request->postVar('title'),
233
			'summary' => $request->postVar('summary')
234
		];
235
236 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...
237
			foreach (explode(',', $request->postVar('options')) as $option) {
238
				$options[$option] = true;
239
			}
240
		}
241
242
		$strategy = $this->createStrategy($options);
243
244
		$approver = Member::get()->byId($request->postVar('approver_id'));
245
		if ($approver && $approver->exists()) {
246
			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...
247
				return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
248
			}
249
		}
250
251
		$deployment = $strategy->createDeployment();
252
		if ($approver && $approver->exists()) {
253
			$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...
254
			$deployment->write();
255
		}
256
257
		$deploymentLink = \Controller::join_links(Director::absoluteBaseURL(), $deployment->Link());
258
259
		$response = $this->getAPIResponse([
260
			'message' => 'Deployment has been created',
261
			'location' => $deploymentLink,
262
			'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...
263
		], 201);
264
265
		$response->addHeader('Location', $deploymentLink);
266
267
		return $response;
268
	}
269
270
	/**
271
	 * @param \SS_HTTPRequest $request
272
	 * @return \SS_HTTPResponse
273
	 */
274
	public function start(\SS_HTTPRequest $request) {
275
		if ($request->httpMethod() !== 'POST') {
276
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
277
		}
278
279
		$this->checkSecurityToken();
280
281
		$deployment = \DNDeployment::get()->byId($request->postVar('id'));
282
		$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...
283
		if ($errorResponse instanceof \SS_HTTPResponse) {
284
			return $errorResponse;
285
		}
286
287
		// The deployment cannot be started until it has been approved, or bypassed straight to approved state
288
		if ($deployment->State !== \DNDeployment::STATE_APPROVED) {
289
			return $this->getAPIResponse(['message' => 'This deployment has not been approved. Cannot deploy'], 403);
290
		}
291
292
		// until we have a system that can invalidate currently scheduled deployments due
293
		// to emergency deploys etc, replan the deployment to check if it's still valid.
294
		$options = $deployment->getDeploymentStrategy()->getOptions();
295
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
296
		$deployment->Strategy = $strategy->toJSON();
297
298
		// if the person starting is not the one who created the deployment, update the deployer
299
		if (Member::currentUserID() !== $deployment->DeployerID) {
300
			$deployment->DeployerID = Member::currentUserID();
301
		}
302
303
		try {
304
			$deployment->getMachine()->apply(\DNDeployment::TR_QUEUE);
305
		} catch (\Exception $e) {
306
			return $this->getAPIResponse([
307
				'message' => $e->getMessage()
308
			], 400);
309
		}
310
311
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
312
313
		$response = $this->getAPIResponse([
314
			'message' => 'Deployment has been queued',
315
			'location' => $location,
316
			'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...
317
		], 201);
318
319
		$response->addHeader('Location', $location);
320
321
		return $response;
322
	}
323
324
	/**
325
	 * @param string $action
326
	 * @return string
327
	 */
328
	public function Link($action = '') {
329
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
330
	}
331
332
	/**
333
	 * @param string $name
334
	 * @return array
335
	 */
336
	public function getModel($name = '') {
337
		return [];
338
	}
339
340
	/**
341
	 * @var array
342
	 * @return \DeploymentStrategy
343
	 */
344
	protected function createStrategy($options) {
345
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
346
		$data = $strategy->toArray();
347
348
		$interface = $this->project->getRepositoryInterface();
349
		if ($this->canCompareCodeVersions($interface, $data['changes'])) {
0 ignored issues
show
Bug introduced by
It seems like $interface defined by $this->project->getRepositoryInterface() on line 348 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...
350
			$compareurl = sprintf(
351
				'%s/compare/%s...%s',
352
				$interface->URL,
353
				$data['changes']['Code version']['from'],
354
				$data['changes']['Code version']['to']
355
			);
356
			$data['changes']['Code version']['compareUrl'] = $compareurl;
357
358
			// special case for .platform.yml field so we don't show a huge blob of changes,
359
			// but rather a link to where the .platform.yml changes were made in the code
360
			if (isset($data['changes']['.platform.yml other'])) {
361
				$data['changes']['.platform.yml other']['compareUrl'] = $compareurl;
362
				$data['changes']['.platform.yml other']['description'] = '';
363
			}
364
		}
365
		$this->extend('updateDeploySummary', $data);
366
367
		// Ensure changes that would have been updated are persisted in the object,
368
		// such as the comparison URL, so that they will be written to the Strategy
369
		// field on the DNDeployment object as part of {@link createDeployment()}
370
		$strategy->setChanges($data['changes']);
371
372
		return $strategy;
373
	}
374
375
	/**
376
	 * @param ArrayData $interface
377
	 * @param $changes
378
	 * @return bool
379
	 */
380
	protected function canCompareCodeVersions(\ArrayData $interface, $changes) {
381
		if (empty($changes['Code version'])) {
382
			return false;
383
		}
384
		$codeVersion = $changes['Code version'];
385
		if (empty($interface)) {
386
			return false;
387
		}
388
		if (empty($interface->URL)) {
389
			return false;
390
		}
391
		if (empty($codeVersion['from']) || empty($codeVersion['to'])) {
392
			return false;
393
		}
394
		if (strlen($codeVersion['from']) !== 40 || strlen($codeVersion['to']) !== 40) {
395
			return false;
396
		}
397
		return true;
398
	}
399
400
	/**
401
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
402
	 * an APIResponse with the error, otherwise null.
403
	 *
404
	 * @param \DNDeployment $deployment
405
	 *
406
	 * @return null|SS_HTTPResponse
407
	 */
408 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...
409
		if (!$deployment || !$deployment->exists()) {
410
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
411
		}
412
		if ($deployment->EnvironmentID != $this->environment->ID) {
413
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
414
		}
415
		if (!$deployment->canView()) {
416
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
417
		}
418
		return null;
419
	}
420
421
}
422