You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/UserCopy/UserCopyViewRuntime.php

108 lines
3.5 KiB
PHP

<?php
namespace App\Services\UserCopy;
use App\Services\PublicLocale;
use App\Utils\Cookie;
use Smarty;
/**
* User-page runtime seam for locale selection, Smarty copy and browser data.
*
* The implementation reads only the immutable runtime catalog and the
* source-owned Chinese fallback. Target-locale copy never lives in source.
*/
final class UserCopyViewRuntime
{
public function __construct(private readonly UserCopyRuntimeReader $reader)
{
}
public static function production(): self
{
$webRoot = dirname(__DIR__, 3);
$source = new UserCopySourceCatalog(UserCopyManifest::load());
return new self(new UserCopyRuntimeReader(
$webRoot . '/storage/framework/user-copy',
$source
));
}
public function bindCurrentRequest(
Smarty $smarty,
?string $page = null
): UserCopyCatalog {
$query = is_array($_GET) ? $_GET : [];
$cookies = is_array($_COOKIE) ? $_COOKIE : [];
$requested = PublicLocale::requestedLocale($query);
if ($requested !== null) {
Cookie::set([
PublicLocale::COOKIE_NAME => $requested,
], time() + PublicLocale::COOKIE_TTL);
$cookies[PublicLocale::COOKIE_NAME] = $requested;
}
$locale = PublicLocale::resolve(
$query,
$cookies,
isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])
? (string) $_SERVER['HTTP_ACCEPT_LANGUAGE'] : ''
);
$requestUri = isset($_SERVER['REQUEST_URI'])
? (string) $_SERVER['REQUEST_URI'] : '/';
return $this->bind($smarty, $locale, $requestUri, $page);
}
public function bind(
Smarty $smarty,
string $locale,
string $requestUri,
?string $page = null
): UserCopyCatalog {
$catalog = $page === null
? new UserCopyCatalog($this->reader, $locale, ['common'])
: UserCopyCatalog::forPage($this->reader, $locale, $page);
$snapshot = $catalog->catalog();
$bootstrap = json_encode([
'schema' => 1,
'locale' => $catalog->locale(),
'generation' => $catalog->generation(),
'messages' => $snapshot['messages'],
'metadata' => $snapshot['metadata'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_THROW_ON_ERROR);
$smarty->assign([
'user_copy_locale' => $catalog->locale(),
'user_copy_generation' => $catalog->generation(),
'user_copy_bootstrap_json' => $bootstrap,
'user_copy_language_zh_url' => PublicLocale::switchUrl(
PublicLocale::CHINESE,
$requestUri
),
'user_copy_language_en_url' => PublicLocale::switchUrl(
PublicLocale::ENGLISH,
$requestUri
),
]);
$smarty->unregisterPlugin('function', 'user_copy');
$smarty->registerPlugin(
'function',
'user_copy',
static function (array $parameters) use ($catalog): string {
$key = isset($parameters['key'])
? (string) $parameters['key'] : '';
unset($parameters['key']);
return htmlspecialchars(
$catalog->text($key, $parameters),
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
}
);
return $catalog;
}
}