translate-laravel/src/Jobs/RunTranslate.php

62 lines
2.2 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\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Str;
use KorElf\TranslateLaravel\DTO\AfterTranslateDto;
use KorElf\TranslateLaravel\DTO\ProcessTranslateDto;
use korElf\TranslateLaravel\DTO\RunTranslateDto;
use KorElf\TranslateLaravel\DTO\Translated;
use KorElf\TranslateLaravel\Translate\SplitTextIntoPartsCommand;
final class RunTranslate implements ShouldQueue, ShouldBeEncrypted
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
private readonly RunTranslateDto $runTranslateDto,
private readonly AfterTranslateDto $afterTranslateDto,
) { }
/**
* Execute the job.
*/
public function handle(SplitTextIntoPartsCommand $splitTextIntoPartsCommand): void
{
$chains = [];
$groupName = 'KorElf\TranslateLaravel\Jobs-' . Str::uuid()->toString();
$translated = new Translated();
foreach ($this->runTranslateDto->getParams() as $key => $param) {
/* @var \KorElf\TranslateLaravel\DTO\Parameter $param */
$texts = $splitTextIntoPartsCommand->execute($param->getText(), $param->getTextType(), $param->getDriver());
foreach ($texts as $part => $partText) {
$processTranslateDto = new ProcessTranslateDto(
$groupName,
$key,
$part,
$partText,
$param->getTextType(),
$param->getTargetLanguageCode(),
$param->getSourceLanguageCode(),
$param->getDriver(),
);
$chains[] = new ProcessTranslate($processTranslateDto);
}
$translated->add($key, count($texts));
}
$chains[] = new AfterTranslate($groupName, $translated, $this->afterTranslateDto);
Bus::chain($chains)->dispatch();
}
}