Completed
Pull Request — master (#653)
by Sean
05:16
created

DeployDispatcher   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 323
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 42
lcom 1
cbo 14
dl 0
loc 323
rs 8.295
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 15 3
A index() 0 3 1
B history() 0 28 6
A upcoming() 0 10 2
A currentbuild() 0 7 2
A show() 0 8 2
A log() 0 12 3
B save() 0 30 3
B start() 0 37 5
A Link() 0 3 1
A getModel() 0 3 1
B getDeploymentData() 0 32 6
A getStackMemberData() 0 19 3
A validateDeployment() 0 9 4

How to fix   Complexity   

Complex Class

Complex classes like DeployDispatcher often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DeployDispatcher, and based on these observations, apply Extract Interface, too.

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
	public static $allowed_actions = [
15
		'history',
16
		'upcoming',
17
		'currentbuild',
18
		'show',
19
		'log',
20
		'start',
21
		'save'
22
23
	];
24
25
	/**
26
	 * @var \DNProject
27
	 */
28
	protected $project = null;
29
30
	/**
31
	 * @var \DNEnvironment
32
	 */
33
	protected $environment = null;
34
35
	/**
36
	 * @var array
37
	 */
38
	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...
39
		self::ACTION_DEPLOY
40
	];
41
42
	public function init() {
43
		parent::init();
44
45
		$this->project = $this->getCurrentProject();
46
47
		if (!$this->project) {
48
			return $this->project404Response();
49
		}
50
51
		// Performs canView permission check by limiting visible projects
52
		$this->environment = $this->getCurrentEnvironment($this->project);
53
		if (!$this->environment) {
54
			return $this->environment404Response();
55
		}
56
	}
57
58
	/**
59
	 * @param \SS_HTTPRequest $request
60
	 * @return \HTMLText|\SS_HTTPResponse
61
	 */
62
	public function index(\SS_HTTPRequest $request) {
63
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
64
	}
65
66
	/**
67
	 * @param \SS_HTTPRequest $request
68
	 * @return \SS_HTTPResponse
69
	 */
70
	public function history(SS_HTTPRequest $request) {
71
		$data = [];
72
		$list = new PaginatedList($this->environment->DeployHistory(), $this->getRequest());
0 ignored issues
show
Documentation introduced by
$this->getRequest() is of type object<SS_HTTPRequest>, but the function expects a array.

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...
73
		$list->setPageLength(4);
74
		$page = $request->getVar('page') ?: 1;
75
		if ($page > $list->TotalPages()) {
76
			$page = 1;
77
		}
78
		if ($page < 1) {
79
			$page = 1;
80
		}
81
		$start = ($page - 1) * $list->getPageLength();
82
		$list->setPageStart((int) $start);
83
		if (empty($list)) {
84
			return $this->getAPIResponse(['list' => []], 200);
85
		}
86
87
		foreach ($list as $deployment) {
88
			$data[] = $this->getDeploymentData($deployment);
89
		}
90
91
		return $this->getAPIResponse([
92
			'list' => $data,
93
			'page_length' => $list->getPageLength(),
94
			'total_pages' => $list->TotalPages(),
95
			'current_page' => $list->CurrentPage()
96
		], 200);
97
	}
98
99
	/**
100
	 * @param \SS_HTTPRequest $request
101
	 * @return \SS_HTTPResponse
102
	 */
103
	public function upcoming(SS_HTTPRequest $request) {
104
		$data = [];
105
		$list = $this->environment->UpcomingDeployments();
106
		foreach ($list as $deployment) {
107
			$data[] = $this->getDeploymentData($deployment);
108
		}
109
		return $this->getAPIResponse([
110
			'list' => $data,
111
		], 200);
112
	}
113
114
	/**
115
	 * @param \SS_HTTPRequest $request
116
	 * @return \SS_HTTPResponse
117
	 */
118
	public function currentbuild(SS_HTTPRequest $request) {
119
		$currentBuild = $this->environment->CurrentBuild();
120
		if (!$currentBuild) {
121
			return $this->getAPIResponse(['deployment' => []], 200);
122
		}
123
		return $this->getAPIResponse(['deployment' => $this->getDeploymentData($currentBuild)], 200);
124
	}
125
126
	/**
127
	 * @param \SS_HTTPRequest $request
128
	 * @return \SS_HTTPResponse
129
	 */
130
	public function show(SS_HTTPRequest $request) {
131
		$deployment = DNDeployment::get()->byId($request->param('ID'));
132
		$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...
133
		if ($errorResponse instanceof \SS_HTTPResponse) {
134
			return $errorResponse;
135
		}
136
		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...
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
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
151
		$lines = explode(PHP_EOL, $content);
152
153
		return $this->getAPIResponse(['message' => $lines, 'status' => $deployment->Status], 200);
154
	}
155
156
	public function save(\SS_HTTPRequest $request) {
157
158
		if ($request->httpMethod() !== 'POST') {
159
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
160
		}
161
162
		$this->checkSecurityToken();
163
		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...
164
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
165
		}
166
167
		// @todo the strategy should have been saved when there has been a request for an
168
		// approval or a bypass. This saved state needs to be checked if it's invalidated
169
		// if another deploy happens before this one
170
		$options = [
171
			'sha' => $request->requestVar('ref'),
172
			'ref_type' => $request->requestVar('ref_type'),
173
			'branch' => $request->requestVar('ref_name'),
174
			'summary' => $request->requestVar('summary')
175
		];
176
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
177
178
		$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...
179
		$deployment = $strategy->createDeployment();
180
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
181
		return $this->getAPIResponse([
182
			'message' => 'deployment has been created',
183
			'id' => $deployment->ID,
184
		], 201);
185
	}
186
187
	/**
188
	 * @param \SS_HTTPRequest $request
189
	 * @return \SS_HTTPResponse
190
	 */
191
	public function start(SS_HTTPRequest $request) {
192
		if ($request->httpMethod() !== 'POST') {
193
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
194
		}
195
196
		$this->checkSecurityToken();
197
198
		$deployment = DNDeployment::get()->byId($request->param('ID'));
199
200
		if (!$deployment || !$deployment->exists()) {
201
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
202
		}
203
		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...
204
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
205
		}
206
207
		// until we have a system that can invalidate currently scheduled deployments due
208
		// to emergency deploys etc, replan the deployment to check if it's still valid.
209
210
		$options = $deployment->getDeploymentStrategy()->getOptions();
211
212
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
213
		$deployment->Strategy = $strategy->toJSON();
214
		$deployment->write();
215
216
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
217
218
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
219
220
		$response = $this->getAPIResponse([
221
			'message' => 'deployment has been queued',
222
			'id' => $deployment->ID,
223
			'location' => $location
224
		], 201);
225
		$response->addHeader('Location', $location);
226
		return $response;
227
	}
228
229
	/**
230
	 * @param string $action
231
	 * @return string
232
	 */
233
	public function Link($action = '') {
234
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
235
	}
236
237
	/**
238
	 * @param string $name
239
	 * @return array
240
	 */
241
	public function getModel($name = '') {
242
		return [];
243
	}
244
245
	/**
246
	 * Return data about a single deployment for use in API response.
247
	 * @param DNDeployment $deployment
248
	 * @return array
249
	 */
250
	protected function getDeploymentData(DNDeployment $deployment) {
251
		$currentBuild = $this->environment->CurrentBuild();
252
253
		$deployer = $deployment->Deployer();
254
		$deployerData = null;
255
		if ($deployer && $deployer->exists()) {
256
			$deployerData = $this->getStackMemberData($deployer);
257
		}
258
		$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...
259
		$approverData = null;
260
		if ($approver && $approver->exists()) {
261
			$approverData = $this->getStackMemberData($approver);
262
		}
263
264
		return [
265
			'id' => $deployment->ID,
266
			'created' => $deployment->Created,
267
			'date_planned' => $deployment->DatePlanned,
0 ignored issues
show
Documentation introduced by
The property DatePlanned 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...
268
			'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...
269
			'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...
270
			'tags' => $deployment->getTags()->toArray(),
271
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
272
			'sha' => $deployment->SHA,
273
			'ref_type' => $deployment->RefType,
274
			'commit_message' => $deployment->getCommitMessage(),
275
			'commit_url' => $deployment->getCommitURL(),
276
			'deployer' => $deployerData,
277
			'approver' => $approverData,
278
			'state' => $deployment->State,
279
			'is_current_build' => $currentBuild ? ($deployment->ID === $currentBuild->ID) : null
280
		];
281
	}
282
283
	/**
284
	 * Return data about a particular {@link Member} of the stack for use in API response.
285
	 * Note that role can be null in the response. This is the case of an admin, or an operations
286
	 * user who can create the deployment but is not part of the stack roles.
287
	 *
288
	 * @param Member $member
289
	 * @return array
290
	 */
291
	protected function getStackMemberData(Member $member) {
292
		$stackMembers = $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...
293
		$role = null;
294
295
		foreach ($stackMembers as $stackMember) {
296
			if ($stackMember['MemberID'] !== $member->ID) {
297
				continue;
298
			}
299
300
			$role = $stackMember['RoleTitle'];
301
		}
302
303
		return [
304
			'id' => $member->ID,
305
			'email' => $member->Email,
306
			'role' => $role,
307
			'name' => $member->getName()
308
		];
309
	}
310
311
	/**
312
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
313
	 * an APIResponse with the error, otherwise null.
314
	 *
315
	 * @param \DNDeployment $deployment
316
	 *
317
	 * @return null|SS_HTTPResponse
318
	 */
319
	protected function validateDeployment(\DNDeployment $deployment) {
320
		if (!$deployment || !$deployment->exists()) {
321
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
322
		}
323
		if (!$deployment->canView()) {
324
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
325
		}
326
		return null;
327
	}
328
329
}
330