Completed
Push — master ( 4a7c4d...4dc0f5 )
by Sean
14:43 queued 08:41
created

DeployDispatcher   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 301
Duplicated Lines 4.98 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 13
dl 15
loc 301
rs 8.6
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 15 15 3
A index() 0 3 1
B history() 0 27 6
A currentbuild() 0 7 2
A show() 0 8 2
A log() 0 12 3
B save() 0 30 3
B start() 0 32 2
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   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
		'currentbuild',
17
		'show',
18
		'log',
19
		'start',
20
		'save'
21
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 View Code Duplication
	public function init() {
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...
42
		parent::init();
43
44
		$this->project = $this->getCurrentProject();
45
46
		if (!$this->project) {
47
			return $this->project404Response();
48
		}
49
50
		// Performs canView permission check by limiting visible projects
51
		$this->environment = $this->getCurrentEnvironment($this->project);
52
		if (!$this->environment) {
53
			return $this->environment404Response();
54
		}
55
	}
56
57
	/**
58
	 * @param \SS_HTTPRequest $request
59
	 * @return \HTMLText|\SS_HTTPResponse
60
	 */
61
	public function index(\SS_HTTPRequest $request) {
62
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
63
	}
64
65
	/**
66
	 * @param \SS_HTTPRequest $request
67
	 * @return \SS_HTTPResponse
68
	 */
69
	public function history(SS_HTTPRequest $request) {
70
		$data = [];
71
		$list = $this->DeployHistory();
0 ignored issues
show
Deprecated Code introduced by
The method DNRoot::DeployHistory() has been deprecated with message: 2.0.0 - moved to DeployDispatcher

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

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