src/Domains/Word/Infrastructure/Repository/WordCacheRepository.php line 37

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Domains\Word\Infrastructure\Repository;
  4. use App\Domains\Shared\RedisCache\CacheService;
  5. final class WordCacheRepository
  6. {
  7.     private const CACHE_KEY 'wordTranslation';
  8.     private const CACHE_TIMEOUT 3600;
  9.     public function __construct(
  10.         private readonly CacheService $cacheService,
  11.     ) {
  12.     }
  13.     public function cacheWord(
  14.         array $wordArray,
  15.         int $userId,
  16.         int $ttl self::CACHE_TIMEOUT,
  17.     ): void {
  18.         $key $this->generateKey($wordArray$userId);
  19.         $this->cacheService->set($key$wordArray$ttl);
  20.     }
  21.     public function getWord(
  22.         string $wordText,
  23.         string $fromLang,
  24.         string $toLang,
  25.         int $userId,
  26.     ): array|null {
  27.         $key $this->generateKeyFromParams($wordText$fromLang$toLang$userId);
  28.         return $this->cacheService->get($key);
  29.     }
  30.     private function generateKey(array $wordArrayint $userId): string
  31.     {
  32.         return $this->generateKeyFromParams(
  33.             $wordArray['word'],
  34.             $wordArray['languageFrom'],
  35.             $wordArray['languageTo'],
  36.             $userId,
  37.         );
  38.     }
  39.     private function generateKeyFromParams(
  40.         string $word,
  41.         string $from,
  42.         string $to,
  43.         int $userId,
  44.     ): string {
  45.         return sprintf(
  46.             '%s:%s:%s:%s:%d',
  47.             self::CACHE_KEY,
  48.             $word,
  49.             $from,
  50.             $to,
  51.             $userId,
  52.         );
  53.     }
  54. }