Completed
Pull Request — master (#699)
by Sean
26:18 queued 20:48
created

ApprovalsDispatcher::submit()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 34
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 23
nc 7
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
	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
		'approvers',
16
		'submit',
17
		'cancel',
18
		'approve',
19
		'reject'
20
	];
21
22
	private static $dependencies = [
23
		'formatter' => '%$DeploynautAPIFormatter'
24
	];
25
26
	/**
27
	 * @var \DNProject
28
	 */
29
	protected $project = null;
30
31
	/**
32
	 * @var \DNEnvironment
33
	 */
34
	protected $environment = null;
35
36
	/**
37
	 * @var array
38
	 */
39
	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...
40
		self::ACTION_APPROVALS
41
	];
42
43
	/**
44
	 * This is a per request cache of $this->project()->listMembers()
45
	 * @var null|array
46
	 */
47
	private static $_cache_project_members = null;
48
49 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...
50
		parent::init();
51
52
		$this->project = $this->getCurrentProject();
53
		if (!$this->project) {
54
			return $this->project404Response();
55
		}
56
57
		// Performs canView permission check by limiting visible projects
58
		$this->environment = $this->getCurrentEnvironment($this->project);
59
		if (!$this->environment) {
60
			return $this->environment404Response();
61
		}
62
	}
63
64
	/**
65
	 * @param \SS_HTTPRequest $request
66
	 * @return \SS_HTTPResponse
67
	 */
68
	public function approvers(SS_HTTPRequest $request) {
69
		$list = [];
70
71
		if (self::$_cache_project_members === null) {
72
			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...
73
		}
74
75
		foreach (self::$_cache_project_members as $data) {
76
			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...
77
				$list[] = [
78
					'id' => $data['MemberID'],
79
					'email' => $data['Email'],
80
					'role' => $data['RoleTitle'],
81
					'name' => $data['FullName']
82
				];
83
			}
84
		}
85
86
		return $this->getAPIResponse([
87
			'approvers' => $list
88
		], 200);
89
	}
90
91
	/**
92
	 * @param \SS_HTTPRequest $request
93
	 * @return \SS_HTTPResponse
94
	 */
95
	public function submit(SS_HTTPRequest $request) {
96
		if ($request->httpMethod() !== 'POST') {
97
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
98
		}
99
100
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
101
		$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...
102
		if ($errorResponse instanceof \SS_HTTPResponse) {
103
			return $errorResponse;
104
		}
105
106
		$approver = Member::get()->byId($request->postVar('approver_id'));
107
		if ($approver && $approver->exists()) {
108
			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...
109
				return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
110
			}
111
112
			$deployment->ApproverID = $approver->ID;
113
			$deployment->write();
114
		}
115
116
		try {
117
			$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
118
		} catch (\Exception $e) {
119
			return $this->getAPIResponse([
120
				'message' => $e->getMessage()
121
			], 400);
122
		}
123
124
		return $this->getAPIResponse([
125
			'message' => 'Deployment request has been submitted',
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
		// if the person cancelling is not the one who created the deployment, update the deployer
146
		if (Member::currentUserID() !== $deployment->DeployerID) {
147
			$deployment->DeployerID = Member::currentUserID();
148
			$deployment->write();
149
		}
150
151
		// @todo permission checking for cancelling an approval request
152
		try {
153
			$deployment->getMachine()->apply(DNDeployment::TR_NEW);
154
		} catch (\Exception $e) {
155
			return $this->getAPIResponse([
156
				'message' => $e->getMessage()
157
			], 400);
158
		}
159
160
		return $this->getAPIResponse([
161
			'message' => 'Deployment request has been cancelled',
162
			'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...
163
		], 200);
164
	}
165
166
	/**
167
	 * @param \SS_HTTPRequest $request
168
	 * @return \SS_HTTPResponse
169
	 */
170
	public function approve(SS_HTTPRequest $request) {
171
		if ($request->httpMethod() !== 'POST') {
172
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
173
		}
174
175
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
176
		$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...
177
		if ($errorResponse instanceof \SS_HTTPResponse) {
178
			return $errorResponse;
179
		}
180
181
		// ensure we have either bypass or approval permission of the logged in user
182
		if (
183
			!$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...
184
			|| !$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...
185
		) {
186
			return $this->getAPIResponse(['message' => 'You are not authorised to approve or bypass this deployment'], 403);
187
		}
188
189
		// check for specific permission depending on the current state of the deployment:
190
		// submitted => approved requires approval permissions
191
		// new => approved requires bypass permissions.
192 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...
193
			$deployment->State === DNDeployment::STATE_SUBMITTED
194
			&& !$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...
195
		) {
196
			return $this->getAPIResponse(['message' => 'You are not authorised to approve this deployment'], 403);
197
		}
198 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...
199
			$deployment->State === DNDeployment::STATE_NEW
200
			&& !$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...
201
		) {
202
			return $this->getAPIResponse(['message' => 'You are not authorised to bypass approval of this deployment'], 403);
203
		}
204
205
		// if the current user is not the person who was selected for approval on submit, but they got
206
		// here because they still have permission, then change the approver to the current user
207
		if (Member::currentUserID() !== $deployment->ApproverID) {
208
			$deployment->ApproverID = Member::currentUserID();
209
			$deployment->write();
210
		}
211
212
		try {
213
			$deployment->getMachine()->apply(DNDeployment::TR_APPROVE);
214
		} catch (\Exception $e) {
215
			return $this->getAPIResponse([
216
				'message' => $e->getMessage()
217
			], 400);
218
		}
219
220
		return $this->getAPIResponse([
221
			'message' => 'Deployment request has been approved',
222
			'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...
223
		], 200);
224
	}
225
226
	/**
227
	 * @param \SS_HTTPRequest $request
228
	 * @return \SS_HTTPResponse
229
	 */
230
	public function reject(SS_HTTPRequest $request) {
231
		if ($request->httpMethod() !== 'POST') {
232
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
233
		}
234
235
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
236
		$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...
237
		if ($errorResponse instanceof \SS_HTTPResponse) {
238
			return $errorResponse;
239
		}
240
		// reject permissions are the same as can approve
241 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...
242
			return $this->getAPIResponse(['message' => 'You are not authorised to reject this deployment'], 403);
243
		}
244
245
		// if the current user is not the person who was selected for approval on submit, but they got
246
		// here because they still have permission, then change the approver to the current user
247
		if (Member::currentUserID() !== $deployment->ApproverID) {
248
			$deployment->ApproverID = Member::currentUserID();
249
			$deployment->write();
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(\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...
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