作者 邓超

翻译

... ... @@ -12,3 +12,4 @@ npm-debug.log
yarn-error.log
composer.lock
.idea
resources/lang/auto
... ...
<?php
namespace App\Console\Commands;
use App\Fun;
use Illuminate\Console\Command;
class Demo extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'demo';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
echo Fun::translate("hello' word",'de');
}
}
... ...
... ... @@ -145,21 +145,45 @@ class Fun {
* @author:dc
* @time 2022/11/16 17:43
*/
private function translate($texts, $tls){
if (is_string($texts)) {
$texts = [$texts];
public static function translate($texts, $tls){
static $langs = [];
if(!empty($langs[$texts])){
return $langs[$texts];
}
if (is_string($tls)) {
$tls = [$tls];
// 缓存的语言文件
$file = resource_path('lang/auto/'.$tls.'.php');
if(!is_file($file)){
@mkdir(dirname($file),0775,true);
file_put_contents($file,"<?php".PHP_EOL);
}
$data = [
'texts' => $texts,
require_once $file;
// 已翻译过的
$langs = $_lang??[];
if(!empty($langs[$texts])){
return $langs[$texts];
}
$response = Http::post('https://translate.hbb618.cn/translates', [
'texts' => [$texts],
'sl' => 'en',
'tls' => $tls,
];
$response = Http::post('https://translate.hbb618.cn/translates', $data);
'tls' => [$tls],
])->json();
$response = $response[0]['texts']??'';
$langs[$texts] = $response;
// 写入文件
file_put_contents($file,"\$_lang['".str_replace("'","\'",$texts)."'] = '".str_replace("'","\'",$response)."';".PHP_EOL,FILE_APPEND);
return $response->json();
return $response;
}
}
... ...