Completed
Push — master ( 96acc8...3bb34a )
by Stig
01:14
created

DeployDispatcher::summary()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 23
Code Lines 15

Duplication

Lines 5
Ratio 21.74 %

Importance

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