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

DeployDispatcher::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

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