選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

112 行
2.3KB

  1. <?php
  2. namespace Framework\Cache\Driver;
  3. use Framework\App;
  4. class FileDriver implements Driver
  5. {
  6. private array $config = [];
  7. private array $cached = [];
  8. public function __construct(array $config)
  9. {
  10. $this->config = $config;
  11. }
  12. public function has(string $key): bool
  13. {
  14. $data = $this->cached[$key] = $this->read($key);
  15. return isset($data['expires']) and $data['expires'] > time();
  16. }
  17. private function path(string $key): string
  18. {
  19. $base = $this->base();
  20. $separator = DIRECTORY_SEPARATOR;
  21. $key = sha1($key);
  22. return "{$base}{$separator}{$key}.json";
  23. }
  24. private function base(): string
  25. {
  26. $base = App::getInstance()->resolve('paths.base');
  27. $separator = DIRECTORY_SEPARATOR;
  28. return "{$base}{$separator}storage{$separator}framework{$separator}cache";
  29. }
  30. private function read(string $key)
  31. {
  32. $path = $this->path($key);
  33. if (!is_file($path)) {
  34. return [];
  35. }
  36. return json_decode(file_get_contents($path), true);
  37. }
  38. public function get(string $key, mixed $default = null): mixed
  39. {
  40. if ($this->has($key)) {
  41. return $this->cached[$key]['value'];
  42. }
  43. return $default;
  44. }
  45. public function put(string $key, mixed $value, int $seconds = null): static
  46. {
  47. if (!is_int($seconds)) {
  48. $seconds = (int) $this->config['seconds'];
  49. }
  50. $data = $this->cached[$key] = [
  51. 'value' => $value,
  52. 'expires' => time() + $seconds,
  53. ];
  54. return $this->write($key, $data);
  55. }
  56. private function write(string $key, mixed $value): static
  57. {
  58. file_put_contents($this->path($key), json_encode($value));
  59. return $this;
  60. }
  61. public function forget(string $key): static
  62. {
  63. unset($this->cached[$key]);
  64. $path = $this->path($key);
  65. if (is_file($path)) {
  66. unlink($path);
  67. }
  68. return $this;
  69. }
  70. public function flush(): static
  71. {
  72. $this->cached = [];
  73. $base = $this->base();
  74. $separator = DIRECTORY_SEPARATOR;
  75. $files = glob("{$base}{$separator}*.json");
  76. foreach ($files as $file){
  77. if (is_file($file)) {
  78. unlink($file);
  79. }
  80. }
  81. return $this;
  82. }
  83. }

Powered by TurnKey Linux.