55 lines
2.0 KiB
PHP
55 lines
2.0 KiB
PHP
<?php declare(strict_types=1);
|
|
|
|
namespace KorElf\TranslateLaravel\Jobs;
|
|
|
|
use Illuminate\Bus\Queueable;
|
|
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Application;
|
|
use Illuminate\Foundation\Bus\Dispatchable;
|
|
use Illuminate\Queue\InteractsWithQueue;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use KorElf\TranslateLaravel\DTO\AfterTranslateDto;
|
|
use KorElf\TranslateLaravel\DTO\Translated;
|
|
use KorElf\TranslateLaravel\Exceptions\AfterTranslateException;
|
|
|
|
final class AfterTranslate implements ShouldQueue, ShouldBeEncrypted
|
|
{
|
|
use Dispatchable, InteractsWithQueue, Queueable;
|
|
|
|
/**
|
|
* Create a new job instance.
|
|
*/
|
|
public function __construct(
|
|
private readonly string $groupName,
|
|
private readonly Translated $translated,
|
|
private readonly AfterTranslateDto $afterTranslateDto
|
|
) { }
|
|
|
|
public function handle(Application $application): void
|
|
{
|
|
$translated = [];
|
|
$data = Cache::get($this->groupName, []);
|
|
|
|
$errors = [];
|
|
foreach ($this->translated->toArray() as $key => $parts) {
|
|
if (!isset($data[$key]) || count($data[$key]) !== $parts) {
|
|
$errors[] = $key;
|
|
continue;
|
|
}
|
|
|
|
$translated[$key] = implode(' ', $data[$key]);
|
|
}
|
|
|
|
if (empty($data) || !empty($errors)) {
|
|
throw new AfterTranslateException('Part or all of the text has not been translated. Keys: ' . implode(', ', $errors));
|
|
}
|
|
$objectAfterTranslate = $application->make($this->afterTranslateDto->getClassName());
|
|
if (!$objectAfterTranslate instanceof \KorElf\TranslateLaravel\Contracts\TranslationCompletedListener) {
|
|
throw new AfterTranslateException('The class must implement the \KorElf\TranslateLaravel\Contracts\TranslationCompletedListener interface.');
|
|
}
|
|
$objectAfterTranslate->onTranslationCompleted($translated, $this->afterTranslateDto->getData());
|
|
|
|
Cache::forget($this->groupName);
|
|
}
|
|
} |