blessing-skin-server/app/Services/Translations/JavaScript.php

75 lines
2.2 KiB
PHP
Raw Normal View History

2019-09-07 17:18:58 +08:00
<?php
namespace App\Services\Translations;
2020-06-23 18:17:16 +08:00
use App\Services\Plugin;
use App\Services\PluginManager;
2019-09-07 17:18:58 +08:00
use Illuminate\Cache\Repository;
use Illuminate\Filesystem\Filesystem;
class JavaScript
{
/** @var Filesystem */
protected $filesystem;
/** @var Repository */
protected $cache;
2020-06-23 18:17:16 +08:00
/** @var PluginManager */
protected $plugins;
2019-09-07 17:18:58 +08:00
protected $prefix = 'front-end-trans-';
2020-06-23 18:17:16 +08:00
public function __construct(
Filesystem $filesystem,
Repository $cache,
PluginManager $plugins
) {
2019-09-07 17:18:58 +08:00
$this->filesystem = $filesystem;
$this->cache = $cache;
2020-06-23 18:17:16 +08:00
$this->plugins = $plugins;
2019-09-07 17:18:58 +08:00
}
public function generate(string $locale): string
{
2020-06-23 18:17:16 +08:00
$plugins = $this->plugins->getEnabledPlugins();
$sourceFiles = $plugins
->map(function (Plugin $plugin) use ($locale) {
return $plugin->getPath()."/lang/$locale/front-end.yml";
})
->filter(function ($path) {
return $this->filesystem->exists($path);
});
$sourceFiles->push(resource_path("lang/$locale/front-end.yml"));
$sourceModified = $sourceFiles->max(function ($path) {
return $this->filesystem->lastModified($path);
});
2019-09-07 17:18:58 +08:00
$compiled = public_path("lang/$locale.js");
2020-06-23 18:17:16 +08:00
$compiledModified = (int) $this->cache->get($this->prefix.$locale, 0);
2019-09-07 17:18:58 +08:00
2019-12-14 11:10:37 +08:00
if ($sourceModified > $compiledModified || !$this->filesystem->exists($compiled)) {
2020-06-23 18:17:16 +08:00
$translations = trans('front-end');
foreach ($plugins as $plugin) {
$translations = array_merge(
$translations,
[$plugin->name => trans($plugin->namespace.'::front-end')]
);
}
$content = 'blessing.i18n = '.json_encode($translations, JSON_UNESCAPED_UNICODE);
2019-09-07 17:18:58 +08:00
$this->filesystem->put($compiled, $content);
$this->cache->put($this->prefix.$locale, $sourceModified);
2020-03-26 11:20:12 +08:00
return url()->asset("lang/$locale.js?t=$sourceModified");
2019-09-07 17:18:58 +08:00
}
2020-03-26 11:20:12 +08:00
return url()->asset("lang/$locale.js?t=$compiledModified");
2019-09-07 17:18:58 +08:00
}
2019-09-08 18:57:19 +08:00
public function resetTime(string $locale): void
{
$this->cache->put($this->prefix.$locale, 0);
}
2019-09-07 17:18:58 +08:00
}