RedisCacheFake.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Services;
  3. /**
  4. * RedisCache 的内存实现,供测试使用(相当于 Laravel Cache 的 array store)。
  5. *
  6. * 只替换存取原语,序列化、TTL 换算、null 语义仍走 RedisCache 本身,
  7. * 所以测试覆盖到的是真实逻辑。二进制的 length / range 两个原语也在这里覆盖。通过 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. protected function length(string $key): ?int
  50. {
  51. $value = $this->read($key);
  52. return $value === null ? null : strlen($value);
  53. }
  54. protected function range(string $key, int $start, int $end): string
  55. {
  56. $value = $this->read($key) ?? '';
  57. if ($start >= strlen($value) || $end < $start) {
  58. return '';
  59. }
  60. return substr($value, $start, $end - $start + 1);
  61. }
  62. }