Completed
Pull Request — master (#727)
by Sean
04:18
created

DeployDispatcher::index()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
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 {
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
	private static $allowed_actions = [
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...
15
		'history',
16
		'upcoming',
17
		'currentbuild',
18
		'show',
19
		'delete',
20
		'log',
21
		'createdeployment',
22
		'start'
23
	];
24
25
	private static $dependencies = [
26
		'formatter' => '%$DeploynautAPIFormatter'
27
	];
28
29
	/**
30
	 * @var \DNProject
31
	 */
32
	protected $project = null;
33
34
	/**
35
	 * @var \DNEnvironment
36
	 */
37
	protected $environment = null;
38
39
	/**
40
	 * @var array
41
	 */
42
	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...
43
		self::ACTION_DEPLOY
44
	];
45
46 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...
47
		parent::init();
48
49
		$this->project = $this->getCurrentProject();
50
51
		if (!$this->project) {
52
			return $this->project404Response();
53
		}
54
55
		// Performs canView permission check by limiting visible projects
56
		$this->environment = $this->getCurrentEnvironment($this->project);
57
		if (!$this->environment) {
58
			return $this->environment404Response();
59
		}
60
	}
61
62
	/**
63
	 * @param \SS_HTTPRequest $request
64
	 * @return \HTMLText|\SS_HTTPResponse
65
	 */
66
	public function index(\SS_HTTPRequest $request) {
67
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
68
	}
69
70
	/**
71
	 * @param \SS_HTTPRequest $request
72
	 * @return \SS_HTTPResponse
73
	 */
74 View Code Duplication
	public function history(\SS_HTTPRequest $request) {
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...
75
		$data = [];
76
77
		$list = $this->environment->DeployHistory('DeployStarted');
78
79
		foreach ($list as $deployment) {
80
			$data[] = $this->formatter->getDeploymentData($deployment);
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
81
		}
82
83
		return $this->getAPIResponse([
84
			'list' => $data,
85
		], 200);
86
	}
87
88
	/**
89
	 * @param \SS_HTTPRequest $request
90
	 * @return \SS_HTTPResponse
91
	 */
92 View Code Duplication
	public function upcoming(\SS_HTTPRequest $request) {
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...
93
		$data = [];
94
		$list = $this->environment->UpcomingDeployments();
95
		foreach ($list as $deployment) {
96
			$data[] = $this->formatter->getDeploymentData($deployment);
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
97
		}
98
		return $this->getAPIResponse([
99
			'list' => $data,
100
		], 200);
101
	}
102
103
	/**
104
	 * @param \SS_HTTPRequest $request
105
	 * @return \SS_HTTPResponse
106
	 */
107
	public function currentbuild(\SS_HTTPRequest $request) {
108
		$currentBuild = $this->environment->CurrentBuild();
109
		if (!$currentBuild) {
110
			return $this->getAPIResponse(['deployment' => []], 200);
111
		}
112
		return $this->getAPIResponse(['deployment' => $this->formatter->getDeploymentData($currentBuild)], 200);
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
113
	}
114
115
	/**
116
	 * @param \SS_HTTPRequest $request
117
	 * @return \SS_HTTPResponse
118
	 */
119
	public function show(\SS_HTTPRequest $request) {
120
		$deployment = DNDeployment::get()->byId($request->param('ID'));
121
		$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...
122
		if ($errorResponse instanceof \SS_HTTPResponse) {
123
			return $errorResponse;
124
		}
125
		return $this->getAPIResponse(['deployment' => $this->formatter->getDeploymentData($deployment)], 200);
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
126
	}
127
128
	public function delete(\SS_HTTPRequest $request) {
129
		if ($request->httpMethod() !== 'POST') {
130
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
131
		}
132
133
		$this->checkSecurityToken();
134
135
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
136
		$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...
137
		if ($errorResponse instanceof \SS_HTTPResponse) {
138
			return $errorResponse;
139
		}
140
141
		$deployment->delete();
142
143
		return $this->getAPIResponse([
144
			'message' => 'Deployment has been deleted'
145
		], 201);
146
	}
147
148
	/**
149
	 * @param \SS_HTTPRequest $request
150
	 * @return \SS_HTTPResponse
151
	 */
152
	public function log(\SS_HTTPRequest $request) {
153
		$deployment = DNDeployment::get()->byId($request->param('ID'));
154
		$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...
155
		if ($errorResponse instanceof \SS_HTTPResponse) {
156
			return $errorResponse;
157
		}
158
		$log = $deployment->log();
159
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
160
		$lines = explode(PHP_EOL, $content);
161
162
		return $this->getAPIResponse([
163
			'message' => $lines,
164
			'status' => $deployment->Status,
165
			'deployment' => $this->formatter->getDeploymentData($deployment),
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
166
		], 200);
167
	}
168
169
	/**
170
	 * Create deployment. Can't use {@link create()} as it's taken by Object.
171
	 *
172
	 * @param \SS_HTTPRequest $request
173
	 * @return \SS_HTTPResponse
174
	 */
175
	public function createdeployment(\SS_HTTPRequest $request) {
176
		if ($request->httpMethod() !== 'POST') {
177
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
178
		}
179
180
		$this->checkSecurityToken();
181
182
		// @todo the strategy should have been saved when there has been a request for an
183
		// approval or a bypass. This saved state needs to be checked if it's invalidated
184
		// if another deploy happens before this one
185
		$isBranchDeploy = (int) $request->postVar('ref_type') === GitDispatcher::REF_TYPE_BRANCH;
186
187
		$options = [
188
			'sha' => $request->postVar('ref'),
189
			'ref_type' => $request->postVar('ref_type'),
190
			'branch' => $isBranchDeploy ? $request->postVar('ref_name') : null,
191
			'title' => $request->postVar('title'),
192
			'summary' => $request->postVar('summary')
193
		];
194
195 View Code Duplication
		if ($request->postVar('options')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
196
			foreach (explode(',', $request->postVar('options')) as $option) {
197
				$options[$option] = true;
198
			}
199
		}
200
201
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
202
203
		$approver = Member::get()->byId($request->postVar('approver_id'));
204
		if ($approver && $approver->exists()) {
205
			if (!$this->project->allowed(ApprovalsDispatcher::ALLOW_APPROVAL, $approver)) {
0 ignored issues
show
Documentation introduced by
$approver is of type object<DataObject>, but the function expects a object<Member>|null.

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...
206
				return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
207
			}
208
		}
209
210
		$deployment = $strategy->createDeployment();
211
		if ($approver && $approver->exists()) {
212
			$deployment->ApproverID = $approver->ID;
0 ignored issues
show
Documentation introduced by
The property ApproverID does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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
			$deployment->write();
214
		}
215
216
		return $this->getAPIResponse([
217
			'message' => 'Deployment has been created',
218
			'deployment' => $this->formatter->getDeploymentData($deployment),
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
219
		], 201);
220
	}
221
222
	/**
223
	 * @param \SS_HTTPRequest $request
224
	 * @return \SS_HTTPResponse
225
	 */
226
	public function start(\SS_HTTPRequest $request) {
227
		if ($request->httpMethod() !== 'POST') {
228
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
229
		}
230
231
		$this->checkSecurityToken();
232
233
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
234
		$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...
235
		if ($errorResponse instanceof \SS_HTTPResponse) {
236
			return $errorResponse;
237
		}
238
239
		// The deployment cannot be started until it has been approved, or bypassed straight to approved state
240
		if ($deployment->State != DNDeployment::STATE_APPROVED) {
241
			return $this->getAPIResponse(['message' => 'This deployment has not been approved. Cannot deploy'], 403);
242
		}
243
244
		// until we have a system that can invalidate currently scheduled deployments due
245
		// to emergency deploys etc, replan the deployment to check if it's still valid.
246
		$options = $deployment->getDeploymentStrategy()->getOptions();
247
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
248
		$deployment->Strategy = $strategy->toJSON();
249
		$deployment->write();
250
251
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
252
253
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
254
255
		$response = $this->getAPIResponse([
256
			'message' => 'Deployment has been queued',
257
			'location' => $location,
258
			'deployment' => $this->formatter->getDeploymentData($deployment),
0 ignored issues
show
Documentation introduced by
The property formatter does not exist on object<DeployDispatcher>. 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...
259
		], 201);
260
261
		$response->addHeader('Location', $location);
262
263
		return $response;
264
	}
265
266
	/**
267
	 * @param string $action
268
	 * @return string
269
	 */
270
	public function Link($action = '') {
271
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
272
	}
273
274
	/**
275
	 * @param string $name
276
	 * @return array
277
	 */
278
	public function getModel($name = '') {
279
		return [];
280
	}
281
282
	/**
283
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
284
	 * an APIResponse with the error, otherwise null.
285
	 *
286
	 * @param \DNDeployment $deployment
287
	 *
288
	 * @return null|SS_HTTPResponse
289
	 */
290 View Code Duplication
	protected function validateDeployment($deployment) {
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...
291
		if (!$deployment || !$deployment->exists()) {
292
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
293
		}
294
		if ($deployment->EnvironmentID != $this->environment->ID) {
295
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
296
		}
297
		if (!$deployment->canView()) {
298
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
299
		}
300
		return null;
301
	}
302
303
}
304