Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Http/Controllers/Base/LocaleController.php
10284 views
1
<?php
2
3
namespace Pterodactyl\Http\Controllers\Base;
4
5
use Illuminate\Http\JsonResponse;
6
use Illuminate\Translation\Translator;
7
use Illuminate\Contracts\Translation\Loader;
8
use Pterodactyl\Http\Controllers\Controller;
9
use Pterodactyl\Http\Requests\Base\LocaleRequest;
10
11
class LocaleController extends Controller
12
{
13
protected Loader $loader;
14
15
public function __construct(Translator $translator)
16
{
17
$this->loader = $translator->getLoader();
18
}
19
20
/**
21
* Returns translation data given a specific locale and namespace.
22
*/
23
public function __invoke(LocaleRequest $request): JsonResponse
24
{
25
$locale = $request->input('locale');
26
$namespace = $request->input('namespace');
27
$response[$locale][$namespace] = $this->i18n($this->loader->load($locale, $namespace));
28
29
return new JsonResponse($response, 200, [
30
// Cache this in the browser for an hour, and allow the browser to use a stale
31
// cache for up to a day after it was created while it fetches an updated set
32
// of translation keys.
33
'Cache-Control' => 'public, max-age=3600, stale-while-revalidate=86400',
34
'ETag' => md5(json_encode($response, JSON_THROW_ON_ERROR)),
35
]);
36
}
37
38
/**
39
* Convert standard Laravel translation keys that look like ":foo"
40
* into key structures that are supported by the front-end i18n
41
* library, like "{{foo}}".
42
*/
43
protected function i18n(array $data): array
44
{
45
foreach ($data as $key => $value) {
46
if (is_array($value)) {
47
$data[$key] = $this->i18n($value);
48
} else {
49
// Find a Laravel style translation replacement in the string and replace it with
50
// one that the front-end is able to use. This won't always be present, especially
51
// for complex strings or things where we'd never have a backend component anyways.
52
//
53
// For example:
54
// "Hello :name, the :notifications.0.title notification needs :count actions :foo.0.bar."
55
//
56
// Becomes:
57
// "Hello {{name}}, the {{notifications.0.title}} notification needs {{count}} actions {{foo.0.bar}}."
58
$data[$key] = preg_replace('/:([\w.-]+\w)([^\w:]?|$)/m', '{{$1}}$2', $value);
59
}
60
}
61
62
return $data;
63
}
64
}
65
66