Path: blob/1.0-develop/app/Http/Controllers/Base/LocaleController.php
10284 views
<?php12namespace Pterodactyl\Http\Controllers\Base;34use Illuminate\Http\JsonResponse;5use Illuminate\Translation\Translator;6use Illuminate\Contracts\Translation\Loader;7use Pterodactyl\Http\Controllers\Controller;8use Pterodactyl\Http\Requests\Base\LocaleRequest;910class LocaleController extends Controller11{12protected Loader $loader;1314public function __construct(Translator $translator)15{16$this->loader = $translator->getLoader();17}1819/**20* Returns translation data given a specific locale and namespace.21*/22public function __invoke(LocaleRequest $request): JsonResponse23{24$locale = $request->input('locale');25$namespace = $request->input('namespace');26$response[$locale][$namespace] = $this->i18n($this->loader->load($locale, $namespace));2728return new JsonResponse($response, 200, [29// Cache this in the browser for an hour, and allow the browser to use a stale30// cache for up to a day after it was created while it fetches an updated set31// of translation keys.32'Cache-Control' => 'public, max-age=3600, stale-while-revalidate=86400',33'ETag' => md5(json_encode($response, JSON_THROW_ON_ERROR)),34]);35}3637/**38* Convert standard Laravel translation keys that look like ":foo"39* into key structures that are supported by the front-end i18n40* library, like "{{foo}}".41*/42protected function i18n(array $data): array43{44foreach ($data as $key => $value) {45if (is_array($value)) {46$data[$key] = $this->i18n($value);47} else {48// Find a Laravel style translation replacement in the string and replace it with49// one that the front-end is able to use. This won't always be present, especially50// for complex strings or things where we'd never have a backend component anyways.51//52// For example:53// "Hello :name, the :notifications.0.title notification needs :count actions :foo.0.bar."54//55// Becomes:56// "Hello {{name}}, the {{notifications.0.title}} notification needs {{count}} actions {{foo.0.bar}}."57$data[$key] = preg_replace('/:([\w.-]+\w)([^\w:]?|$)/m', '{{$1}}$2', $value);58}59}6061return $data;62}63}646566