Completed
Push — master ( a9696d...2d5de8 )
by Sean
13:09 queued 07:41
created

DeployDispatcher::getStackMemberData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 1
1
<?php
2
3
/**
4
 * This dispatcher takes care of updating and returning information about this
5
 * projects git repository
6
 */
7
class DeployDispatcher 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...
8
9
	const ACTION_DEPLOY = 'deploys';
10
11
	/**
12
	 * @var array
13
	 */
14
	public static $allowed_actions = [
15
		'history',
16
		'upcoming',
17
		'currentbuild',
18
		'show',
19
		'log',
20
		'start',
21
		'save'
22
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_DEPLOY
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
47
		if (!$this->project) {
48
			return $this->project404Response();
49
		}
50
51
		// Performs canView permission check by limiting visible projects
52
		$this->environment = $this->getCurrentEnvironment($this->project);
53
		if (!$this->environment) {
54
			return $this->environment404Response();
55
		}
56
	}
57
58
	/**
59
	 * @param \SS_HTTPRequest $request
60
	 * @return \HTMLText|\SS_HTTPResponse
61
	 */
62
	public function index(\SS_HTTPRequest $request) {
63
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
64
	}
65
66
	/**
67
	 * @param \SS_HTTPRequest $request
68
	 * @return \SS_HTTPResponse
69
	 */
70
	public function history(SS_HTTPRequest $request) {
71
		$data = [];
72
		$list = new PaginatedList($this->environment->DeployHistory('DeployStarted'), $this->getRequest());
0 ignored issues
show
Documentation introduced by
$this->getRequest() is of type object<SS_HTTPRequest>, but the function expects a array.

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...
73
		$list->setPageLength(4);
74
		$page = $request->getVar('page') ?: 1;
75
		if ($page > $list->TotalPages()) {
76
			$page = 1;
77
		}
78
		if ($page < 1) {
79
			$page = 1;
80
		}
81
		$start = ($page - 1) * $list->getPageLength();
82
		$list->setPageStart((int) $start);
83
		if (empty($list)) {
84
			return $this->getAPIResponse(['list' => []], 200);
85
		}
86
87
		foreach ($list as $deployment) {
88
			$data[] = $this->getDeploymentData($deployment);
89
		}
90
91
		return $this->getAPIResponse([
92
			'list' => $data,
93
			'page_length' => $list->getPageLength(),
94
			'total_pages' => $list->TotalPages(),
95
			'current_page' => $list->CurrentPage()
96
		], 200);
97
	}
98
99
	/**
100
	 * @param \SS_HTTPRequest $request
101
	 * @return \SS_HTTPResponse
102
	 */
103
	public function upcoming(SS_HTTPRequest $request) {
104
		$data = [];
105
		$list = $this->environment->UpcomingDeployments();
106
		foreach ($list as $deployment) {
107
			$data[] = $this->getDeploymentData($deployment);
108
		}
109
		return $this->getAPIResponse([
110
			'list' => $data,
111
		], 200);
112
	}
113
114
	/**
115
	 * @param \SS_HTTPRequest $request
116
	 * @return \SS_HTTPResponse
117
	 */
118
	public function currentbuild(SS_HTTPRequest $request) {
119
		$currentBuild = $this->environment->CurrentBuild();
120
		if (!$currentBuild) {
121
			return $this->getAPIResponse(['deployment' => []], 200);
122
		}
123
		return $this->getAPIResponse(['deployment' => $this->getDeploymentData($currentBuild)], 200);
124
	}
125
126
	/**
127
	 * @param \SS_HTTPRequest $request
128
	 * @return \SS_HTTPResponse
129
	 */
130
	public function show(SS_HTTPRequest $request) {
131
		$deployment = DNDeployment::get()->byId($request->param('ID'));
132
		$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...
133
		if ($errorResponse instanceof \SS_HTTPResponse) {
134
			return $errorResponse;
135
		}
136
		return $this->getAPIResponse(['deployment' => $this->getDeploymentData($deployment)], 200);
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...
137
	}
138
139
	/**
140
	 * @param \SS_HTTPRequest $request
141
	 * @return \SS_HTTPResponse
142
	 */
143
	public function log(SS_HTTPRequest $request) {
144
		$deployment = DNDeployment::get()->byId($request->param('ID'));
145
		$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...
146
		if ($errorResponse instanceof \SS_HTTPResponse) {
147
			return $errorResponse;
148
		}
149
		$log = $deployment->log();
150
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
151
		$lines = explode(PHP_EOL, $content);
152
153
		return $this->getAPIResponse(['message' => $lines, 'status' => $deployment->Status], 200);
154
	}
155
156
	public function save(\SS_HTTPRequest $request) {
157
158
		if ($request->httpMethod() !== 'POST') {
159
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
160
		}
161
162
		$this->checkSecurityToken();
163
		if (!$this->environment->canDeploy(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, DNEnvironment::canDeploy() 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
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
165
		}
166
167
		// @todo the strategy should have been saved when there has been a request for an
168
		// approval or a bypass. This saved state needs to be checked if it's invalidated
169
		// if another deploy happens before this one
170
		$options = [
171
			'sha' => $request->requestVar('ref'),
172
			'ref_type' => $request->requestVar('ref_type'),
173
			'branch' => $request->requestVar('ref_name'),
174
			'summary' => $request->requestVar('summary')
175
		];
176
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
177
178
		$strategy->fromArray($request->requestVars());
0 ignored issues
show
Documentation introduced by
$request->requestVars() is of type array|null, but the function expects a string.

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...
179
		$deployment = $strategy->createDeployment();
180
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
181
		return $this->getAPIResponse([
182
			'message' => 'deployment has been created',
183
			'id' => $deployment->ID,
184
		], 201);
185
	}
186
187
	/**
188
	 * @param \SS_HTTPRequest $request
189
	 * @return \SS_HTTPResponse
190
	 */
191
	public function start(SS_HTTPRequest $request) {
192
		if ($request->httpMethod() !== 'POST') {
193
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
194
		}
195
196
		$this->checkSecurityToken();
197
198
		$deployment = DNDeployment::get()->byId($request->param('ID'));
199
200
		if (!$deployment || !$deployment->exists()) {
201
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
202
		}
203
		if (!$this->environment->canDeploy(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, DNEnvironment::canDeploy() 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...
204
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
205
		}
206
207
		// until we have a system that can invalidate currently scheduled deployments due
208
		// to emergency deploys etc, replan the deployment to check if it's still valid.
209
210
		$options = $deployment->getDeploymentStrategy()->getOptions();
211
212
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
213
		$deployment->Strategy = $strategy->toJSON();
214
		$deployment->write();
215
216
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
217
218
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
219
220
		$response = $this->getAPIResponse([
221
			'message' => 'deployment has been queued',
222
			'id' => $deployment->ID,
223
			'location' => $location
224
		], 201);
225
		$response->addHeader('Location', $location);
226
		return $response;
227
	}
228
229
	/**
230
	 * @param string $action
231
	 * @return string
232
	 */
233
	public function Link($action = '') {
234
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
235
	}
236
237
	/**
238
	 * @param string $name
239
	 * @return array
240
	 */
241
	public function getModel($name = '') {
242
		return [];
243
	}
244
245
	/**
246
	 * Return data about a single deployment for use in API response.
247
	 * @param DNDeployment $deployment
248
	 * @return array
249
	 */
250
	protected function getDeploymentData(DNDeployment $deployment) {
251
		$currentBuild = $this->environment->CurrentBuild();
252
253
		$deployer = $deployment->Deployer();
254
		$deployerData = null;
255
		if ($deployer && $deployer->exists()) {
256
			$deployerData = $this->getStackMemberData($deployer);
257
		}
258
		$approver = $deployment->Approver();
0 ignored issues
show
Documentation Bug introduced by
The method Approver does not exist on object<DNDeployment>? 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...
259
		$approverData = null;
260
		if ($approver && $approver->exists()) {
261
			$approverData = $this->getStackMemberData($approver);
262
		}
263
264
		// failover for older deployments
265
		$started = $deployment->Created;
266
		if($deployment->DeployStarted) {
267
			$started = $deployment->DeployStarted;
268
		}
269
270
		$requested = $deployment->Created;
271
		if($deployment->DeployRequested) {
272
			$requested = $deployment->DeployRequested;
273
		}
274
275
		return [
276
			'id' => $deployment->ID,
277
			'date_created' => $deployment->Created,
278
			'date_started' => $started,
279
			'date_requested' => $requested,
280
			'date_updated' => $deployment->LastEdited,
281
			'summary' => $deployment->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...
282
			'branch' => $deployment->Branch,
0 ignored issues
show
Documentation introduced by
The property Branch does not exist on object<DNDeployment>. 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...
283
			'tags' => $deployment->getTags()->toArray(),
284
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
285
			'sha' => $deployment->SHA,
286
			'ref_type' => $deployment->RefType,
287
			'commit_message' => $deployment->getCommitMessage(),
288
			'commit_url' => $deployment->getCommitURL(),
289
			'deployer' => $deployerData,
290
			'approver' => $approverData,
291
			'state' => $deployment->State,
292
			'is_current_build' => $currentBuild ? ($deployment->ID === $currentBuild->ID) : null
293
		];
294
	}
295
296
	/**
297
	 * Return data about a particular {@link Member} of the stack for use in API response.
298
	 * Note that role can be null in the response. This is the case of an admin, or an operations
299
	 * user who can create the deployment but is not part of the stack roles.
300
	 *
301
	 * @param Member $member
302
	 * @return array
303
	 */
304
	protected function getStackMemberData(Member $member) {
305
		$stackMembers = $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...
306
		$role = null;
307
308
		foreach ($stackMembers as $stackMember) {
309
			if ($stackMember['MemberID'] !== $member->ID) {
310
				continue;
311
			}
312
313
			$role = $stackMember['RoleTitle'];
314
		}
315
316
		return [
317
			'id' => $member->ID,
318
			'email' => $member->Email,
319
			'role' => $role,
320
			'name' => $member->getName()
321
		];
322
	}
323
324
	/**
325
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
326
	 * an APIResponse with the error, otherwise null.
327
	 *
328
	 * @param \DNDeployment $deployment
329
	 *
330
	 * @return null|SS_HTTPResponse
331
	 */
332
	protected function validateDeployment(\DNDeployment $deployment) {
333
		if (!$deployment || !$deployment->exists()) {
334
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
335
		}
336
		if (!$deployment->canView()) {
337
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
338
		}
339
		return null;
340
	}
341
342
}
343