Completed
Pull Request — master (#720)
by Sean
05:10
created

DeployDispatcher::getModel()   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
		'log',
20
		'createdeployment',
21
		'start'
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
			'title' => $request->postVar('title'),
171
			'summary' => $request->postVar('summary')
172
		];
173
174 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...
175
			foreach (explode(',', $request->postVar('options')) as $option) {
176
				$options[$option] = 'true';
177
			}
178
		}
179
180
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
181
182
		$approver = Member::get()->byId($request->postVar('approver_id'));
183
		if ($approver && $approver->exists()) {
184
			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...
185
				return $this->getAPIResponse(['message' => 'The given approver does not have permissions to approve'], 403);
186
			}
187
		}
188
189
		$deployment = $strategy->createDeployment();
190
		if ($approver && $approver->exists()) {
191
			$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...
192
			$deployment->write();
193
		}
194
195
		return $this->getAPIResponse([
196
			'message' => 'Deployment has been created',
197
			'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...
198
		], 201);
199
	}
200
201
	/**
202
	 * @param \SS_HTTPRequest $request
203
	 * @return \SS_HTTPResponse
204
	 */
205
	public function start(SS_HTTPRequest $request) {
206
		if ($request->httpMethod() !== 'POST') {
207
			return $this->getAPIResponse(['message' => 'Method not allowed, requires POST'], 405);
208
		}
209
210
		$this->checkSecurityToken();
211
212
		$deployment = DNDeployment::get()->byId($request->postVar('id'));
213
		if (!$deployment || !$deployment->exists()) {
214
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
215
		}
216
217
		// The deployment cannot be started until it has been approved, or bypassed straight to approved state
218
		if ($deployment->State != DNDeployment::STATE_APPROVED) {
219
			return $this->getAPIResponse(['message' => 'This deployment has not been approved. Cannot deploy'], 403);
220
		}
221
222
		// until we have a system that can invalidate currently scheduled deployments due
223
		// to emergency deploys etc, replan the deployment to check if it's still valid.
224
		$options = $deployment->getDeploymentStrategy()->getOptions();
225
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
226
		$deployment->Strategy = $strategy->toJSON();
227
		$deployment->write();
228
229
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
230
231
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
232
233
		$response = $this->getAPIResponse([
234
			'message' => 'Deployment has been queued',
235
			'location' => $location,
236
			'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...
237
		], 201);
238
239
		$response->addHeader('Location', $location);
240
241
		return $response;
242
	}
243
244
	/**
245
	 * @param string $action
246
	 * @return string
247
	 */
248
	public function Link($action = '') {
249
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
250
	}
251
252
	/**
253
	 * @param string $name
254
	 * @return array
255
	 */
256
	public function getModel($name = '') {
257
		return [];
258
	}
259
260
	/**
261
	 * Check if a DNDeployment exists and do permission checks on it. If there is something wrong it will return
262
	 * an APIResponse with the error, otherwise null.
263
	 *
264
	 * @param \DNDeployment $deployment
265
	 *
266
	 * @return null|SS_HTTPResponse
267
	 */
268 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...
269
		if (!$deployment || !$deployment->exists()) {
270
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
271
		}
272
		if ($deployment->EnvironmentID != $this->environment->ID) {
273
			return $this->getAPIResponse(['message' => 'This deployment does not belong to the environment'], 403);
274
		}
275
		if (!$deployment->canView()) {
276
			return $this->getAPIResponse(['message' => 'You are not authorised to view this deployment'], 403);
277
		}
278
		return null;
279
	}
280
281
}
282