Completed
Pull Request — master (#681)
by Sean
08:51
created

ApprovalsDispatcher::cancel()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 17

Duplication

Lines 25
Ratio 100 %

Importance

Changes 0
Metric Value
dl 25
loc 25
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 17
nc 4
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 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...
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
		try {
107
			$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
108
		} catch (\Exception $e) {
109
			return $this->getAPIResponse([
110
				'message' => $e->getMessage()
111
			], 400);
112
		}
113
114
		return $this->getAPIResponse([
115
			'message' => 'Deployment request has been submitted',
116
			'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...
117
		], 200);
118
	}
119
120
	/**
121
	 * @param \SS_HTTPRequest $request
122
	 * @return \SS_HTTPResponse
123
	 */
124 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...
125
		if ($request->httpMethod() !== 'POST') {
126
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
127
		}
128
129
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
130
		$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...
131
		if ($errorResponse instanceof \SS_HTTPResponse) {
132
			return $errorResponse;
133
		}
134
135
		// @todo permission checking for cancelling an approval request
136
		try {
137
			$deployment->getMachine()->apply(DNDeployment::TR_NEW);
138
		} catch (\Exception $e) {
139
			return $this->getAPIResponse([
140
				'message' => $e->getMessage()
141
			], 400);
142
		}
143
144
		return $this->getAPIResponse([
145
			'message' => 'Deployment request has been cancelled',
146
			'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...
147
		], 200);
148
	}
149
150
	/**
151
	 * @param \SS_HTTPRequest $request
152
	 * @return \SS_HTTPResponse
153
	 */
154
	public function approve(SS_HTTPRequest $request) {
155
		if ($request->httpMethod() !== 'POST') {
156
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
157
		}
158
159
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
160
		$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...
161
		if ($errorResponse instanceof \SS_HTTPResponse) {
162
			return $errorResponse;
163
		}
164
165
		$validStates = [DNDeployment::STATE_SUBMITTED, DNDeployment::STATE_NEW];
166
		if (!in_array($deployment->State, $validStates)) {
167
			return $this->getAPIResponse([
168
				'message' => sprintf(
169
					'Deployment must be in one of the following states before it can be approved: %s',
170
					implode(', ', $validStates)
171
				)
172
			], 403);
173
		}
174 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...
175
			$deployment->State === DNDeployment::STATE_SUBMITTED
176
			&& !$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
		) {
178
			return $this->getAPIResponse(['message' => 'You are not authorised to approve this deployment'], 403);
179
		}
180 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...
181
			$deployment->State === DNDeployment::STATE_NEW
182
			&& !$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...
183
		) {
184
			return $this->getAPIResponse(['message' => 'You are not authorised to bypass approval of this deployment'], 403);
185
		}
186
187
		try {
188
			$deployment->getMachine()->apply(DNDeployment::TR_APPROVE);
189
		} catch (\Exception $e) {
190
			return $this->getAPIResponse([
191
				'message' => $e->getMessage()
192
			], 400);
193
		}
194
195
		return $this->getAPIResponse([
196
			'message' => 'Deployment request has been approved',
197
			'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...
198
		], 200);
199
	}
200
201
	/**
202
	 * @param \SS_HTTPRequest $request
203
	 * @return \SS_HTTPResponse
204
	 */
205
	public function reject(SS_HTTPRequest $request) {
206
		if ($request->httpMethod() !== 'POST') {
207
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
208
		}
209
210
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
211
		$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...
212
		if ($errorResponse instanceof \SS_HTTPResponse) {
213
			return $errorResponse;
214
		}
215
		// reject permissions are the same as can approve
216 View Code Duplication
		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...
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...
217
			return $this->getAPIResponse(['message' => 'You are not authorised to reject this deployment'], 403);
218
		}
219
220
		try {
221
			$deployment->getMachine()->apply(DNDeployment::TR_REJECT);
222
		} catch (\Exception $e) {
223
			return $this->getAPIResponse([
224
				'message' => $e->getMessage()
225
			], 400);
226
		}
227
228
		return $this->getAPIResponse([
229
			'message' => 'Deployment request has been rejected',
230
			'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...
231
		], 200);
232
	}
233
234
	/**
235
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
236
	 * an APIResponse with the error, otherwise null.
237
	 *
238
	 * @param \DNDeployment $deployment
239
	 *
240
	 * @return null|SS_HTTPResponse
241
	 */
242 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...
243
		if (!$deployment || !$deployment->exists()) {
244
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
245
		}
246
		if ($deployment->EnvironmentID != $this->environment->ID) {
247
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
248
		}
249
		if (!$deployment->canView()) {
250
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
251
		}
252
		return null;
253
	}
254
255
	/**
256
	 * @return ArrayList
257
	 */
258
	protected function getApprovers() {
259
		$list = new ArrayList();
260
		if (self::$_cache_project_members === null) {
261
			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...
262
		}
263
		foreach (self::$_cache_project_members as $data) {
264
			$list->push(new ArrayData([
265
				'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...
266
				'Role' => $data['RoleTitle']
267
			]));
268
		}
269
		return $list;
270
	}
271
272
	/**
273
	 * @param string $name
274
	 * @return array
275
	 */
276
	public function getModel($name = '') {
277
		return [];
278
	}
279
280
	/**
281
	 * @param string $action
282
	 * @return string
283
	 */
284
	public function Link($action = '') {
285
		return \Controller::join_links($this->environment->Link(), self::ACTION_APPROVALS, $action);
286
	}
287
288
}
289