Completed
Pull Request — master (#681)
by Sean
06:16
created

DeployDispatcher::createdeployment()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 18
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
		'log',
20
		'create',
21
		'createdeployment'
22
	];
23
24
	private static $dependencies = [
25
		'formatter' => '%$DeploynautAPIFormatter'
26
	];
27
28
	/**
29
	 * @var \DNProject
30
	 */
31
	protected $project = null;
32
33
	/**
34
	 * @var \DNEnvironment
35
	 */
36
	protected $environment = null;
37
38
	/**
39
	 * @var array
40
	 */
41
	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...
42
		self::ACTION_DEPLOY
43
	];
44
45 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...
46
		parent::init();
47
48
		$this->project = $this->getCurrentProject();
49
50
		if (!$this->project) {
51
			return $this->project404Response();
52
		}
53
54
		// Performs canView permission check by limiting visible projects
55
		$this->environment = $this->getCurrentEnvironment($this->project);
56
		if (!$this->environment) {
57
			return $this->environment404Response();
58
		}
59
	}
60
61
	/**
62
	 * @param \SS_HTTPRequest $request
63
	 * @return \HTMLText|\SS_HTTPResponse
64
	 */
65
	public function index(\SS_HTTPRequest $request) {
66
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
67
	}
68
69
	/**
70
	 * @param \SS_HTTPRequest $request
71
	 * @return \SS_HTTPResponse
72
	 */
73 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...
74
		$data = [];
75
76
		$list = $this->environment->DeployHistory('DeployStarted');
77
78
		foreach ($list as $deployment) {
79
			$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...
80
		}
81
82
		return $this->getAPIResponse([
83
			'list' => $data,
84
		], 200);
85
	}
86
87
	/**
88
	 * @param \SS_HTTPRequest $request
89
	 * @return \SS_HTTPResponse
90
	 */
91 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...
92
		$data = [];
93
		$list = $this->environment->UpcomingDeployments();
94
		foreach ($list as $deployment) {
95
			$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...
96
		}
97
		return $this->getAPIResponse([
98
			'list' => $data,
99
		], 200);
100
	}
101
102
	/**
103
	 * @param \SS_HTTPRequest $request
104
	 * @return \SS_HTTPResponse
105
	 */
106
	public function currentbuild(SS_HTTPRequest $request) {
107
		$currentBuild = $this->environment->CurrentBuild();
108
		if (!$currentBuild) {
109
			return $this->getAPIResponse(['deployment' => []], 200);
110
		}
111
		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...
112
	}
113
114
	/**
115
	 * @param \SS_HTTPRequest $request
116
	 * @return \SS_HTTPResponse
117
	 */
118
	public function show(SS_HTTPRequest $request) {
119
		$deployment = DNDeployment::get()->byId($request->param('ID'));
120
		$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...
121
		if ($errorResponse instanceof \SS_HTTPResponse) {
122
			return $errorResponse;
123
		}
124
		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...
125
	}
126
127
	/**
128
	 * @param \SS_HTTPRequest $request
129
	 * @return \SS_HTTPResponse
130
	 */
131
	public function log(SS_HTTPRequest $request) {
132
		$deployment = DNDeployment::get()->byId($request->param('ID'));
133
		$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...
134
		if ($errorResponse instanceof \SS_HTTPResponse) {
135
			return $errorResponse;
136
		}
137
		$log = $deployment->log();
138
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
139
		$lines = explode(PHP_EOL, $content);
140
141
		return $this->getAPIResponse([
142
			'message' => $lines,
143
			'status' => $deployment->Status,
144
			'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...
145
		], 200);
146
	}
147
148
	/**
149
	 * Create deployment. Can't use {@link create()} as it's taken by Object.
150
	 *
151
	 * @param \SS_HTTPRequest $request
152
	 * @return \SS_HTTPResponse
153
	 */
154
	public function createdeployment(SS_HTTPRequest $request) {
155
		if ($request->httpMethod() !== 'POST') {
156
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
157
		}
158
159
		$this->checkSecurityToken();
160
161
		// @todo the strategy should have been saved when there has been a request for an
162
		// approval or a bypass. This saved state needs to be checked if it's invalidated
163
		// if another deploy happens before this one
164
		$isBranchDeploy = (int) $request->postVar('ref_type') === GitDispatcher::REF_TYPE_BRANCH;
165
166
		$options = [
167
			'sha' => $request->postVar('ref'),
168
			'ref_type' => $request->postVar('ref_type'),
169
			'branch' => $isBranchDeploy ? $request->postVar('ref_name') : null,
170
			'summary' => $request->postVar('summary')
171
		];
172
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
173
174
		$strategy->fromArray($request->postVars());
0 ignored issues
show
Documentation introduced by
$request->postVars() is of type array, 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...
175
		$deployment = $strategy->createDeployment();
176
177
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
178
179
		return $this->getAPIResponse([
180
			'message' => 'Deployment has been created',
181
			'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...
182
		], 201);
183
	}
184
185
	/**
186
	 * @param \SS_HTTPRequest $request
187
	 * @return \SS_HTTPResponse
188
	 */
189
	public function start(SS_HTTPRequest $request) {
190
		if ($request->httpMethod() !== 'POST') {
191
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
192
		}
193
194
		$this->checkSecurityToken();
195
196
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
197
		if (!$deployment || !$deployment->exists()) {
198
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
199
		}
200
201
		// The deployment cannot be started until it has been approved, or bypassed straight to approved state
202
		if ($deployment->State != DNDeployment::STATE_APPROVED) {
203
			return $this->getAPIResponse(['message' => 'This deployment has not been approved. Cannot deploy'], 403);
204
		}
205
206
		// until we have a system that can invalidate currently scheduled deployments due
207
		// to emergency deploys etc, replan the deployment to check if it's still valid.
208
		$options = $deployment->getDeploymentStrategy()->getOptions();
209
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
210
		$deployment->Strategy = $strategy->toJSON();
211
		$deployment->write();
212
213
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
214
215
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
216
217
		$response = $this->getAPIResponse([
218
			'message' => 'Deployment has been queued',
219
			'location' => $location,
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
		$response->addHeader('Location', $location);
224
225
		return $response;
226
	}
227
228
	/**
229
	 * @param string $action
230
	 * @return string
231
	 */
232
	public function Link($action = '') {
233
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
234
	}
235
236
	/**
237
	 * @param string $name
238
	 * @return array
239
	 */
240
	public function getModel($name = '') {
241
		return [];
242
	}
243
244
	/**
245
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
246
	 * an APIResponse with the error, otherwise null.
247
	 *
248
	 * @param \DNDeployment $deployment
249
	 *
250
	 * @return null|SS_HTTPResponse
251
	 */
252 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...
253
		if (!$deployment || !$deployment->exists()) {
254
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
255
		}
256
		if ($deployment->EnvironmentID != $this->environment->ID) {
257
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
258
		}
259
		if (!$deployment->canView()) {
260
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
261
		}
262
		return null;
263
	}
264
265
}
266