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

ApprovalsDispatcher   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 281
Duplicated Lines 29.89 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 38
lcom 1
cbo 11
dl 84
loc 281
rs 8.3999
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 14 14 3
B approvers() 0 22 4
C submit() 0 36 7
B cancel() 0 26 4
B approve() 29 29 5
B reject() 29 29 5
B validateDeployment() 12 12 5
A getApprovers() 0 13 3
A getModel() 0 3 1
A Link() 0 3 1

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
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
	const ALLOW_APPROVAL = 'ALLOW_APPROVAL';
8
9
	/**
10
	 * @var array
11
	 */
12
	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...
13
		'approvers',
14
		'submit',
15
		'cancel',
16
		'approve',
17
		'reject'
18
	];
19
20
	private static $dependencies = [
21
		'formatter' => '%$DeploynautAPIFormatter'
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_APPROVALS
39
	];
40
41
	/**
42
	 * This is a per request cache of $this->project()->listMembers()
43
	 * @var null|array
44
	 */
45
	private static $_cache_project_members = null;
46
47 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...
48
		parent::init();
49
50
		$this->project = $this->getCurrentProject();
51
		if (!$this->project) {
52
			return $this->project404Response();
53
		}
54
55
		// Performs canView permission check by limiting visible projects
56
		$this->environment = $this->getCurrentEnvironment($this->project);
57
		if (!$this->environment) {
58
			return $this->environment404Response();
59
		}
60
	}
61
62
	/**
63
	 * @param \SS_HTTPRequest $request
64
	 * @return \SS_HTTPResponse
65
	 */
66
	public function approvers(SS_HTTPRequest $request) {
67
		$list = [];
68
69
		if (self::$_cache_project_members === null) {
70
			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...
71
		}
72
73
		foreach (self::$_cache_project_members as $data) {
74
			if ($this->project->allowed(self::ALLOW_APPROVAL, 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, DNProject::allowed() 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...
75
				$list[] = [
76
					'id' => $data['MemberID'],
77
					'email' => $data['Email'],
78
					'role' => $data['RoleTitle'],
79
					'name' => $data['FullName']
80
				];
81
			}
82
		}
83
84
		return $this->getAPIResponse([
85
			'approvers' => $list
86
		], 200);
87
	}
88
89
	/**
90
	 * @param \SS_HTTPRequest $request
91
	 * @return \SS_HTTPResponse
92
	 */
93
	public function submit(SS_HTTPRequest $request) {
94
		if ($request->httpMethod() !== 'POST') {
95
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
96
		}
97
98
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
99
		$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...
100
		if ($errorResponse instanceof \SS_HTTPResponse) {
101
			return $errorResponse;
102
		}
103
104
		$approver = Member::get()->byId($request->postVar('approver_id'));
105
		if (!$approver || !$approver->exists()) {
106
			return $this->getAPIResponse(['message' => 'Invalid approver. Does not exist'], 403);
107
		}
108
		if (!$this->project->allowed(self::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...
109
			return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
110
		}
111
112
		try {
113
			$deployment->ApproverID = $approver->ID;
114
			$deployment->write();
115
116
			$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
117
		} catch (\Exception $e) {
118
			return $this->getAPIResponse([
119
				'status' => 'FAILED',
120
				'message' => $e->getMessage()
121
			], 400);
122
		}
123
124
		return $this->getAPIResponse([
125
			'status' => 'OK',
126
			'deployment' => $this->formatter->getDeploymentData($deployment)
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<ApprovalsDispatcher>. 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...
127
		], 200);
128
	}
129
130
	/**
131
	 * @param \SS_HTTPRequest $request
132
	 * @return \SS_HTTPResponse
133
	 */
134
	public function cancel(SS_HTTPRequest $request) {
135
		if ($request->httpMethod() !== 'POST') {
136
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
137
		}
138
139
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
140
		$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...
141
		if ($errorResponse instanceof \SS_HTTPResponse) {
142
			return $errorResponse;
143
		}
144
145
		// @todo permission checking for cancelling an approval request
146
		try {
147
			$deployment->getMachine()->apply(DNDeployment::TR_NEW);
148
		} catch (\Exception $e) {
149
			return $this->getAPIResponse([
150
				'status' => 'FAILED',
151
				'message' => $e->getMessage()
152
			], 400);
153
		}
154
155
		return $this->getAPIResponse([
156
			'status' => 'OK',
157
			'deployment' => $this->formatter->getDeploymentData($deployment)
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<ApprovalsDispatcher>. 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...
158
		], 200);
159
	}
160
161
	/**
162
	 * @param \SS_HTTPRequest $request
163
	 * @return \SS_HTTPResponse
164
	 */
165 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...
166
		if ($request->httpMethod() !== 'POST') {
167
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
168
		}
169
170
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
171
		$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...
172
		if ($errorResponse instanceof \SS_HTTPResponse) {
173
			return $errorResponse;
174
		}
175
176
		if (!$this->project->allowed(self::ALLOW_APPROVAL, 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, DNProject::allowed() 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...
177
			return $this->getAPIResponse(['message' => 'You are not authorised to approve this deployment'], 403);
178
		}
179
180
		try {
181
			$deployment->getMachine()->apply(DNDeployment::TR_APPROVE);
182
		} catch (\Exception $e) {
183
			return $this->getAPIResponse([
184
				'status' => 'FAILED',
185
				'message' => $e->getMessage()
186
			], 400);
187
		}
188
189
		return $this->getAPIResponse([
190
			'status' => 'OK',
191
			'deployment' => $this->formatter->getDeploymentData($deployment)
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<ApprovalsDispatcher>. 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...
192
		], 200);
193
	}
194
195
	/**
196
	 * @param \SS_HTTPRequest $request
197
	 * @return \SS_HTTPResponse
198
	 */
199 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...
200
		if ($request->httpMethod() !== 'POST') {
201
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
202
		}
203
204
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
205
		$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...
206
		if ($errorResponse instanceof \SS_HTTPResponse) {
207
			return $errorResponse;
208
		}
209
		// reject permissions are the same as can approve
210
		if (!$this->project->allowed(self::ALLOW_APPROVAL, 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, DNProject::allowed() 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...
211
			return $this->getAPIResponse(['message' => 'You are not authorised to reject this deployment'], 403);
212
		}
213
214
		try {
215
			$deployment->getMachine()->apply(DNDeployment::TR_REJECT);
216
		} catch (\Exception $e) {
217
			return $this->getAPIResponse([
218
				'status' => 'FAILED',
219
				'message' => $e->getMessage()
220
			], 400);
221
		}
222
223
		return $this->getAPIResponse([
224
			'status' => 'OK',
225
			'deployment' => $this->formatter->getDeploymentData($deployment)
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<ApprovalsDispatcher>. 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...
226
		], 200);
227
	}
228
229
	/**
230
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
231
	 * an APIResponse with the error, otherwise null.
232
	 *
233
	 * @param \DNDeployment $deployment
234
	 *
235
	 * @return null|SS_HTTPResponse
236
	 */
237 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...
238
		if (!$deployment || !$deployment->exists()) {
239
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
240
		}
241
		if ($deployment->EnvironmentID != $this->environment->ID) {
242
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
243
		}
244
		if (!$deployment->canView()) {
245
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
246
		}
247
		return null;
248
	}
249
250
	/**
251
	 * @return ArrayList
252
	 */
253
	protected function getApprovers() {
254
		$list = new ArrayList();
255
		if (self::$_cache_project_members === null) {
256
			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...
257
		}
258
		foreach (self::$_cache_project_members as $data) {
259
			$list->push(new ArrayData([
260
				'ID' => $member->ID,
0 ignored issues
show
Bug introduced by
The variable $member does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
261
				'Role' => $data['RoleTitle']
262
			]));
263
		}
264
		return $list;
265
	}
266
267
	/**
268
	 * @param string $name
269
	 * @return array
270
	 */
271
	public function getModel($name = '') {
272
		return [];
273
	}
274
275
	/**
276
	 * @param string $action
277
	 * @return string
278
	 */
279
	public function Link($action = '') {
280
		return \Controller::join_links($this->environment->Link(), self::ACTION_APPROVALS, $action);
281
	}
282
283
}
284