Add DTOs, exceptions, and jobs for translation service.
Introduced new Data Transfer Objects (DTOs), exceptions, and jobs to enhance the translation service functionality. Updated namespaces for consistency and added rate limiting to the translation provider. Expanded the README with detailed usage instructions.
This commit is contained in:
53
src/Jobs/AfterTranslate.php
Normal file
53
src/Jobs/AfterTranslate.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?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\Support\Facades\Cache;
|
||||
use KorElf\TranslateLaravel\Contracts\TranslationCompletedListener;
|
||||
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 TranslationCompletedListener $listener,
|
||||
private readonly Translated $translated,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*/
|
||||
public function handle(): 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)) {
|
||||
throw new AfterTranslateException('Part or all of the text has not been translated. Keys: ' . implode(', ', $errors));
|
||||
}
|
||||
Cache::forget($this->groupName);
|
||||
|
||||
$this->listener->onTranslationCompleted($translated);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user