FilesystemCommonTrait.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 $directory;
  20. private $tmp;
  21. private function init(string $namespace, ?string $directory)
  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. /**
  47. * {@inheritdoc}
  48. */
  49. protected function doClear(string $namespace)
  50. {
  51. $ok = true;
  52. foreach ($this->scanHashDir($this->directory) as $file) {
  53. if ('' !== $namespace && !str_starts_with($this->getFileKey($file), $namespace)) {
  54. continue;
  55. }
  56. $ok = ($this->doUnlink($file) || !file_exists($file)) && $ok;
  57. }
  58. return $ok;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. protected function doDelete(array $ids)
  64. {
  65. $ok = true;
  66. foreach ($ids as $id) {
  67. $file = $this->getFile($id);
  68. $ok = (!is_file($file) || $this->doUnlink($file) || !file_exists($file)) && $ok;
  69. }
  70. return $ok;
  71. }
  72. protected function doUnlink(string $file)
  73. {
  74. return @unlink($file);
  75. }
  76. private function write(string $file, string $data, ?int $expiresAt = null)
  77. {
  78. $unlink = false;
  79. set_error_handler(__CLASS__.'::throwError');
  80. try {
  81. if (null === $this->tmp) {
  82. $this->tmp = $this->directory.bin2hex(random_bytes(6));
  83. }
  84. try {
  85. $h = fopen($this->tmp, 'x');
  86. } catch (\ErrorException $e) {
  87. if (!str_contains($e->getMessage(), 'File exists')) {
  88. throw $e;
  89. }
  90. $this->tmp = $this->directory.bin2hex(random_bytes(6));
  91. $h = fopen($this->tmp, 'x');
  92. }
  93. fwrite($h, $data);
  94. fclose($h);
  95. $unlink = true;
  96. if (null !== $expiresAt) {
  97. touch($this->tmp, $expiresAt ?: time() + 31556952); // 1 year in seconds
  98. }
  99. $success = rename($this->tmp, $file);
  100. $unlink = !$success;
  101. return $success;
  102. } finally {
  103. restore_error_handler();
  104. if ($unlink) {
  105. @unlink($this->tmp);
  106. }
  107. }
  108. }
  109. private function getFile(string $id, bool $mkdir = false, ?string $directory = null)
  110. {
  111. // Use MD5 to favor speed over security, which is not an issue here
  112. $hash = str_replace('/', '-', base64_encode(hash('md5', static::class.$id, true)));
  113. $dir = ($directory ?? $this->directory).strtoupper($hash[0].\DIRECTORY_SEPARATOR.$hash[1].\DIRECTORY_SEPARATOR);
  114. if ($mkdir && !is_dir($dir)) {
  115. @mkdir($dir, 0777, true);
  116. }
  117. return $dir.substr($hash, 2, 20);
  118. }
  119. private function getFileKey(string $file): string
  120. {
  121. return '';
  122. }
  123. private function scanHashDir(string $directory): \Generator
  124. {
  125. if (!is_dir($directory)) {
  126. return;
  127. }
  128. $chars = '+-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  129. for ($i = 0; $i < 38; ++$i) {
  130. if (!is_dir($directory.$chars[$i])) {
  131. continue;
  132. }
  133. for ($j = 0; $j < 38; ++$j) {
  134. if (!is_dir($dir = $directory.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
  135. continue;
  136. }
  137. foreach (@scandir($dir, \SCANDIR_SORT_NONE) ?: [] as $file) {
  138. if ('.' !== $file && '..' !== $file) {
  139. yield $dir.\DIRECTORY_SEPARATOR.$file;
  140. }
  141. }
  142. }
  143. }
  144. }
  145. /**
  146. * @internal
  147. */
  148. public static function throwError(int $type, string $message, string $file, int $line)
  149. {
  150. throw new \ErrorException($message, 0, $type, $file, $line);
  151. }
  152. /**
  153. * @return array
  154. */
  155. public function __sleep()
  156. {
  157. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  158. }
  159. public function __wakeup()
  160. {
  161. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  162. }
  163. public function __destruct()
  164. {
  165. if (method_exists(parent::class, '__destruct')) {
  166. parent::__destruct();
  167. }
  168. if (null !== $this->tmp && is_file($this->tmp)) {
  169. unlink($this->tmp);
  170. }
  171. }
  172. }