Completed
Pull Request — master (#727)
by Sean
05:03
created

DeployDispatcher::delete()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 14
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
	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
		$id = $deployment->ID;
142
		$deployment->delete();
143
144
		return $this->getAPIResponse([
145
			'id' => $id,
146
			'message' => 'Deployment has been deleted'
147
		], 201);
148
	}
149
150
	/**
151
	 * @param \SS_HTTPRequest $request
152
	 * @return \SS_HTTPResponse
153
	 */
154
	public function log(\SS_HTTPRequest $request) {
155
		$deployment = DNDeployment::get()->byId($request->param('ID'));
156
		$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...
157
		if ($errorResponse instanceof \SS_HTTPResponse) {
158
			return $errorResponse;
159
		}
160
		$log = $deployment->log();
161
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
162
		$lines = explode(PHP_EOL, $content);
163
164
		return $this->getAPIResponse([
165
			'message' => $lines,
166
			'status' => $deployment->Status,
167
			'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...
168
		], 200);
169
	}
170
171
	/**
172
	 * Create deployment. Can't use {@link create()} as it's taken by Object.
173
	 *
174
	 * @param \SS_HTTPRequest $request
175
	 * @return \SS_HTTPResponse
176
	 */
177
	public function createdeployment(\SS_HTTPRequest $request) {
178
		if ($request->httpMethod() !== 'POST') {
179
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
180
		}
181
182
		$this->checkSecurityToken();
183
184
		// @todo the strategy should have been saved when there has been a request for an
185
		// approval or a bypass. This saved state needs to be checked if it's invalidated
186
		// if another deploy happens before this one
187
		$isBranchDeploy = (int) $request->postVar('ref_type') === GitDispatcher::REF_TYPE_BRANCH;
188
189
		$options = [
190
			'sha' => $request->postVar('ref'),
191
			'ref_type' => $request->postVar('ref_type'),
192
			'branch' => $isBranchDeploy ? $request->postVar('ref_name') : null,
193
			'title' => $request->postVar('title'),
194
			'summary' => $request->postVar('summary')
195
		];
196
197 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...
198
			foreach (explode(',', $request->postVar('options')) as $option) {
199
				$options[$option] = true;
200
			}
201
		}
202
203
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
204
205
		$approver = Member::get()->byId($request->postVar('approver_id'));
206
		if ($approver && $approver->exists()) {
207
			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...
208
				return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
209
			}
210
		}
211
212
		$deployment = $strategy->createDeployment();
213
		if ($approver && $approver->exists()) {
214
			$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...
215
			$deployment->write();
216
		}
217
218
		return $this->getAPIResponse([
219
			'message' => 'Deployment has been created',
220
			'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...
221
		], 201);
222
	}
223
224
	/**
225
	 * @param \SS_HTTPRequest $request
226
	 * @return \SS_HTTPResponse
227
	 */
228
	public function start(\SS_HTTPRequest $request) {
229
		if ($request->httpMethod() !== 'POST') {
230
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
231
		}
232
233
		$this->checkSecurityToken();
234
235
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
236
		$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...
237
		if ($errorResponse instanceof \SS_HTTPResponse) {
238
			return $errorResponse;
239
		}
240
241
		// The deployment cannot be started until it has been approved, or bypassed straight to approved state
242
		if ($deployment->State != DNDeployment::STATE_APPROVED) {
243
			return $this->getAPIResponse(['message' => 'This deployment has not been approved. Cannot deploy'], 403);
244
		}
245
246
		// until we have a system that can invalidate currently scheduled deployments due
247
		// to emergency deploys etc, replan the deployment to check if it's still valid.
248
		$options = $deployment->getDeploymentStrategy()->getOptions();
249
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
250
		$deployment->Strategy = $strategy->toJSON();
251
		$deployment->write();
252
253
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
254
255
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
256
257
		$response = $this->getAPIResponse([
258
			'message' => 'Deployment has been queued',
259
			'location' => $location,
260
			'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...
261
		], 201);
262
263
		$response->addHeader('Location', $location);
264
265
		return $response;
266
	}
267
268
	/**
269
	 * @param string $action
270
	 * @return string
271
	 */
272
	public function Link($action = '') {
273
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
274
	}
275
276
	/**
277
	 * @param string $name
278
	 * @return array
279
	 */
280
	public function getModel($name = '') {
281
		return [];
282
	}
283
284
	/**
285
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
286
	 * an APIResponse with the error, otherwise null.
287
	 *
288
	 * @param \DNDeployment $deployment
289
	 *
290
	 * @return null|SS_HTTPResponse
291
	 */
292 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...
293
		if (!$deployment || !$deployment->exists()) {
294
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
295
		}
296
		if ($deployment->EnvironmentID != $this->environment->ID) {
297
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
298
		}
299
		if (!$deployment->canView()) {
300
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
301
		}
302
		return null;
303
	}
304
305
}
306