FilesystemCommonTrait.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Traits;
  11. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  12. /**
  13. * @author Nicolas Grekas <p@tchwork.com>
  14. *
  15. * @internal
  16. */
  17. trait FilesystemCommonTrait
  18. {
  19. private string $directory;
  20. private string $tmpSuffix;
  21. private function init(string $namespace, ?string $directory): void
  22. {
  23. if (!isset($directory[0])) {
  24. $directory = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'symfony-cache';
  25. } else {
  26. $directory = realpath($directory) ?: $directory;
  27. }
  28. if (isset($namespace[0])) {
  29. if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
  30. throw new InvalidArgumentException(\sprintf('Namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
  31. }
  32. $directory .= \DIRECTORY_SEPARATOR.$namespace;
  33. } else {
  34. $directory .= \DIRECTORY_SEPARATOR.'@';
  35. }
  36. if (!is_dir($directory)) {
  37. @mkdir($directory, 0777, true);
  38. }
  39. $directory .= \DIRECTORY_SEPARATOR;
  40. // On Windows the whole path is limited to 258 chars
  41. if ('\\' === \DIRECTORY_SEPARATOR && \strlen($directory) > 234) {
  42. throw new InvalidArgumentException(\sprintf('Cache directory too long (%s).', $directory));
  43. }
  44. $this->directory = $directory;
  45. }
  46. protected function doClear(string $namespace): bool
  47. {
  48. $ok = true;
  49. foreach ($this->scanHashDir($this->directory) as $file) {
  50. if ('' !== $namespace && !str_starts_with($this->getFileKey($file), $namespace)) {
  51. continue;
  52. }
  53. $ok = ($this->doUnlink($file) || !file_exists($file)) && $ok;
  54. }
  55. return $ok;
  56. }
  57. protected function doDelete(array $ids): bool
  58. {
  59. $ok = true;
  60. foreach ($ids as $id) {
  61. $file = $this->getFile($id);
  62. $ok = (!is_file($file) || $this->doUnlink($file) || !file_exists($file)) && $ok;
  63. }
  64. return $ok;
  65. }
  66. protected function doUnlink(string $file): bool
  67. {
  68. return @unlink($file);
  69. }
  70. private function write(string $file, string $data, ?int $expiresAt = null): bool
  71. {
  72. $unlink = false;
  73. set_error_handler(static fn ($type, $message, $file, $line) => throw new \ErrorException($message, 0, $type, $file, $line));
  74. try {
  75. $tmp = $this->directory.$this->tmpSuffix ??= str_replace('/', '-', base64_encode(random_bytes(6)));
  76. try {
  77. $h = fopen($tmp, 'x');
  78. } catch (\ErrorException $e) {
  79. if (!str_contains($e->getMessage(), 'File exists')) {
  80. throw $e;
  81. }
  82. $tmp = $this->directory.$this->tmpSuffix = str_replace('/', '-', base64_encode(random_bytes(6)));
  83. $h = fopen($tmp, 'x');
  84. }
  85. fwrite($h, $data);
  86. fclose($h);
  87. $unlink = true;
  88. if (null !== $expiresAt) {
  89. touch($tmp, $expiresAt ?: time() + 31556952); // 1 year in seconds
  90. }
  91. if ('\\' === \DIRECTORY_SEPARATOR) {
  92. $success = copy($tmp, $file);
  93. } else {
  94. $success = rename($tmp, $file);
  95. $unlink = !$success;
  96. }
  97. return $success;
  98. } finally {
  99. restore_error_handler();
  100. if ($unlink) {
  101. @unlink($tmp);
  102. }
  103. }
  104. }
  105. private function getFile(string $id, bool $mkdir = false, ?string $directory = null): string
  106. {
  107. // Use xxh128 to favor speed over security, which is not an issue here
  108. $hash = str_replace('/', '-', base64_encode(hash('xxh128', static::class.$id, true)));
  109. $dir = ($directory ?? $this->directory).strtoupper($hash[0].\DIRECTORY_SEPARATOR.$hash[1].\DIRECTORY_SEPARATOR);
  110. if ($mkdir && !is_dir($dir)) {
  111. @mkdir($dir, 0777, true);
  112. }
  113. return $dir.substr($hash, 2, 20);
  114. }
  115. private function getFileKey(string $file): string
  116. {
  117. return '';
  118. }
  119. private function scanHashDir(string $directory): \Generator
  120. {
  121. if (!is_dir($directory)) {
  122. return;
  123. }
  124. $chars = '+-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  125. for ($i = 0; $i < 38; ++$i) {
  126. if (!is_dir($directory.$chars[$i])) {
  127. continue;
  128. }
  129. for ($j = 0; $j < 38; ++$j) {
  130. if (!is_dir($dir = $directory.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
  131. continue;
  132. }
  133. foreach (@scandir($dir, \SCANDIR_SORT_NONE) ?: [] as $file) {
  134. if ('.' !== $file && '..' !== $file) {
  135. yield $dir.\DIRECTORY_SEPARATOR.$file;
  136. }
  137. }
  138. }
  139. }
  140. }
  141. public function __serialize(): array
  142. {
  143. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  144. }
  145. public function __unserialize(array $data): void
  146. {
  147. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  148. }
  149. public function __destruct()
  150. {
  151. if (method_exists(parent::class, '__destruct')) {
  152. parent::__destruct();
  153. }
  154. if (isset($this->tmpSuffix) && is_file($this->directory.$this->tmpSuffix)) {
  155. unlink($this->directory.$this->tmpSuffix);
  156. }
  157. }
  158. }