Completed
Pull Request — master (#640)
by Stig
04:45
created

DeployDispatcher::start()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 32
rs 8.8571
cc 2
eloc 19
nc 2
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 {
8
9
	const ACTION_DEPLOY = 'deploys';
10
11
	/**
12
	 * @var array
13
	 */
14
	private static $action_types = [
15
		self::ACTION_DEPLOY
16
	];
17
18
	/**
19
	 * @var array
20
	 */
21
	public static $allowed_actions = [
22
		'history',
23
		'currentbuild',
24
		'show',
25
		'log',
26
		'start'
27
	];
28
29
	/**
30
	 * @var \DNProject
31
	 */
32
	protected $project = null;
33
34
	/**
35
	 * @var \DNEnvironment
36
	 */
37
	protected $environment = null;
38
39 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...
40
		parent::init();
41
42
		$this->project = $this->getCurrentProject();
43
44
		if (!$this->project) {
45
			return $this->project404Response();
46
		}
47
48
		// Performs canView permission check by limiting visible projects
49
		$this->environment = $this->getCurrentEnvironment($this->project);
50
		if (!$this->environment) {
51
			return $this->environment404Response();
52
		}
53
	}
54
55
	/**
56
	 * @param \SS_HTTPRequest $request
57
	 * @return \HTMLText|\SS_HTTPResponse
58
	 */
59
	public function index(\SS_HTTPRequest $request) {
60
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
61
	}
62
63
	/**
64
	 * @param \SS_HTTPRequest $request
65
	 * @return \SS_HTTPResponse
66
	 */
67
	public function history(SS_HTTPRequest $request) {
68
		$data = [];
69
		$list = $this->DeployHistory();
0 ignored issues
show
Deprecated Code introduced by
The method DNRoot::DeployHistory() has been deprecated with message: 2.0.0 - moved to DeployDispatcher

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
70
		$page = $request->getVar('page') ?: 1;
71
		if ($page > $list->TotalPages()) {
72
			$page = 1;
73
		}
74
		if ($page < 1) {
75
			$page = 1;
76
		}
77
		$start = ($page - 1) * $list->getPageLength();
78
		$list->setPageStart((int) $start);
79
		if (empty($list)) {
80
			return $this->getAPIResponse(['list' => []], 200);
81
		}
82
83
		foreach ($list as $deployment) {
84
			$data[] = $this->getDeploymentData($deployment);
85
		}
86
87
		return $this->getAPIResponse([
88
			'list' => $data,
89
			'page_length' => $list->getPageLength(),
90
			'total_pages' => $list->TotalPages(),
91
			'current_page' => $list->CurrentPage()
92
		], 200);
93
	}
94
95
	/**
96
	 * @param \SS_HTTPRequest $request
97
	 * @return \SS_HTTPResponse
98
	 */
99
	public function currentbuild(SS_HTTPRequest $request) {
100
		$currentBuild = $this->environment->CurrentBuild();
101
		if (!$currentBuild) {
102
			return $this->getAPIResponse(['deployment' => []], 200);
103
		}
104
		return $this->getAPIResponse(['deployment' => $this->getDeploymentData($currentBuild)], 200);
105
	}
106
107
	/**
108
	 * @param \SS_HTTPRequest $request
109
	 * @return \SS_HTTPResponse
110
	 */
111
	public function show(SS_HTTPRequest $request) {
112
		$deployment = DNDeployment::get()->byId($request->param('ID'));
113
		$errorResponse = $this->validateDeployement($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...
114
		if($errorResponse !== null) {
115
			return $errorResponse;
116
		}
117
		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...
118
	}
119
120
	/**
121
	 * @param \SS_HTTPRequest $request
122
	 * @return \SS_HTTPResponse
123
	 */
124
	public function log(SS_HTTPRequest $request) {
125
		$deployment = DNDeployment::get()->byId($request->param('ID'));
126
		$errorResponse = $this->validateDeployement($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...
127
		if($errorResponse !== null) {
128
			return $errorResponse;
129
		}
130
		$log = $deployment->log();
131
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
132
		$lines = explode(PHP_EOL, $content);
133
134
		return $this->getAPIResponse(['message' => $lines, 'status' => $deployment->Status], 200);
135
	}
136
137
	/**
138
	 * @param \SS_HTTPRequest $request
139
	 * @return \SS_HTTPResponse
140
	 */
141
	public function start(SS_HTTPRequest $request) {
142
		$this->checkSecurityToken();
143
144
		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...
145
			return $this->getAPIResponse(['message' => 'You are not authorised to deploy this environment'], 403);
146
		}
147
148
		// @todo the strategy should have been saved when there has been a request for an
149
		// approval or a bypass. This saved state needs to be checked if it's invalidated
150
		// if another deploy happens before this one
151
		$options = [
152
			'sha' => $request->requestVar('sha'),
153
		];
154
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
155
156
		$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...
157
		$deployment = $strategy->createDeployment();
158
159
		// Skip through the approval state for now.
160
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
161
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
162
163
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
164
165
		$response = $this->getAPIResponse([
166
			'message' => 'deployment has been queued',
167
			'id' => $deployment->ID,
168
			'location' => $location
169
		], 201);
170
		$response->addHeader('Location', $location);
171
		return $response;
172
	}
173
174
	/**
175
	 * @param string $action
176
	 * @return string
177
	 */
178
	public function Link($action = '') {
179
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
180
	}
181
182
	/**
183
	 * @param string $name
184
	 * @return array
185
	 */
186
	public function getModel($name = '') {
187
		return [];
188
	}
189
190
	/**
191
	 * Return data about a single deployment for use in API response.
192
	 * @param DNDeployment $deployment
193
	 * @return array
194
	 */
195
	protected function getDeploymentData(DNDeployment $deployment) {
196
		$currentBuild = $this->environment->CurrentBuild();
197
198
		$deployer = $deployment->Deployer();
199
		$deployerData = null;
200
		if ($deployer && $deployer->exists()) {
201
			$deployerData = $this->getStackMemberData($deployer);
202
		}
203
		$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...
204
		$approverData = null;
205
		if ($approver && $approver->exists()) {
206
			$approverData = $this->getStackMemberData($approver);
207
		}
208
209
		return [
210
			'id' => $deployment->ID,
211
			'created' => $deployment->Created,
212
			'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...
213
			'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...
214
			'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...
215
			'tags' => $deployment->getTags()->toArray(),
216
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
217
			'sha' => $deployment->SHA,
218
			'commit_message' => $deployment->getCommitMessage(),
219
			'commit_url' => $deployment->getCommitURL(),
220
			'deployer' => $deployerData,
221
			'approver' => $approverData,
222
			'state' => $deployment->State,
223
			'is_current_build' => $currentBuild ? ($deployment->ID === $currentBuild->ID) : null
224
		];
225
	}
226
227
	/**
228
	 * Return data about a particular {@link Member} of the stack for use in API response.
229
	 * Note that role can be null in the response. This is the case of an admin, or an operations
230
	 * user who can create the deployment but is not part of the stack roles.
231
	 *
232
	 * @param Member $member
233
	 * @return array
234
	 */
235
	protected function getStackMemberData(Member $member) {
236
		$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...
237
		$role = null;
238
239
		foreach ($stackMembers as $stackMember) {
240
			if ($stackMember['MemberID'] !== $member->ID) {
241
				continue;
242
			}
243
244
			$role = $stackMember['RoleTitle'];
245
		}
246
247
		return [
248
			'id' => $member->ID,
249
			'email' => $member->Email,
250
			'role' => $role,
251
			'name' => $member->getName()
252
		];
253
	}
254
	
255
	/**
256
	 * Check if a DNDeployment is exists and do permission checks on it. If there is something wrong it will return
257
	 * an APIResponse with the error, otherwise null.
258
	 *
259
	 * @param DNDeployment $deployment
260
	 *
261
	 * @return null|SS_HTTPResponse
262
	 */
263
	protected function validateDeployement(\DNDeployment $deployment) {
264
		if (!$deployment || !$deployment->exists()) {
265
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
266
		}
267
		if (!$deployment->canView()) {
268
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
269
		}
270
		return null;
271
	}
272
273
}
274