RedisCacheFake.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Services;
  3. /**
  4. * RedisCache 的内存实现,供测试使用(相当于 Laravel Cache 的 array store)。
  5. *
  6. * 只替换四个存取原语,序列化、TTL 换算、null 语义仍走 RedisCache 本身,
  7. * 所以测试覆盖到的是真实逻辑。通过 App\Facades\RedisCache::fake() 启用。
  8. */
  9. class RedisCacheFake extends RedisCache
  10. {
  11. /** @var array<string, array{value: string, expiresAt: int|null}> */
  12. protected array $items = [];
  13. protected function read(string $key): ?string
  14. {
  15. $item = $this->items[$key] ?? null;
  16. if ($item === null) {
  17. return null;
  18. }
  19. if ($item['expiresAt'] !== null && $item['expiresAt'] <= $this->currentTime()) {
  20. unset($this->items[$key]);
  21. return null;
  22. }
  23. return $item['value'];
  24. }
  25. protected function write(string $key, string $value, int $seconds): bool
  26. {
  27. $this->items[$key] = [
  28. 'value' => $value,
  29. 'expiresAt' => $this->currentTime() + $seconds,
  30. ];
  31. return true;
  32. }
  33. protected function delete(string $key): bool
  34. {
  35. $existed = $this->read($key) !== null;
  36. unset($this->items[$key]);
  37. return $existed;
  38. }
  39. protected function incrementBy(string $key, int $value): int
  40. {
  41. $current = $this->read($key);
  42. $next = (int) ($current ?? 0) + $value;
  43. $this->items[$key] = [
  44. 'value' => (string) $next,
  45. 'expiresAt' => $current === null ? null : $this->items[$key]['expiresAt'],
  46. ];
  47. return $next;
  48. }
  49. }