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

ApprovalsDispatcher::approvers()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 14
nc 6
nop 1
1
<?php
2
3
class ApprovalsDispatcher 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...
4
5
	const ACTION_APPROVALS = 'approvals';
6
7
	/**
8
	 * @var array
9
	 */
10
	public static $allowed_actions = [
11
		'approvers',
12
		'submit',
13
		'cancel',
14
		'approve',
15
		'reject'
16
	];
17
18
	/**
19
	 * @var \DNProject
20
	 */
21
	protected $project = null;
22
23
	/**
24
	 * @var \DNEnvironment
25
	 */
26
	protected $environment = null;
27
28
	/**
29
	 * @var array
30
	 */
31
	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...
32
		self::ACTION_APPROVALS
33
	];
34
35
	/**
36
	 * This is a per request cache of $this->project()->listMembers()
37
	 *
38
	 * @var null|array
39
	 */
40
	private static $_cache_project_members = null;
41
42 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...
43
		parent::init();
44
45
		$this->project = $this->getCurrentProject();
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 \SS_HTTPResponse
60
	 */
61
	public function approvers(SS_HTTPRequest $request) {
62
		$list = [];
63
64
		if (self::$_cache_project_members === null) {
65
			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...
66
		}
67
68
		foreach (self::$_cache_project_members as $data) {
69
			if ($this->canApprove(Member::get()->byId($data['MemberID']))) {
0 ignored issues
show
Bug introduced by
It seems like \Member::get()->byId($data['MemberID']) targeting DataList::byID() can also be of type object<DataObject>; however, ApprovalsDispatcher::canApprove() does only seem to accept null|object<Member>, 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...
70
				$list[] = [
71
					'id' => $data['MemberID'],
72
					'email' => $data['Email'],
73
					'role' => $data['RoleTitle'],
74
					'name' => $data['FullName']
75
				];
76
			}
77
		}
78
79
		return $this->getAPIResponse([
80
			'approvers' => $list
81
		], 200);
82
	}
83
84
	/**
85
	 * @param \SS_HTTPRequest $request
86
	 * @return \SS_HTTPResponse
87
	 */
88 View Code Duplication
	public function submit(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...
89
		if ($request->httpMethod() !== 'POST') {
90
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
91
		}
92
93
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
94
		$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...
95
		if ($errorResponse instanceof \SS_HTTPResponse) {
96
			return $errorResponse;
97
		}
98
99
		// todo set approver id from request, and if the approver has changed
100
		// we have to re-transition to TR_SUBMIT so the new approver gets
101
		// emailed from the state transition event handler
102
103
		try {
104
			$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
105
		} catch (\Exception $e) {
106
			return $this->getAPIResponse([
107
				'status' => 'FAILED',
108
				'message' => $e->getMessage()
109
			], 400);
110
		}
111
112
		return $this->getAPIResponse([
113
			'status' => 'OK',
114
			'id' => $deployment->ID,
115
			'new_status' => DNDeployment::STATE_SUBMITTED
116
		], 200);
117
	}
118
119
	/**
120
	 * @param \SS_HTTPRequest $request
121
	 * @return \SS_HTTPResponse
122
	 */
123 View Code Duplication
	public function cancel(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...
124
		if ($request->httpMethod() !== 'POST') {
125
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
126
		}
127
128
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
129
		$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...
130
		if ($errorResponse instanceof \SS_HTTPResponse) {
131
			return $errorResponse;
132
		}
133
134
		// @todo permission checking for cancelling an approval request
135
136
		try {
137
			$deployment->getMachine()->apply(DNDeployment::TR_NEW);
138
		} catch (\Exception $e) {
139
			return $this->getAPIResponse([
140
				'status' => 'FAILED',
141
				'message' => $e->getMessage()
142
			], 400);
143
		}
144
145
		return $this->getAPIResponse([
146
			'status' => 'OK',
147
			'id' => $deployment->ID,
148
			'new_status' => DNDeployment::STATE_NEW
149
		], 200);
150
	}
151
152
	/**
153
	 * @param \SS_HTTPRequest $request
154
	 * @return \SS_HTTPResponse
155
	 */
156 View Code Duplication
	public function approve(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...
157
		if ($request->httpMethod() !== 'POST') {
158
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
159
		}
160
161
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
162
		$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...
163
		if ($errorResponse instanceof \SS_HTTPResponse) {
164
			return $errorResponse;
165
		}
166
		if (!$this->canApprove()) {
167
			return $this->getAPIResponse(['message' => 'You are not authorised to approve this deployment'], 403);
168
		}
169
170
		try {
171
			$deployment->getMachine()->apply(DNDeployment::TR_APPROVE);
172
		} catch (\Exception $e) {
173
			return $this->getAPIResponse([
174
				'status' => 'FAILED',
175
				'message' => $e->getMessage()
176
			], 400);
177
		}
178
179
		return $this->getAPIResponse([
180
			'status' => 'OK',
181
			'id' => $deployment->ID,
182
			'new_status' => DNDeployment::STATE_APPROVED
183
		], 200);
184
	}
185
186
	/**
187
	 * @param \SS_HTTPRequest $request
188
	 * @return \SS_HTTPResponse
189
	 */
190 View Code Duplication
	public function reject(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...
191
		if ($request->httpMethod() !== 'POST') {
192
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
193
		}
194
195
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
196
		$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...
197
		if ($errorResponse instanceof \SS_HTTPResponse) {
198
			return $errorResponse;
199
		}
200
		// can reject permissions are the same as can approve
201
		if (!$this->canApprove()) {
202
			return $this->getAPIResponse(['message' => 'You are not authorised to reject this deployment'], 403);
203
		}
204
205
		try {
206
			$deployment->getMachine()->apply(DNDeployment::TR_REJECT);
207
		} catch (\Exception $e) {
208
			return $this->getAPIResponse([
209
				'status' => 'FAILED',
210
				'message' => $e->getMessage()
211
			], 400);
212
		}
213
214
		return $this->getAPIResponse([
215
			'status' => 'OK',
216
			'id' => $deployment->ID,
217
			'new_status' => DNDeployment::STATE_REJECTED
218
		], 200);
219
	}
220
221
	/**
222
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
223
	 * an APIResponse with the error, otherwise null.
224
	 *
225
	 * @param \DNDeployment $deployment
226
	 *
227
	 * @return null|SS_HTTPResponse
228
	 */
229 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...
230
		if (!$deployment || !$deployment->exists()) {
231
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
232
		}
233
		if ($deployment->EnvironmentID != $this->environment->ID) {
234
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
235
		}
236
		if (!$deployment->canView()) {
237
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
238
		}
239
		return null;
240
	}
241
242
	protected function canApprove(Member $member = null) {
243
		if (!$member) {
244
			$member = Member::currentUser();
245
		}
246
		if (!$member) {
247
			return false;
248
		}
249
		if (Permission::checkMember($member, 'ADMIN')) {
250
			return true;
251
		}
252
253
		if (self::$_cache_project_members === null) {
254
			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...
255
		}
256
257
		foreach (self::$_cache_project_members as $data) {
258
			if ($data['MemberID'] == $member->ID && in_array($data['RoleTitle'], [
259
				GroupExtension::STACK_MANAGER,
260
				GroupExtension::RELEASE_MANAGER
261
			])) {
262
				return true;
263
			}
264
		}
265
266
		return false;
267
	}
268
269
	/**
270
	 * @param string $name
271
	 * @return array
272
	 */
273
	public function getModel($name = '') {
274
		return [];
275
	}
276
277
	/**
278
	 * @param string $action
279
	 * @return string
280
	 */
281
	public function Link($action = '') {
282
		return \Controller::join_links($this->environment->Link(), self::ACTION_APPROVALS, $action);
283
	}
284
285
}
286