Completed
Pull Request — master (#653)
by Sean
28:35 queued 22:32
created

DeployDispatcher::log()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
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
	public function init() {
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 = null;
73
		$history = $this->environment->DeployHistory();
74
		if ($history->count() > 0) {
75
			$list = new PaginatedList($history, $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...
76
			$list->setPageLength(4);
77
		}
78
		$page = $request->getVar('page') ?: 1;
79
		if ($page > $list->TotalPages()) {
80
			$page = 1;
81
		}
82
		if ($page < 1) {
83
			$page = 1;
84
		}
85
		$start = ($page - 1) * $list->getPageLength();
86
		$list->setPageStart((int) $start);
87
		if (empty($list)) {
88
			return $this->getAPIResponse(['list' => []], 200);
89
		}
90
91
		foreach ($list as $deployment) {
92
			$data[] = $this->getDeploymentData($deployment);
93
		}
94
95
		return $this->getAPIResponse([
96
			'list' => $data,
97
			'page_length' => $list->getPageLength(),
98
			'total_pages' => $list->TotalPages(),
99
			'current_page' => $list->CurrentPage()
100
		], 200);
101
	}
102
103
	/**
104
	 * @param \SS_HTTPRequest $request
105
	 * @return \SS_HTTPResponse
106
	 */
107
	public function upcoming(SS_HTTPRequest $request) {
108
		$data = [];
109
		$list = $this->environment->UpcomingDeployments();
110
		foreach ($list as $deployment) {
111
			$data[] = $this->getDeploymentData($deployment);
112
		}
113
		return $this->getAPIResponse([
114
			'list' => $data,
115
		], 200);
116
117
	}
118
119
	/**
120
	 * @param \SS_HTTPRequest $request
121
	 * @return \SS_HTTPResponse
122
	 */
123
	public function currentbuild(SS_HTTPRequest $request) {
124
		$currentBuild = $this->environment->CurrentBuild();
125
		if (!$currentBuild) {
126
			return $this->getAPIResponse(['deployment' => []], 200);
127
		}
128
		return $this->getAPIResponse(['deployment' => $this->getDeploymentData($currentBuild)], 200);
129
	}
130
131
	/**
132
	 * @param \SS_HTTPRequest $request
133
	 * @return \SS_HTTPResponse
134
	 */
135
	public function show(SS_HTTPRequest $request) {
136
		$deployment = DNDeployment::get()->byId($request->param('ID'));
137
		$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...
138
		if ($errorResponse instanceof \SS_HTTPResponse) {
139
			return $errorResponse;
140
		}
141
		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...
142
	}
143
144
	/**
145
	 * @param \SS_HTTPRequest $request
146
	 * @return \SS_HTTPResponse
147
	 */
148
	public function log(SS_HTTPRequest $request) {
149
		$deployment = DNDeployment::get()->byId($request->param('ID'));
150
		$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...
151
		if ($errorResponse instanceof \SS_HTTPResponse) {
152
			return $errorResponse;
153
		}
154
		$log = $deployment->log();
155
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
156
		$lines = explode(PHP_EOL, $content);
157
158
		return $this->getAPIResponse(['message' => $lines, 'status' => $deployment->Status], 200);
159
	}
160
161
	public function save(\SS_HTTPRequest $request) {
162
163
		if ($request->httpMethod() !== 'POST') {
164
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
165
		}
166
167
		$this->checkSecurityToken();
168
		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...
169
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
170
		}
171
172
		// @todo the strategy should have been saved when there has been a request for an
173
		// approval or a bypass. This saved state needs to be checked if it's invalidated
174
		// if another deploy happens before this one
175
		$options = [
176
			'sha' => $request->requestVar('ref'),
177
			'ref_type' => $request->requestVar('ref_type'),
178
			'branch' => $request->requestVar('ref_name'),
179
			'summary' => $request->requestVar('summary')
180
		];
181
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
182
183
		$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...
184
		$deployment = $strategy->createDeployment();
185
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
186
		return $this->getAPIResponse([
187
			'message' => 'deployment has been created',
188
			'id' => $deployment->ID,
189
		], 201);
190
	}
191
192
	/**
193
	 * @param \SS_HTTPRequest $request
194
	 * @return \SS_HTTPResponse
195
	 */
196
	public function start(SS_HTTPRequest $request) {
197
		if ($request->httpMethod() !== 'POST') {
198
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
199
		}
200
201
		$this->checkSecurityToken();
202
203
		$deployment = DNDeployment::get()->byId($request->param('ID'));
204
205
		if (!$deployment || !$deployment->exists()) {
206
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
207
		}
208
		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...
209
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
210
		}
211
212
		// until we have a system that can invalidate currently scheduled deployments due
213
		// to emergency deploys etc, replan the deployment to check if it's still valid.
214
215
		$options = $deployment->getDeploymentStrategy()->getOptions();
216
217
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
218
		$deployment->Strategy = $strategy->toJSON();
219
		$deployment->write();
220
221
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
222
223
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
224
225
		$response = $this->getAPIResponse([
226
			'message' => 'deployment has been queued',
227
			'id' => $deployment->ID,
228
			'location' => $location
229
		], 201);
230
		$response->addHeader('Location', $location);
231
		return $response;
232
	}
233
234
	/**
235
	 * @param string $action
236
	 * @return string
237
	 */
238
	public function Link($action = '') {
239
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
240
	}
241
242
	/**
243
	 * @param string $name
244
	 * @return array
245
	 */
246
	public function getModel($name = '') {
247
		return [];
248
	}
249
250
	/**
251
	 * Return data about a single deployment for use in API response.
252
	 * @param DNDeployment $deployment
253
	 * @return array
254
	 */
255
	protected function getDeploymentData(DNDeployment $deployment) {
256
		$currentBuild = $this->environment->CurrentBuild();
257
258
		$deployer = $deployment->Deployer();
259
		$deployerData = null;
260
		if ($deployer && $deployer->exists()) {
261
			$deployerData = $this->getStackMemberData($deployer);
262
		}
263
		$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...
264
		$approverData = null;
265
		if ($approver && $approver->exists()) {
266
			$approverData = $this->getStackMemberData($approver);
267
		}
268
269
		return [
270
			'id' => $deployment->ID,
271
			'created' => $deployment->Created,
272
			'date_planned' => $deployment->DatePlanned,
0 ignored issues
show
Documentation introduced by
The property DatePlanned 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...
273
			'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...
274
			'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...
275
			'tags' => $deployment->getTags()->toArray(),
276
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
277
			'sha' => $deployment->SHA,
278
			'ref_type' => $deployment->RefType,
279
			'commit_message' => $deployment->getCommitMessage(),
280
			'commit_url' => $deployment->getCommitURL(),
281
			'deployer' => $deployerData,
282
			'approver' => $approverData,
283
			'state' => $deployment->State,
284
			'is_current_build' => $currentBuild ? ($deployment->ID === $currentBuild->ID) : null
285
		];
286
	}
287
288
	/**
289
	 * Return data about a particular {@link Member} of the stack for use in API response.
290
	 * Note that role can be null in the response. This is the case of an admin, or an operations
291
	 * user who can create the deployment but is not part of the stack roles.
292
	 *
293
	 * @param Member $member
294
	 * @return array
295
	 */
296
	protected function getStackMemberData(Member $member) {
297
		$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...
298
		$role = null;
299
300
		foreach ($stackMembers as $stackMember) {
301
			if ($stackMember['MemberID'] !== $member->ID) {
302
				continue;
303
			}
304
305
			$role = $stackMember['RoleTitle'];
306
		}
307
308
		return [
309
			'id' => $member->ID,
310
			'email' => $member->Email,
311
			'role' => $role,
312
			'name' => $member->getName()
313
		];
314
	}
315
316
	/**
317
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
318
	 * an APIResponse with the error, otherwise null.
319
	 *
320
	 * @param \DNDeployment $deployment
321
	 *
322
	 * @return null|SS_HTTPResponse
323
	 */
324
	protected function validateDeployment(\DNDeployment $deployment) {
325
		if (!$deployment || !$deployment->exists()) {
326
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
327
		}
328
		if (!$deployment->canView()) {
329
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
330
		}
331
		return null;
332
	}
333
334
}
335