Completed
Pull Request — master (#630)
by Sean
04:25 queued 01:20
created

DeployDispatcher::Link()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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