Completed
Pull Request — master (#634)
by Sean
09:29 queued 05:52
created

DeployDispatcher::Link()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 3
rs 10
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 {
8
9
	const ACTION_DEPLOY = 'deploys';
10
11
	/**
12
	 * @var array
13
	 */
14
	private static $action_types = [
15
		self::ACTION_DEPLOY
16
	];
17
18
	/**
19
	 * @var array
20
	 */
21
	public static $allowed_actions = [
22
		'history',
23
		'currentbuild',
24
		'deployment',
25
		'log',
26
		'start'
27
	];
28
29
	/**
30
	 * @var \DNProject
31
	 */
32
	protected $project = null;
33
34
	/**
35
	 * @var \DNEnvironment
36
	 */
37
	protected $environment = null;
38
39 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...
40
		parent::init();
41
42
		$this->project = $this->getCurrentProject();
43
44
		if (!$this->project) {
45
			return $this->project404Response();
46
		}
47
48
		// Performs canView permission check by limiting visible projects
49
		$this->environment = $this->getCurrentEnvironment($this->project);
50
		if (!$this->environment) {
51
			return $this->environment404Response();
52
		}
53
	}
54
55
	/**
56
	 * @param \SS_HTTPRequest $request
57
	 * @return \HTMLText|\SS_HTTPResponse
58
	 */
59
	public function index(\SS_HTTPRequest $request) {
60
		return $this->redirect(\Controller::join_links($this->Link(), 'history'), 302);
61
	}
62
63
	/**
64
	 * @param \SS_HTTPRequest $request
65
	 * @return \SS_HTTPResponse
66
	 */
67
	public function history(SS_HTTPRequest $request) {
68
		$data = [];
69
		$list = $this->DeployHistory();
0 ignored issues
show
Deprecated Code introduced by
The method DNRoot::DeployHistory() has been deprecated with message: 2.0.0 - moved to DeployDispatcher

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
70
		$page = $request->getVar('page') ?: 1;
71
		if ($page > $list->TotalPages()) {
72
			$page = 1;
73
		}
74
		if ($page < 1) {
75
			$page = 1;
76
		}
77
		$start = ($page - 1) * $list->getPageLength();
78
		$list->setPageStart((int) $start);
79
		if (empty($list)) {
80
			return $this->getAPIResponse(['list' => []], 200);
81
		}
82
83
		foreach ($list as $deployment) {
84
			$data[] = $this->getDeploymentData($deployment);
85
		}
86
87
		return $this->getAPIResponse([
88
			'list' => $data,
89
			'pagelength' => $list->getPageLength(),
90
			'totalpages' => $list->TotalPages(),
91
			'currentpage' => $list->CurrentPage()
92
		], 200);
93
	}
94
95
	/**
96
	 * @param \SS_HTTPRequest $request
97
	 * @return \SS_HTTPResponse
98
	 */
99
	public function currentbuild(SS_HTTPRequest $request) {
100
		$currentBuild = $this->environment->CurrentBuild();
101
		if (!$currentBuild) {
102
			return $this->getAPIResponse(['deployment' => []], 200);
103
		}
104
		return $this->getAPIResponse(['deployment' => $this->getDeploymentData($currentBuild)], 200);
105
	}
106
107
	/**
108
	 * @param \SS_HTTPRequest $request
109
	 * @return \SS_HTTPResponse
110
	 */
111
	public function deployment(SS_HTTPRequest $request) {
112
		$deployment = DNDeployment::get()->byId($request->param('ID'));
113
		if (!$deployment || !$deployment->exists()) {
114
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
115
		}
116
		if (!$deployment->canView()) {
117
			return $this->getAPIResponse(['message' => 'You are not authorized to deploy this environment'], 403);
118
		}
119
		return $this->getAPIResponse(['deployment' => $this->getDeploymentData($deployment)], 200);
0 ignored issues
show
Compatibility introduced by
$deployment of type object<DataObject> is not a sub-type of object<DNDeployment>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
120
	}
121
122
	/**
123
	 * @param \SS_HTTPRequest $request
124
	 * @return \SS_HTTPResponse
125
	 */
126
	public function log(SS_HTTPRequest $request) {
127
		$deployment = DNDeployment::get()->byId($request->params('ID'));
0 ignored issues
show
Unused Code introduced by
The call to SS_HTTPRequest::params() has too many arguments starting with 'ID'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Documentation introduced by
$request->params('ID') is of type array, but the function expects a integer.

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...
128
		if (!$deployment || !$deployment->exists) {
129
			return $this->getAPIResponse(['message' => 'This deployment does not exist'], 404);
130
		}
131
		if(!$deployment->canView()) {
132
			return $this->getAPIResponse(['message' => 'You are not authorized to view this environment'], 403);
133
		}
134
135
		$log = $deployment->log();
136
		$content = $log->exists() ? $log->content() : 'Waiting for action to start';
137
		$lines = explode(PHP_EOL, $content);
138
139
		return $this->getAPIResponse(['message' => $lines, 'status' => $deployment->Status], 200);
140
	}
141
142
	/**
143
	 * @param \SS_HTTPRequest $request
144
	 * @return \SS_HTTPResponse
145
	 */
146
	public function start(SS_HTTPRequest $request) {
147
		$this->checkSecurityToken();
148
149
		if (!$this->environment->canDeploy(Member::currentUser())) {
0 ignored issues
show
Bug introduced by
It seems like \Member::currentUser() targeting Member::currentUser() can also be of type object<DataObject>; however, DNEnvironment::canDeploy() does only seem to accept object<Member>|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
150
			return $this->getAPIResponse(['message' => 'You are not authorized to deploy this environment'], 403);
151
		}
152
153
		// @todo the strategy should have been saved when there has been a request for an
154
		// approval or a bypass. This saved state needs to be checked if it's invalidated
155
		// if another deploy happens before this one
156
		$options = [
157
			'sha' => $request->requestVar('sha'),
158
		];
159
		$strategy = $this->environment->Backend()->planDeploy($this->environment, $options);
160
161
		$strategy->fromArray($request->requestVars());
0 ignored issues
show
Documentation introduced by
$request->requestVars() is of type array|null, 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...
162
		$deployment = $strategy->createDeployment();
163
164
		// Skip through the approval state for now.
165
		$deployment->getMachine()->apply(DNDeployment::TR_SUBMIT);
166
		$deployment->getMachine()->apply(DNDeployment::TR_QUEUE);
167
168
		$location = \Controller::join_links(Director::absoluteBaseURL(), $this->Link('log'), $deployment->ID);
169
170
		$response = $this->getAPIResponse([
171
			'message' => 'deployment has been queued',
172
			'ID' => $deployment->ID,
173
			'location' => $location
174
		], 201);
175
		$response->addHeader('Location', $location);
176
		return $response;
177
	}
178
179
	/**
180
	 * @param string $action
181
	 * @return string
182
	 */
183
	public function Link($action = '') {
184
		return \Controller::join_links($this->environment->Link(), self::ACTION_DEPLOY, $action);
185
	}
186
187
	/**
188
	 * @param string $name
189
	 * @return array
190
	 */
191
	public function getModel($name = '') {
192
		return [];
193
	}
194
195
	/**
196
	 * Return data about a single deployment.
197
	 * @param DNDeployment $deployment
198
	 * @return array
199
	 */
200
	protected function getDeploymentData(DNDeployment $deployment) {
201
		$currentBuild = $this->environment->CurrentBuild();
202
203
		return [
204
			'ID' => $deployment->ID,
205
			'CreatedDate' => $deployment->Created,
206
			'DatePlanned' => $deployment->DatePlanned,
0 ignored issues
show
Documentation introduced by
The property DatePlanned does not exist on object<DNDeployment>. 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...
207
			'Summary' => $deployment->Summary,
0 ignored issues
show
Bug introduced by
The property Summary does not seem to exist. Did you mean summary_fields?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
208
			'Branch' => $deployment->Branch,
0 ignored issues
show
Documentation introduced by
The property Branch does not exist on object<DNDeployment>. 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...
209
			'Tags' => $deployment->getTags()->toArray(),
210
			'Changes' => $deployment->getDeploymentStrategy()->getChanges(),
211
			'SHA' => $deployment->SHA,
212
			'CommitMessage' => $deployment->getCommitMessage(),
213
			'CommitURL' => $deployment->getCommitURL(),
214
			'Deployer' => $deployment->Deployer()->getName(),
215
			'Approver' => $deployment->Approver()->getName(),
0 ignored issues
show
Documentation Bug introduced by
The method Approver does not exist on object<DNDeployment>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
216
			'State' => $deployment->State,
217
			'IsCurrentBuild' => $currentBuild ? ($deployment->ID === $currentBuild->ID) : null
218
		];
219
	}
220
221
}
222