<?php
declare(strict_types=1);
namespace App\Domains\Word\Infrastructure\Repository;
use App\Domains\Shared\RedisCache\CacheService;
final class WordCacheRepository
{
private const CACHE_KEY = 'wordTranslation';
private const CACHE_TIMEOUT = 3600;
public function __construct(
private readonly CacheService $cacheService,
) {
}
public function cacheWord(
array $wordArray,
int $userId,
int $ttl = self::CACHE_TIMEOUT,
): void {
$key = $this->generateKey($wordArray, $userId);
$this->cacheService->set($key, $wordArray, $ttl);
}
public function getWord(
string $wordText,
string $fromLang,
string $toLang,
int $userId,
): array|null {
$key = $this->generateKeyFromParams($wordText, $fromLang, $toLang, $userId);
return $this->cacheService->get($key);
}
private function generateKey(array $wordArray, int $userId): string
{
return $this->generateKeyFromParams(
$wordArray['word'],
$wordArray['languageFrom'],
$wordArray['languageTo'],
$userId,
);
}
private function generateKeyFromParams(
string $word,
string $from,
string $to,
int $userId,
): string {
return sprintf(
'%s:%s:%s:%s:%d',
self::CACHE_KEY,
$word,
$from,
$to,
$userId,
);
}
}