Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
TranslationController
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
2 / 2
4
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 translations
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3/**
4 * The Translations Controller
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public License,
7 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
8 * obtain one at https://mozilla.org/MPL/2.0/.
9 *
10 * @package   phpMyFAQ
11 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
12 * @copyright 2025-2026 phpMyFAQ Team
13 * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
14 * @link      https://www.phpmyfaq.de
15 * @since     2025-03-17
16 */
17
18declare(strict_types=1);
19
20namespace phpMyFAQ\Controller\Frontend\Api;
21
22use Closure;
23use phpMyFAQ\Controller\AbstractController;
24use phpMyFAQ\Core\Exception;
25use phpMyFAQ\Filter;
26use phpMyFAQ\Language;
27use phpMyFAQ\Translation;
28use Symfony\Component\HttpFoundation\JsonResponse;
29use Symfony\Component\HttpFoundation\Request;
30use Symfony\Component\HttpFoundation\Response;
31use Symfony\Component\Routing\Attribute\Route;
32
33final class TranslationController extends AbstractController
34{
35    /**
36     * @param ?Closure(string): void $setCurrentLanguage
37     * @param ?Closure(): array      $getTranslations
38     * @throws \Exception
39     */
40    public function __construct(
41        private readonly ?Closure $setCurrentLanguage = null,
42        private readonly ?Closure $getTranslations = null,
43    ) {
44        parent::__construct();
45    }
46
47    #[Route(path: 'translations/{language}', name: 'api.private.translations', methods: ['GET'])]
48    public function translations(Request $request): JsonResponse
49    {
50        $language = Filter::filterVar($request->attributes->get('language'), FILTER_SANITIZE_SPECIAL_CHARS, '');
51
52        if (!Language::isASupportedLanguage($language)) {
53            return $this->json(['error' => 'Language not supported'], Response::HTTP_BAD_REQUEST);
54        }
55
56        try {
57            ($this->setCurrentLanguage ?? static function (string $language): void {
58                Translation::getInstance()->setCurrentLanguage($language);
59            })($language);
60
61            return $this->json(($this->getTranslations ?? Translation::getAll(...))());
62        } catch (Exception $exception) {
63            return $this->json(['error' => $exception->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
64        }
65    }
66}