Passed
Pull Request — master (#99)
by Daniel
34:06
created

WebsitesController::updatePersonalWebsite()   D

Complexity

Conditions 18
Paths 99

Size

Total Lines 61
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 136.0828

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 44
c 1
b 0
f 0
dl 0
loc 61
ccs 12
cts 42
cp 0.2857
rs 4.8666
cc 18
nc 99
nop 2
crap 136.0828

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * CMS Pico - Create websites using Pico CMS for Nextcloud.
4
 *
5
 * @copyright Copyright (c) 2017, Maxence Lange (<[email protected]>)
6
 * @copyright Copyright (c) 2019, Daniel Rudolf (<[email protected]>)
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 */
23
24
declare(strict_types=1);
25
26
namespace OCA\CMSPico\Controller;
27
28
use OCA\CMSPico\AppInfo\Application;
29
use OCA\CMSPico\Exceptions\TemplateNotCompatibleException;
30
use OCA\CMSPico\Exceptions\TemplateNotFoundException;
31
use OCA\CMSPico\Exceptions\ThemeNotCompatibleException;
32
use OCA\CMSPico\Exceptions\ThemeNotFoundException;
33
use OCA\CMSPico\Exceptions\WebsiteExistsException;
34
use OCA\CMSPico\Exceptions\WebsiteForeignOwnerException;
35
use OCA\CMSPico\Exceptions\WebsiteInvalidDataException;
36
use OCA\CMSPico\Exceptions\WebsiteInvalidOwnerException;
37
use OCA\CMSPico\Exceptions\WebsiteNotFoundException;
38
use OCA\CMSPico\Model\Website;
39
use OCA\CMSPico\Service\WebsitesService;
40
use OCP\AppFramework\Controller;
41
use OCP\AppFramework\Http;
42
use OCP\AppFramework\Http\DataResponse;
43
use OCP\IL10N;
44
use OCP\ILogger;
45
use OCP\IRequest;
46
use OCP\IUserSession;
47
48
class WebsitesController extends Controller
49
{
50
	use ControllerTrait;
51
52
	/** @var IUserSession */
53
	private $userSession;
54
55
	/** @var IL10N */
56
	private $l10n;
57
58
	/** @var WebsitesService */
59
	private $websitesService;
60
61
	/**
62
	 * WebsitesController constructor.
63
	 *
64
	 * @param IRequest        $request
65
	 * @param IUserSession    $userSession
66
	 * @param IL10N           $l10n
67
	 * @param ILogger         $logger
68
	 * @param WebsitesService $websitesService
69
	 */
70 1
	public function __construct(
71
		IRequest $request,
72
		IUserSession $userSession,
73
		IL10N $l10n,
74
		ILogger $logger,
75
		WebsitesService $websitesService
76
	) {
77 1
		parent::__construct(Application::APP_NAME, $request);
78
79 1
		$this->userSession = $userSession;
80 1
		$this->l10n = $l10n;
81 1
		$this->logger = $logger;
82 1
		$this->websitesService = $websitesService;
83 1
	}
84
85
	/**
86
	 * @NoAdminRequired
87
	 *
88
	 * @return DataResponse
89
	 */
90 6
	public function getPersonalWebsites(): DataResponse
91
	{
92 6
		$userId = $this->userSession->getUser()->getUID();
93 6
		$data = [ 'websites' => $this->websitesService->getWebsitesFromUser($userId) ];
94 6
		return new DataResponse($data, Http::STATUS_OK);
95
	}
96
97
	/**
98
	 * @NoAdminRequired
99
	 *
100
	 * @param array<string,string> $data
101
	 *
102
	 * @return DataResponse
103
	 */
104 3
	public function createPersonalWebsite(array $data): DataResponse
105
	{
106 3
		$userId = $this->userSession->getUser()->getUID();
107
108
		try {
109 3
			$website = (new Website())
110 3
				->setName($data['name'] ?? '')
111 3
				->setUserId($userId)
112 3
				->setSite($data['site'] ?? '')
113 3
				->setTheme($data['theme'] ?? '')
114 3
				->setPath($data['path'] ?? '');
115
116 3
			$website->assertValidOwner();
117
118 3
			$this->websitesService->createWebsite($website, $data['template'] ?? '');
119
120 2
			return $this->getPersonalWebsites();
121 1
		} catch (\Exception $e) {
122 1
			$error = [];
123 1
			if ($e instanceof WebsiteExistsException) {
124 1
				$error['error'] = [ 'field' => 'site', 'message' => $this->l10n->t('Website exists.') ];
125
			} elseif ($e instanceof WebsiteInvalidOwnerException) {
126
				$error['error'] = [ 'field' => 'user', 'message' => $this->l10n->t('No permission.') ];
127
			} elseif (($e instanceof WebsiteInvalidDataException) && $e->getField()) {
128
				$error['error'] = [ 'field' => $e->getField(), 'message' => $e->getMessage() ];
129
			} elseif ($e instanceof ThemeNotFoundException) {
130
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t('Theme not found.') ];
131
			} elseif ($e instanceof ThemeNotCompatibleException) {
132
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t($e->getReason()) ];
133
			} elseif ($e instanceof TemplateNotFoundException) {
134
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t('Template not found.') ];
135
			} elseif ($e instanceof TemplateNotCompatibleException) {
136
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t($e->getReason()) ];
137
			}
138
139 1
			return $this->createErrorResponse($e, $error);
140
		}
141
	}
142
143
	/**
144
	 * @NoAdminRequired
145
	 *
146
	 * @param int     $siteId
147
	 * @param mixed[] $data
148
	 *
149
	 * @return DataResponse
150
	 */
151 1
	public function updatePersonalWebsite(int $siteId, array $data): DataResponse
152
	{
153
		try {
154 1
			$website = $this->websitesService->getWebsiteFromId($siteId);
155
156 1
			$userId = $this->userSession->getUser()->getUID();
157 1
			$website->assertOwnedBy($userId);
158
159 1
			foreach ($data as $key => $value) {
160 1
				switch ($key) {
161 1
					case 'name':
162
						$website->setName($value);
163
						break;
164
165 1
					case 'type':
166 1
						$website->setType((int) $value);
167 1
						break;
168
169
					case 'theme':
170
						$website->setTheme($value);
171
						break;
172
173
					case 'options':
174
						foreach ($value as $optionKey => $optionValue) {
175
							switch ($optionKey) {
176
								case 'group_access':
177
									$groupAccess = $optionValue ? explode('|', $optionValue) : [];
178
									$website->setOption($optionKey, $groupAccess ?: null);
179
									break;
180
181
								default:
182
									throw new WebsiteInvalidDataException();
183
							}
184
						}
185
						break;
186
187
					default:
188
						throw new WebsiteInvalidDataException();
189
				}
190
			}
191
192 1
			$this->websitesService->updateWebsite($website);
193
194 1
			return $this->getPersonalWebsites();
195
		} catch (\Exception $e) {
196
			$error = [];
197
			if (($e instanceof WebsiteNotFoundException) || ($e instanceof WebsiteForeignOwnerException)) {
198
				$error['error'] = [ 'field' => 'identifier', 'message' => $this->l10n->t('Website not found.') ];
199
			} elseif ($e instanceof WebsiteInvalidDataException) {
200
				$error['error'] = [ 'field' => $e->getField(), 'message' => $e->getMessage() ];
201
			} elseif ($e instanceof ThemeNotFoundException) {
202
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t('Theme not found.') ];
203
			} elseif ($e instanceof ThemeNotCompatibleException) {
204
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t($e->getReason()) ];
205
			} elseif ($e instanceof TemplateNotFoundException) {
206
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t('Template not found.') ];
207
			} elseif ($e instanceof TemplateNotCompatibleException) {
208
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t($e->getReason()) ];
209
			}
210
211
			return $this->createErrorResponse($e, $error);
212
		}
213
	}
214
215
	/**
216
	 * @NoAdminRequired
217
	 *
218
	 * @param int $siteId
219
	 *
220
	 * @return DataResponse
221
	 */
222 1
	public function removePersonalWebsite(int $siteId): DataResponse
223
	{
224
		try {
225 1
			$website = $this->websitesService->getWebsiteFromId($siteId);
226
227 1
			$userId = $this->userSession->getUser()->getUID();
228 1
			$website->assertOwnedBy($userId);
229
230 1
			$this->websitesService->deleteWebsite($website);
231
232 1
			return $this->getPersonalWebsites();
233
		} catch (WebsiteNotFoundException $e) {
234
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Website not found.') ]);
235
		} catch (WebsiteForeignOwnerException $e) {
236
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Website not found.') ]);
237
		} catch (\Exception $e) {
238
			return $this->createErrorResponse($e);
239
		}
240
	}
241
}
242