Completed
Push — master ( b26f23...9f01bf )
by Sean
03:51
created

DeployDispatcher::delete()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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