Completed
Pull Request — master (#627)
by Stig
03:55
created

DeployDispatcher::Link()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
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
		'start',
24
		'log'
25
	];
26
27
	/**
28
	 * @var \DNProject
29
	 */
30
	protected $project = null;
31
32
	/**
33
	 * @var \DNEnvironment
34
	 */
35
	protected $environment = null;
36
37 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...
38
		parent::init();
39
40
		$this->project = $this->getCurrentProject();
41
42
		if(!$this->project) {
43
			return $this->project404Response();
44
		}
45
46
		// Performs canView permission check by limiting visible projects
47
		$this->environment = $this->getCurrentEnvironment($this->project);
48
		if(!$this->environment) {
49
			return $this->environment404Response();
50
		}
51
	}
52
53
	/**
54
	 *
55
	 * @param \SS_HTTPRequest $request
56
	 *
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
	 * @return SS_HTTPResponse
65
	 */
66
	public function history(SS_HTTPRequest $request) {
67
		$data = [];
68
		$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...
69
		$page = $request->getVar('page') ?: 1;
70
		if ($page > $list->TotalPages()) {
71
			$page = 1;
72
		}
73
		if ($page < 1) {
74
			$page = 1;
75
		}
76
		$start = ($page - 1) * $list->getPageLength();
77
		$list->setPageStart((int) $start);
78
		if (empty($list)) {
79
			return $this->getAPIResponse(['message' => 'No deploy history'], 404);
80
		}
81
82
		foreach ($list as $deployment) {
83
			$data[] = [
84
				'CreatedDate' => $deployment->Created,
85
				'Branch' => $deployment->Branch,
86
				'Tags' => $deployment->getTags()->toArray(),
87
				'Changes' => $deployment->getDeploymentStrategy()->getChanges(),
88
				'CommitMessage' => $deployment->getCommitMessage(),
89
				'Deployer' => $deployment->Deployer()->getName(),
90
				'Approver' => $deployment->Approver()->getName(),
91
				'State' => $deployment->State,
92
			];
93
		}
94
95
		return $this->getAPIResponse(
96
			[
97
				'list' => $data,
98
				'pagelength' => $list->getPageLength(),
99
				'totalpages' => $list->TotalPages(),
100
				'currentpage' => $list->CurrentPage()
101
			],
102
			200
103
		);
104
	}
105
106
	/**
107
	 *
108
	 * @param SS_HTTPRequest $request
109
	 *
110
	 * @return SS_HTTPResponse
111
	 * @throws ValidationException
112
	 * @throws null
113
	 */
114
	public function start(SS_HTTPRequest $request) {
115
		$this->checkSecurityToken();
116
117
		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...
118
			return $this->getAPIResponse(['message' => 'You are not authorized to deploy this environment'], 403);
119
		}
120
121
		// @todo the strategy should have been saved when there has been a request for an
122
		// approval or a bypass. This saved state needs to be checked if it's invalidated
123
		// if another deploy happens before this one
124
		$options = [
125
			'sha' => $request->requestVar('sha'),
126
		];
127
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
128
129
		$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...
130
		$deployment = $strategy->createDeployment();
131
132
		// Skip through the approval state for now.
133
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
134
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
135
136
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
137
138
		$output = [
139
			'message' => 'deployment has been queued',
140
			'ID' => $deployment->ID,
141
			'location' => $location
142
		];
143
		$response = $this->getAPIResponse($output, 201);
144
		$response->addHeader('Location', $location);
145
		return $response;
146
	}
147
148
	/**
149
	    * Action - Get the latest deploy log
150
	    *
151
	    * @param SS_HTTPRequest $request
152
	    *
153
	    * @return string
154
	    * @throws SS_HTTPResponse_Exception
155
	    */
156
	public function log(SS_HTTPRequest $request) {
157
		$params = $request->params();
158
		$deployment = DNDeployment::get()->byId($params['ID']);
159
		if(!$deployment || !$deployment->ID) {
160
			throw new SS_HTTPResponse_Exception('Deployment not found', 404);
161
		}
162
		if(!$deployment->canView()) {
163
			return Security::permissionFailure();
164
		}
165
		if($this->environment->Name != $params['Environment']) {
166
			throw new LogicException("Environment in URL doesn't match this deploy");
167
		}
168
		if($this->project->Name != $params['Project']) {
169
			throw new LogicException("Project in URL doesn't match this deploy");
170
		}
171
		$log = $deployment->log();
172
		if($log->exists()) {
173
			$content = $log->content();
174
		} else {
175
			$content = 'Waiting for action to start';
176
		}
177
178
		$lines = explode(PHP_EOL, $content);
179
180
		return $this->getAPIResponse(['message' => $lines, 'status' => $deployment->ResqueStatus()], 200);
181
	}
182
183
	/**
184
	 * @param string $action
185
	 *
186
	 * @return string
187
	 */
188
	public function Link($action = "") {
189
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
190
	}
191
192
	/**
193
	 * @param string $name
194
	 *
195
	 * @return array
196
	 */
197
	public function getModel($name = '') {
198
		return [];
199
	}
200
201
}
202