Passed
Push — master ( 14685e...6cfd53 )
by Julius
15:11 queued 13s
created

TranslationApiController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
nc 1
nop 3
dl 0
loc 4
c 1
b 0
f 0
cc 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright Copyright (c) 2022 Julius Härtl <[email protected]>
7
 *
8
 * @author Julius Härtl <[email protected]>
9
 *
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24
 */
25
26
27
namespace OC\Core\Controller;
28
29
use InvalidArgumentException;
30
use OCP\AppFramework\Http;
31
use OCP\AppFramework\Http\DataResponse;
32
use OCP\IRequest;
33
use OCP\PreConditionNotMetException;
34
use OCP\Translation\ITranslationManager;
35
use RuntimeException;
36
37
class TranslationApiController extends \OCP\AppFramework\OCSController {
38
	private ITranslationManager $translationManager;
39
40
	public function __construct($appName, IRequest $request, ITranslationManager $translationManager) {
41
		parent::__construct($appName, $request);
42
43
		$this->translationManager = $translationManager;
44
	}
45
46
	public function languages(): DataResponse {
47
		return new DataResponse([
48
			'languages' => $this->translationManager->getLanguages(),
49
			'languageDetection' => $this->translationManager->canDetectLanguage(),
50
		]);
51
	}
52
53
	public function translate(string $text, ?string $fromLanguage, string $toLanguage): DataResponse {
54
		try {
55
			return new DataResponse([
56
				'text' => $this->translationManager->translate($text, $fromLanguage, $toLanguage)
57
			]);
58
		} catch (PreConditionNotMetException) {
59
			return new DataResponse(['message' => 'No translation provider available'], Http::STATUS_PRECONDITION_FAILED);
60
		} catch (InvalidArgumentException) {
61
			return new DataResponse(['message' => 'Could not detect language', Http::STATUS_NOT_FOUND]);
62
		} catch (RuntimeException) {
63
			return new DataResponse(['message' => 'Unable to translate', Http::STATUS_INTERNAL_SERVER_ERROR]);
64
		}
65
	}
66
}
67