Completed
Push — master ( e20418...1f7fe6 )
by Stig
11:13 queued 07:20
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...
4
5
	const ACTION_APPROVALS = 'approvals';
6
7
	const ALLOW_APPROVAL = 'ALLOW_APPROVAL';
8
9
	const ALLOW_APPROVAL_BYPASS = 'ALLOW_APPROVAL_BYPASS';
10
11
	/**
12
	 * @var array
13
	 */
14
	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...
15
		'submit',
16
		'cancel',
17
		'approve',
18
		'reject'
19
	];
20
21
	private static $dependencies = [
22
		'formatter' => '%$DeploynautAPIFormatter'
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_APPROVALS
40
	];
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 submit(\SS_HTTPRequest $request) {
62
		if ($request->httpMethod() !== 'POST') {
63
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
64
		}
65
66
		$this->checkSecurityToken();
67
68
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
69
		$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...
70
		if ($errorResponse instanceof \SS_HTTPResponse) {
71
			return $errorResponse;
72
		}
73
74
		$approver = Member::get()->byId($request->postVar('approver_id'));
75
		if ($approver && $approver->exists()) {
76
			if (!$this->project->allowed(ApprovalsDispatcher::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...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
77
				return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
78
			}
79
80
			$deployment->ApproverID = $approver->ID;
81
			$deployment->write();
82
		}
83
84
		// title and summary may have changed, ensure they are saved
85
		if ($request->postVar('title')) {
86
			$deployment->Title = $request->postVar('title');
87
		}
88
		if ($request->postVar('summary')) {
89
			$deployment->Summary = $request->postVar('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...
90
		}
91
92
		try {
93
			$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
94
		} catch (\Exception $e) {
95
			return $this->getAPIResponse([
96
				'message' => $e->getMessage()
97
			], 400);
98
		}
99
100
		return $this->getAPIResponse([
101
			'message' => 'Deployment request has been submitted',
102
			'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...
103
		], 200);
104
	}
105
106
	/**
107
	 * @param \SS_HTTPRequest $request
108
	 * @return \SS_HTTPResponse
109
	 */
110
	public function cancel(\SS_HTTPRequest $request) {
111
		if ($request->httpMethod() !== 'POST') {
112
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
113
		}
114
115
		$this->checkSecurityToken();
116
117
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
118
		$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...
119
		if ($errorResponse instanceof \SS_HTTPResponse) {
120
			return $errorResponse;
121
		}
122
123
		// if the person cancelling is not the one who created the deployment, update the deployer
124
		if (Member::currentUserID() !== $deployment->DeployerID) {
125
			$deployment->DeployerID = Member::currentUserID();
126
			$deployment->write();
127
		}
128
129
		try {
130
			$deployment->getMachine()->apply(DNDeployment::TR_NEW);
131
		} catch (\Exception $e) {
132
			return $this->getAPIResponse([
133
				'message' => $e->getMessage()
134
			], 400);
135
		}
136
137
		return $this->getAPIResponse([
138
			'message' => 'Deployment request has been cancelled',
139
			'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...
140
		], 200);
141
	}
142
143
	/**
144
	 * @param \SS_HTTPRequest $request
145
	 * @return \SS_HTTPResponse
146
	 */
147
	public function approve(\SS_HTTPRequest $request) {
148
		if ($request->httpMethod() !== 'POST') {
149
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
150
		}
151
152
		$this->checkSecurityToken();
153
154
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
155
		$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...
156
		if ($errorResponse instanceof \SS_HTTPResponse) {
157
			return $errorResponse;
158
		}
159
160
		// ensure we have either bypass or approval permission of the logged in user
161
		if (
162
			!$this->project->allowed(self::ALLOW_APPROVAL_BYPASS, 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...
163
			|| !$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...
164
		) {
165
			return $this->getAPIResponse(['message' => 'You are not authorised to approve or bypass this deployment'], 403);
166
		}
167
168
		// check for specific permission depending on the current state of the deployment:
169
		// submitted => approved requires approval permissions
170
		// new => approved requires bypass permissions.
171 View Code Duplication
		if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
172
			$deployment->State === DNDeployment::STATE_SUBMITTED
173
			&& !$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...
174
		) {
175
			return $this->getAPIResponse(['message' => 'You are not authorised to approve this deployment'], 403);
176
		}
177 View Code Duplication
		if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
178
			$deployment->State === DNDeployment::STATE_NEW
179
			&& !$this->project->allowed(self::ALLOW_APPROVAL_BYPASS, 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...
180
		) {
181
			return $this->getAPIResponse(['message' => 'You are not authorised to bypass approval of this deployment'], 403);
182
		}
183
184
		if ($deployment->State === DNDeployment::STATE_NEW) {
185
			// Bypassing approval: Ensure that approver is not set. This may happen when someone has requested approval,
186
			// cancelled approval, then bypassed.
187
			$deployment->ApproverID = 0;
188
			$deployment->write();
189
		} else {
190
			// if the current user is not the person who was selected for approval on submit, but they got
191
			// here because they still have permission, then change the approver to the current user
192
			if (Member::currentUserID() !== $deployment->ApproverID) {
193
				$deployment->ApproverID = Member::currentUserID();
194
				$deployment->write();
195
			}
196
		}
197
198
		// title and summary may have changed, ensure they are saved
199
		if ($request->postVar('title')) {
200
			$deployment->Title = $request->postVar('title');
201
		}
202
		if ($request->postVar('summary')) {
203
			$deployment->Summary = $request->postVar('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...
204
		}
205
206
		try {
207
			$deployment->getMachine()->apply(DNDeployment::TR_APPROVE);
208
		} catch (\Exception $e) {
209
			return $this->getAPIResponse([
210
				'message' => $e->getMessage()
211
			], 400);
212
		}
213
214
		return $this->getAPIResponse([
215
			'message' => 'Deployment request has been approved',
216
			'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...
217
		], 200);
218
	}
219
220
	/**
221
	 * @param \SS_HTTPRequest $request
222
	 * @return \SS_HTTPResponse
223
	 */
224
	public function reject(\SS_HTTPRequest $request) {
225
		if ($request->httpMethod() !== 'POST') {
226
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
227
		}
228
229
		$this->checkSecurityToken();
230
231
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
232
		$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...
233
		if ($errorResponse instanceof \SS_HTTPResponse) {
234
			return $errorResponse;
235
		}
236
		// reject permissions are the same as can approve
237 View Code Duplication
		if (!$this->project->allowed(self::ALLOW_APPROVAL, Member::currentUser())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
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...
238
			return $this->getAPIResponse(['message' => 'You are not authorised to reject this deployment'], 403);
239
		}
240
241
		// if the current user is not the person who was selected for approval on submit, but they got
242
		// here because they still have permission, then change the approver to the current user
243
		if (Member::currentUserID() !== $deployment->ApproverID) {
244
			$deployment->ApproverID = Member::currentUserID();
245
			$deployment->write();
246
		}
247
248
		if ($request->postVar('rejected_reason')) {
249
			$deployment->RejectedReason = $request->postVar('rejected_reason');
250
		}
251
252
		try {
253
			$deployment->getMachine()->apply(DNDeployment::TR_REJECT);
254
		} catch (\Exception $e) {
255
			return $this->getAPIResponse([
256
				'message' => $e->getMessage()
257
			], 400);
258
		}
259
260
		return $this->getAPIResponse([
261
			'message' => 'Deployment request has been rejected',
262
			'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...
263
		], 200);
264
	}
265
266
	/**
267
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
268
	 * an APIResponse with the error, otherwise null.
269
	 *
270
	 * @param \DNDeployment $deployment
271
	 *
272
	 * @return null|SS_HTTPResponse
273
	 */
274 View Code Duplication
	protected function validateDeployment($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...
275
		if (!$deployment || !$deployment->exists()) {
276
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
277
		}
278
		if ($deployment->EnvironmentID != $this->environment->ID) {
279
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
280
		}
281
		if (!$deployment->canView()) {
282
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
283
		}
284
		return null;
285
	}
286
287
	/**
288
	 * @param string $name
289
	 * @return array
290
	 */
291
	public function getModel($name = '') {
292
		return [];
293
	}
294
295
	/**
296
	 * @param string $action
297
	 * @return string
298
	 */
299
	public function Link($action = '') {
300
		return \Controller::join_links($this->environment->Link(), self::ACTION_APPROVALS, $action);
301
	}
302
303
}
304