Completed
Push — master ( 942a32...26de0d )
by Stig
01:23
created

DeployDispatcher::createStrategy()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 17
nc 3
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
		'upcoming',
17
		'currentbuild',
18
		'show',
19
		'delete',
20
		'log',
21
		'redeploy',
22
		'summary',
23
		'createdeployment',
24
		'start'
25
	];
26
27
	private static $dependencies = [
28
		'formatter' => '%$DeploynautAPIFormatter'
29
	];
30
31
	/**
32
	 * @var \DNProject
33
	 */
34
	protected $project = null;
35
36
	/**
37
	 * @var \DNEnvironment
38
	 */
39
	protected $environment = null;
40
41
	/**
42
	 * @var array
43
	 */
44
	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...
45
		self::ACTION_DEPLOY
46
	];
47
48
	public function init() {
49
		parent::init();
50
51
		$this->project = $this->getCurrentProject();
52
53
		if (!$this->project) {
54
			return $this->project404Response();
55
		}
56
57
		// Performs canView permission check by limiting visible projects
58
		$this->environment = $this->getCurrentEnvironment($this->project);
59
		if (!$this->environment) {
60
			return $this->environment404Response();
61
		}
62
	}
63
64
	/**
65
	 * @param \SS_HTTPRequest $request
66
	 * @return \HTMLText|\SS_HTTPResponse
67
	 */
68
	public function index(\SS_HTTPRequest $request) {
69
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
70
	}
71
72
	/**
73
	 * @param \SS_HTTPRequest $request
74
	 * @return \SS_HTTPResponse
75
	 */
76
	public function history(\SS_HTTPRequest $request) {
77
		$data = [];
78
79
		$list = $this->environment->DeployHistory('DeployStarted');
80
81
		$fromTimestamp = $request->requestVar('from');
82
		if ($fromTimestamp) {
83
			$from = SS_Datetime::create();
84
			$from->setValue($fromTimestamp);
85
			$list = $list->filter('LastEdited:GreaterThan', $from->Format('Y-m-d H:i:s'));
86
		}
87
88
		foreach ($list as $deployment) {
89
			$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...
90
		}
91
92
		return $this->getAPIResponse([
93
			'list' => $data,
94
		], 200);
95
	}
96
97
	/**
98
	 * @param \SS_HTTPRequest $request
99
	 * @return \SS_HTTPResponse
100
	 */
101
	public function upcoming(\SS_HTTPRequest $request) {
102
		$data = [];
103
		$list = $this->environment->UpcomingDeployments();
0 ignored issues
show
Bug introduced by
The method UpcomingDeployments() does not exist on DNEnvironment. Did you maybe mean Deployments()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
104
		foreach ($list as $deployment) {
105
			$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...
106
		}
107
		return $this->getAPIResponse([
108
			'list' => $data,
109
		], 200);
110
	}
111
112
	/**
113
	 * @param \SS_HTTPRequest $request
114
	 * @return \SS_HTTPResponse
115
	 */
116
	public function currentbuild(\SS_HTTPRequest $request) {
117
		$currentBuild = $this->environment->CurrentBuild();
118
		if (!$currentBuild) {
119
			return $this->getAPIResponse(['deployment' => []], 200);
120
		}
121
		return $this->getAPIResponse(['deployment' => $this->formatter->getDeploymentData($currentBuild)], 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...
122
	}
123
124
	/**
125
	 * @param \SS_HTTPRequest $request
126
	 * @return \SS_HTTPResponse
127
	 */
128
	public function show(\SS_HTTPRequest $request) {
129
		$deployment = \DNDeployment::get()->byId($request->param('ID'));
130
		$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...
131
		if ($errorResponse instanceof \SS_HTTPResponse) {
132
			return $errorResponse;
133
		}
134
		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...
135
	}
136
137
	/**
138
	 * @param \SS_HTTPRequest $request
139
	 * @return \SS_HTTPResponse
140
	 */
141
	public function delete(\SS_HTTPRequest $request) {
142
		if ($request->httpMethod() !== 'POST') {
143
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
144
		}
145
146
		$this->checkSecurityToken();
147
148
		$deployment = \DNDeployment::get()->byId($request->postVar('id'));
149
		$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...
150
		if ($errorResponse instanceof \SS_HTTPResponse) {
151
			return $errorResponse;
152
		}
153
154
		$id = $deployment->ID;
155
		$deployment->delete();
156
157
		return $this->getAPIResponse([
158
			'id' => $id,
159
			'message' => 'Deployment has been deleted'
160
		], 201);
161
	}
162
163
	/**
164
	 * @param \SS_HTTPRequest $request
165
	 * @return \SS_HTTPResponse
166
	 */
167
	public function log(\SS_HTTPRequest $request) {
168
		$deployment = \DNDeployment::get()->byId($request->param('ID'));
169
		$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...
170
		if ($errorResponse instanceof \SS_HTTPResponse) {
171
			return $errorResponse;
172
		}
173
		$log = $deployment->log();
174
		$lines = [];
175
		if ($log->exists()) {
176
			$lines = explode(PHP_EOL, $log->content());
177
		}
178
179
		return $this->getAPIResponse([
180
			'message' => $lines,
181
			'status' => $deployment->Status,
182
			'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...
183
		], 200);
184
	}
185
186
	/**
187
	 * @param \SS_HTTPRequest $request
188
	 * @return \SS_HTTPResponse
189
	 */
190
	public function redeploy(\SS_HTTPRequest $request) {
191
		$currentBuild = $this->environment->CurrentBuild();
192
		if (!$currentBuild || !$currentBuild->exists()) {
193
			return $this->redirect(Controller::join_links(
194
				$this->environment->Link(\EnvironmentOverview::ACTION_OVERVIEW),
195
				'deployment',
196
				'new'
197
			));
198
		}
199
200
		$strategy = $this->environment->Backend()->planDeploy($this->environment, [
201
			'sha' => $currentBuild->SHA,
202
			'ref_type' => \GitDispatcher::REF_TYPE_PREVIOUS,
203
			'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...
204
		]);
205
		$deployment = $strategy->createDeployment();
206
207
		return $this->redirect($deployment->Link());
208
	}
209
210
	/**
211
	 * Return a summary of the deployment changes without creating the deployment.
212
	 *
213
	 * @param \SS_HTTPRequest $request
214
	 * @return \SS_HTTPResponse
215
	 */
216
	public function summary(\SS_HTTPRequest $request) {
217
		if ($request->httpMethod() !== 'POST') {
218
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
219
		}
220
		$this->checkSecurityToken();
221
222
		$options = ['sha' => $request->postVar('ref')];
223 View Code Duplication
		if ($request->requestVar('options')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

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