Completed
Pull Request — master (#681)
by Sean
06:17
created

DeployDispatcher::validateDeployment()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
dl 12
loc 12
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
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...
Coding Style introduced by
The property $_cache_project_members 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 $_cache_current_build 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...
8
9
	const ACTION_DEPLOY = 'deploys';
10
11
	/**
12
	 * @var array
13
	 */
14
	public static $allowed_actions = [
15
		'history',
16
		'upcoming',
17
		'currentbuild',
18
		'show',
19
		'log',
20
		'start',
21
		'save'
22
	];
23
24
	/**
25
	 * @var \DNProject
26
	 */
27
	protected $project = null;
28
29
	/**
30
	 * @var \DNEnvironment
31
	 */
32
	protected $environment = null;
33
34
	/**
35
	 * @var array
36
	 */
37
	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...
38
		self::ACTION_DEPLOY
39
	];
40
41
	/**
42
	 * This is a per request cache of $this->project()->listMembers()
43
	 *
44
	 * @var null|array
45
	 */
46
	private static $_cache_project_members = null;
47
48
	/**
49
	 * This is a per request cache of $this->environment->CurrentBuild();
50
	 *
51
	 * @var null|DNDeployment
52
	 */
53
	private static $_cache_current_build = null;
54
55
	public function init() {
56
		parent::init();
57
58
		$this->project = $this->getCurrentProject();
59
60
		if (!$this->project) {
61
			return $this->project404Response();
62
		}
63
64
		// Performs canView permission check by limiting visible projects
65
		$this->environment = $this->getCurrentEnvironment($this->project);
66
		if (!$this->environment) {
67
			return $this->environment404Response();
68
		}
69
	}
70
71
	/**
72
	 * @param \SS_HTTPRequest $request
73
	 * @return \HTMLText|\SS_HTTPResponse
74
	 */
75
	public function index(\SS_HTTPRequest $request) {
76
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
77
	}
78
79
	/**
80
	 * @param \SS_HTTPRequest $request
81
	 * @return \SS_HTTPResponse
82
	 */
83 View Code Duplication
	public function history(SS_HTTPRequest $request) {
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...
84
		$data = [];
85
86
		$list = $this->environment->DeployHistory('DeployStarted');
87
88
		foreach ($list as $deployment) {
89
			$data[] = $this->getDeploymentData($deployment);
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 View Code Duplication
	public function upcoming(SS_HTTPRequest $request) {
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...
102
		$data = [];
103
		$list = $this->environment->UpcomingDeployments();
104
		foreach ($list as $deployment) {
105
			$data[] = $this->getDeploymentData($deployment);
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->getDeploymentData($currentBuild)], 200);
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->getDeploymentData($deployment)], 200);
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...
135
	}
136
137
	/**
138
	 * @param \SS_HTTPRequest $request
139
	 * @return \SS_HTTPResponse
140
	 */
141
	public function log(SS_HTTPRequest $request) {
142
		$deployment = DNDeployment::get()->byId($request->param('ID'));
143
		$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...
144
		if ($errorResponse instanceof \SS_HTTPResponse) {
145
			return $errorResponse;
146
		}
147
		$log = $deployment->log();
148
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
149
		$lines = explode(PHP_EOL, $content);
150
151
		return $this->getAPIResponse([
152
			'message' => $lines,
153
			'status' => $deployment->Status,
154
			'deployment' => $this->getDeploymentData($deployment),
0 ignored issues
show
Compatibility introduced by
$deployment of type object<DataObject> is not a sub-type of object<DNDeployment>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
155
		], 200);
156
	}
157
158
	public function save(\SS_HTTPRequest $request) {
159
		if ($request->httpMethod() !== 'POST') {
160
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
161
		}
162
163
		$this->checkSecurityToken();
164
		if (!$this->environment->canDeploy(Member::currentUser())) {
0 ignored issues
show
Bug introduced by
It seems like \Member::currentUser() targeting Member::currentUser() can also be of type object<DataObject>; however, DNEnvironment::canDeploy() does only seem to accept object<Member>|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
165
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
166
		}
167
168
		// @todo the strategy should have been saved when there has been a request for an
169
		// approval or a bypass. This saved state needs to be checked if it's invalidated
170
		// if another deploy happens before this one
171
		$isBranchDeploy = (int) $request->requestVar('ref_type') === GitDispatcher::REF_TYPE_BRANCH;
172
173
		$options = [
174
			'sha' => $request->requestVar('ref'),
175
			'ref_type' => $request->requestVar('ref_type'),
176
			'branch' => $isBranchDeploy ? $request->requestVar('ref_name') : null,
177
			'summary' => $request->requestVar('summary')
178
		];
179
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
180
181
		$strategy->fromArray($request->requestVars());
0 ignored issues
show
Documentation introduced by
$request->requestVars() is of type array|null, but the function expects a string.

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...
182
		$deployment = $strategy->createDeployment();
183
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
184
		return $this->getAPIResponse([
185
			'message' => 'deployment has been created',
186
			'id' => $deployment->ID,
187
			'deployment' => $this->getDeploymentData($deployment),
188
		], 201);
189
	}
190
191
	/**
192
	 * @param \SS_HTTPRequest $request
193
	 * @return \SS_HTTPResponse
194
	 */
195
	public function start(SS_HTTPRequest $request) {
196
		if ($request->httpMethod() !== 'POST') {
197
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
198
		}
199
200
		$this->checkSecurityToken();
201
202
		$deployment = DNDeployment::get()->byId($request->param('ID'));
203
204
		if (!$deployment || !$deployment->exists()) {
205
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
206
		}
207
208
		// @todo this is going to restrict team members from deploying.
209
		if (!$this->environment->canDeploy(Member::currentUser())) {
0 ignored issues
show
Bug introduced by
It seems like \Member::currentUser() targeting Member::currentUser() can also be of type object<DataObject>; however, DNEnvironment::canDeploy() does only seem to accept object<Member>|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
210
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
211
		}
212
213
		// until we have a system that can invalidate currently scheduled deployments due
214
		// to emergency deploys etc, replan the deployment to check if it's still valid.
215
216
		$options = $deployment->getDeploymentStrategy()->getOptions();
217
218
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
219
		$deployment->Strategy = $strategy->toJSON();
220
		$deployment->write();
221
222
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
223
224
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
225
226
		$response = $this->getAPIResponse([
227
			'message' => 'deployment has been queued',
228
			'id' => $deployment->ID,
229
			'location' => $location,
230
			'deployment' => $this->getDeploymentData($deployment),
0 ignored issues
show
Compatibility introduced by
$deployment of type object<DataObject> is not a sub-type of object<DNDeployment>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
231
		], 201);
232
		$response->addHeader('Location', $location);
233
		return $response;
234
	}
235
236
	/**
237
	 * @param string $action
238
	 * @return string
239
	 */
240
	public function Link($action = '') {
241
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
242
	}
243
244
	/**
245
	 * @param string $name
246
	 * @return array
247
	 */
248
	public function getModel($name = '') {
249
		return [];
250
	}
251
252
	/**
253
	 * Return data about a single deployment for use in API response.
254
	 * @param DNDeployment $deployment
255
	 * @return array
256
	 */
257
	protected function getDeploymentData(DNDeployment $deployment) {
258
		if (self::$_cache_current_build === null) {
259
			self::$_cache_current_build = $this->environment->CurrentBuild();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->environment->CurrentBuild() can also be of type false. However, the property $_cache_current_build is declared as type null|object<DNDeployment>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
260
		}
261
262
		$deployer = $deployment->Deployer();
263
		$deployerData = null;
264
		if ($deployer && $deployer->exists()) {
265
			$deployerData = $this->getStackMemberData($deployer);
266
		}
267
		$approver = $deployment->Approver();
0 ignored issues
show
Documentation Bug introduced by
The method Approver does not exist on object<DNDeployment>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
268
		$approverData = null;
269
		if ($approver && $approver->exists()) {
270
			$approverData = $this->getStackMemberData($approver);
271
		}
272
273
		// failover for older deployments
274
		$started = $deployment->Created;
275
		$startedNice = $deployment->obj('Created')->Nice();
276
		if($deployment->DeployStarted) {
277
			$started = $deployment->DeployStarted;
278
			$startedNice = $deployment->obj('DeployStarted')->Nice();
279
		}
280
281
		$requested = $deployment->Created;
282
		$requestedNice = $deployment->obj('Created')->Nice();
283
		if($deployment->DeployRequested) {
284
			$requested = $deployment->DeployRequested;
285
			$requestedNice = $deployment->obj('DeployRequested')->Nice();
286
		}
287
288
		$isCurrentBuild = self::$_cache_current_build ? ($deployment->ID === self::$_cache_current_build->ID) : false;
289
290
		return [
291
			'id' => $deployment->ID,
292
			'date_created' => $deployment->Created,
293
			'date_created_nice' => $deployment->obj('Created')->Nice(),
294
			'date_started' => $started,
295
			'date_started_nice' => $startedNice,
296
			'date_requested' => $requested,
297
			'date_requested_nice' => $requestedNice,
298
			'date_updated' => $deployment->LastEdited,
299
			'date_updated_nice' => $deployment->obj('LastEdited')->Nice(),
300
			'summary' => $deployment->Summary,
0 ignored issues
show
Bug introduced by
The property Summary does not seem to exist. Did you mean summary_fields?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
301
			'branch' => $deployment->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...
302
			'tags' => $deployment->getTags()->toArray(),
303
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
304
			'sha' => $deployment->SHA,
305
			'short_sha' => substr($deployment->SHA, 0, 7),
306
			'ref_type' => $deployment->RefType,
307
			'commit_message' => $deployment->getCommitMessage(),
308
			'commit_url' => $deployment->getCommitURL(),
309
			'deployer' => $deployerData,
310
			'approver' => $approverData,
311
			'state' => $deployment->State,
312
			'is_current_build' => $isCurrentBuild
313
		];
314
	}
315
316
	/**
317
	 * Return data about a particular {@link Member} of the stack for use in API response.
318
	 * Note that role can be null in the response. This is the case of an admin, or an operations
319
	 * user who can create the deployment but is not part of the stack roles.
320
	 *
321
	 * @param Member $member
322
	 * @return array
323
	 */
324
	protected function getStackMemberData(Member $member) {
325
		if (self::$_cache_project_members === null) {
326
			self::$_cache_project_members = $this->project->listMembers();
0 ignored issues
show
Documentation Bug introduced by
The method listMembers does not exist on object<DNProject>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
327
		}
328
329
		$role = null;
330
331
		foreach (self::$_cache_project_members as $stackMember) {
332
			if ($stackMember['MemberID'] !== $member->ID) {
333
				continue;
334
			}
335
336
			$role = $stackMember['RoleTitle'];
337
		}
338
339
		return [
340
			'id' => $member->ID,
341
			'email' => $member->Email,
342
			'role' => $role,
343
			'name' => $member->getName()
344
		];
345
	}
346
347
	/**
348
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
349
	 * an APIResponse with the error, otherwise null.
350
	 *
351
	 * @param \DNDeployment $deployment
352
	 *
353
	 * @return null|SS_HTTPResponse
354
	 */
355 View Code Duplication
	protected function validateDeployment(\DNDeployment $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...
356
		if (!$deployment || !$deployment->exists()) {
357
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
358
		}
359
		if (!$deployment->canView()) {
360
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
361
		}
362
		if ($deployment->EnvironmentID != $this->environment->ID) {
363
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
364
		}
365
		return null;
366
	}
367
368
}
369