Completed
Pull Request — master (#655)
by Sean
05:54
created

GitDispatcher::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 GitDispatcher 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_GIT = 'git';
10
11
	const REF_TYPE_FROM_UAT = 0;
12
	const REF_TYPE_BRANCH = 1;
13
	const REF_TYPE_TAG = 2;
14
	const REF_TYPE_PREVIOUS = 3;
15
	const REF_TYPE_SHA = 4;
16
17
	/**
18
	 * @var array
19
	 */
20
	public static $allowed_actions = [
21
		'update',
22
		'show'
23
	];
24
25
	/**
26
	 * @var \DNProject
27
	 */
28
	protected $project = null;
29
30
	/**
31
	 * @var \DNEnvironment
32
	 */
33
	protected $environment = null;
34
35
	/**
36
	 * @var array
37
	 */
38
	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...
39
		self::ACTION_GIT
40
	];
41
42
	public function init() {
43
		parent::init();
44
45
		$this->project = $this->getCurrentProject();
46
47
		if (!$this->project) {
48
			return $this->project404Response();
49
		}
50
	}
51
52
	/**
53
	 *
54
	 * @param \SS_HTTPRequest $request
55
	 *
56
	 * @return \HTMLText|\SS_HTTPResponse
57
	 */
58
	public function index(\SS_HTTPRequest $request) {
59
		return $this->redirect(\Controller::join_links($this->Link(), 'show'), 302);
60
	}
61
62
	/**
63
	 * @param SS_HTTPRequest $request
64
	 * @return SS_HTTPResponse
65
	 */
66
	public function update(SS_HTTPRequest $request) {
67
		switch ($request->httpMethod()) {
68
			case 'POST':
69
				$this->checkSecurityToken();
70
				return $this->createUpdate();
71
			case 'GET':
72
				return $this->getUpdateStatus($this->getRequest()->param('ID'));
73
			default:
74
				return $this->getAPIResponse(['message' => 'Method not allowed, requires POST or GET/{id}'], 405);
75
		}
76
	}
77
78
	/**
79
	 * @param SS_HTTPRequest $request
80
	 *
81
	 * @return string
82
	 */
83
	public function show(\SS_HTTPRequest $request) {
84
		$targetEnvironment = null;
85
		if (!empty($request->getVar('environmentId'))) {
86
			$targetEnvironment = DNEnvironment::get()->byId((int) $request->getVar('environmentId'));
87
		}
88
89
		$refs = [];
90
		$prevDeploys = [];
91
92
		$uatEnvironment = $this->project->DNEnvironmentList()->filter('Usage', 'UAT')->first();
93
		$uatBuild = $uatEnvironment ? $uatEnvironment->CurrentBuild() : null;
94
		if ($uatBuild && $uatBuild->exists() && $targetEnvironment && $targetEnvironment->Usage === 'Production') {
95
			$refs[self::REF_TYPE_FROM_UAT] = [
96
				'id' => self::REF_TYPE_FROM_UAT,
97
				'label' => 'Promote the version currently on UAT',
98
				'description' => 'Promote the version currently on UAT',
99
				'promote_build' => [
100
					'id' => $uatBuild->ID,
101
					'deployed' => DBField::create_field('SS_Datetime', $uatBuild->Created, 'Created')->Ago(),
102
					'branch' => $uatBuild->Branch,
103
					'tags' => $uatBuild->getTags()->toArray(),
104
					'sha' => $uatBuild->SHA,
105
					'commit_message' => $uatBuild->getCommitMessage(),
106
					'commit_url' => $uatBuild->getCommitURL(),
107
				]
108
			];
109
		}
110
111
		$refs[self::REF_TYPE_BRANCH] = [
112
			'id' => self::REF_TYPE_BRANCH,
113
			'label' => 'Branch version',
114
			'description' => 'Deploy the latest version of a branch',
115
			'list' => $this->getGitBranches($this->project)
116
		];
117
118
		$refs[self::REF_TYPE_TAG] = [
119
			'id' => self::REF_TYPE_TAG,
120
			'label' => 'Tag version',
121
			'description' => 'Deploy a tagged release',
122
			'list' => $this->getGitTags($this->project)
123
		];
124
125
		// @todo: the original was a tree that was keyed by environment, the
126
		// front-end dropdown needs to be changed to support that. brrrr.
127
		foreach ($this->getGitPrevDeploys($this->project) as $env) {
128
			foreach ($env as $deploy) {
129
				$prevDeploys[] = $deploy;
130
			}
131
		}
132
		$refs[self::REF_TYPE_PREVIOUS] = [
133
			'id' => self::REF_TYPE_PREVIOUS,
134
			'label' => 'Redeploy a release that was previously deployed (to any environment)',
135
			'description' => 'Deploy a previous release',
136
			'list' => $prevDeploys
137
		];
138
		$refs[self::REF_TYPE_SHA] = [
139
			'id' => self::REF_TYPE_SHA,
140
			'label' => 'Deploy a specific SHA',
141
			'description' => 'Deploy a specific SHA'
142
		];
143
144
		return $this->getAPIResponse(['refs' => $refs], 200);
145
	}
146
147
	/**
148
	 * @return string
149
	 */
150
	public function Link() {
151
		return \Controller::join_links($this->project->Link(), self::ACTION_GIT);
152
	}
153
154
	/**
155
	 * @param string $name
156
	 *
157
	 * @return array
158
	 */
159
	public function getModel($name = '') {
160
		return [];
161
	}
162
163
	/**
164
	 * @param int $ID
165
	 * @return SS_HTTPResponse
166
	 */
167
	protected function getUpdateStatus($ID) {
168
		$ping = DNGitFetch::get()->byID($ID);
169
		if (!$ping) {
170
			return $this->getAPIResponse(['message' => 'GIT update (' . $ID . ') not found'], 404);
171
		}
172
		$output = [
173
			'id' => $ID,
174
			'status' => $ping->ResqueStatus(),
175
			'message' => array_filter(explode(PHP_EOL, $ping->LogContent()))
176
		];
177
178
		return $this->getAPIResponse($output, 200);
179
	}
180
181
	/**
182
	 * @return SS_HTTPResponse
183
	 */
184 View Code Duplication
	protected function createUpdate() {
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...
185
		/** @var DNGitFetch $fetch */
186
		$fetch = DNGitFetch::create();
187
		$fetch->ProjectID = $this->project->ID;
188
		$fetch->write();
189
		$fetch->start();
190
191
		$location = Director::absoluteBaseURL() . $this->Link() . '/update/' . $fetch->ID;
192
		$output = [
193
			'message' => 'git fetch has been queued',
194
			'id' => $fetch->ID,
195
			'location' => $location,
196
		];
197
198
		$response = $this->getAPIResponse($output, 201);
199
		$response->addHeader('Location', $location);
200
		return $response;
201
	}
202
203
	/**
204
	 * @param $project
205
	 *
206
	 * @return array
207
	 */
208
	protected function getGitBranches($project) {
209
		$branches = [];
210
		foreach ($project->DNBranchList() as $branch) {
211
			$branches[] = [
212
				'key' => $branch->SHA(),
213
				'value' => $branch->Name(),
214
			];
215
		}
216
		return $branches;
217
	}
218
219
	/**
220
	 * @param $project
221
	 *
222
	 * @return array
223
	 */
224
	protected function getGitTags($project) {
225
		$tags = [];
226
		foreach ($project->DNTagList()->setLimit(null) as $tag) {
227
			$tags[] = [
228
				'key' => $tag->SHA(),
229
				'value' => $tag->Name(),
230
			];
231
		}
232
		return $tags;
233
	}
234
235
	/**
236
	 * @param $project
237
	 *
238
	 * @return array
239
	 */
240
	protected function getGitPrevDeploys($project) {
241
		$redeploy = [];
242 View Code Duplication
		foreach ($project->DNEnvironmentList() as $dnEnvironment) {
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...
243
			$envName = $dnEnvironment->Name;
244
			$perEnvDeploys = [];
245
			foreach ($dnEnvironment->DeployHistory() as $deploy) {
246
				$sha = $deploy->SHA;
247
248
				// Check if exists to make sure the newest deployment date is used.
249
				if (!isset($perEnvDeploys[$sha])) {
250
					$pastValue = sprintf(
251
						"%s (deployed %s)",
252
						substr($sha, 0, 8),
253
						$deploy->obj('LastEdited')->Ago()
254
					);
255
					$perEnvDeploys[$sha] = [
256
						'key' => $sha,
257
						'value' => $pastValue
258
					];
259
				}
260
			}
261
			if (!empty($perEnvDeploys)) {
262
				$redeploy[$envName] = array_values($perEnvDeploys);
263
			}
264
		}
265
		return $redeploy;
266
	}
267
268
}
269