Cache.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Composer\IO\IOInterface;
  13. use Composer\Util\Filesystem;
  14. use Symfony\Component\Finder\Finder;
  15. /**
  16. * Reads/writes to a filesystem cache
  17. *
  18. * @author Jordi Boggiano <j.boggiano@seld.be>
  19. */
  20. class Cache
  21. {
  22. private static $cacheCollected = false;
  23. private $io;
  24. private $root;
  25. private $enabled = true;
  26. private $whitelist;
  27. private $filesystem;
  28. /**
  29. * @param IOInterface $io
  30. * @param string $cacheDir location of the cache
  31. * @param string $whitelist List of characters that are allowed in path names (used in a regex character class)
  32. * @param Filesystem $filesystem optional filesystem instance
  33. */
  34. public function __construct(IOInterface $io, $cacheDir, $whitelist = 'a-z0-9.', Filesystem $filesystem = null)
  35. {
  36. $this->io = $io;
  37. $this->root = rtrim($cacheDir, '/\\') . '/';
  38. $this->whitelist = $whitelist;
  39. $this->filesystem = $filesystem ?: new Filesystem();
  40. if (
  41. (!is_dir($this->root) && !@mkdir($this->root, 0777, true))
  42. || !is_writable($this->root)
  43. ) {
  44. $this->io->writeError('<warning>Cannot create cache directory ' . $this->root . ', or directory is not writable. Proceeding without cache</warning>');
  45. $this->enabled = false;
  46. }
  47. }
  48. public function isEnabled()
  49. {
  50. return $this->enabled;
  51. }
  52. public function getRoot()
  53. {
  54. return $this->root;
  55. }
  56. public function read($file)
  57. {
  58. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  59. if ($this->enabled && file_exists($this->root . $file)) {
  60. if ($this->io->isDebug()) {
  61. $this->io->writeError('Reading '.$this->root . $file.' from cache');
  62. }
  63. return file_get_contents($this->root . $file);
  64. }
  65. return false;
  66. }
  67. public function write($file, $contents)
  68. {
  69. if ($this->enabled) {
  70. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  71. if ($this->io->isDebug()) {
  72. $this->io->writeError('Writing '.$this->root . $file.' into cache');
  73. }
  74. try {
  75. return file_put_contents($this->root . $file, $contents);
  76. } catch (\ErrorException $e) {
  77. if ($this->io->isDebug()) {
  78. $this->io->writeError('<warning>Failed to write into cache: '.$e->getMessage().'</warning>');
  79. }
  80. if (preg_match('{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}', $e->getMessage(), $m)) {
  81. // Remove partial file.
  82. unlink($this->root . $file);
  83. $message = sprintf(
  84. '<warning>Writing %1$s into cache failed after %2$u of %3$u bytes written, only %4$u bytes of free space available</warning>',
  85. $this->root . $file,
  86. $m[1],
  87. $m[2],
  88. @disk_free_space($this->root . dirname($file))
  89. );
  90. $this->io->writeError($message);
  91. return false;
  92. }
  93. throw $e;
  94. }
  95. }
  96. return false;
  97. }
  98. /**
  99. * Copy a file into the cache
  100. */
  101. public function copyFrom($file, $source)
  102. {
  103. if ($this->enabled) {
  104. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  105. $this->filesystem->ensureDirectoryExists(dirname($this->root . $file));
  106. if (!file_exists($source)) {
  107. $this->io->writeError('<error>'.$source.' does not exist, can not write into cache</error>');
  108. } elseif ($this->io->isDebug()) {
  109. $this->io->writeError('Writing '.$this->root . $file.' into cache from '.$source);
  110. }
  111. return copy($source, $this->root . $file);
  112. }
  113. return false;
  114. }
  115. /**
  116. * Copy a file out of the cache
  117. */
  118. public function copyTo($file, $target)
  119. {
  120. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  121. if ($this->enabled && file_exists($this->root . $file)) {
  122. try {
  123. touch($this->root . $file, filemtime($this->root . $file), time());
  124. } catch (\ErrorException $e) {
  125. // fallback in case the above failed due to incorrect ownership
  126. // see https://github.com/composer/composer/issues/4070
  127. touch($this->root . $file);
  128. }
  129. if ($this->io->isDebug()) {
  130. $this->io->writeError('Reading '.$this->root . $file.' from cache');
  131. }
  132. return copy($this->root . $file, $target);
  133. }
  134. return false;
  135. }
  136. public function gcIsNecessary()
  137. {
  138. return (!self::$cacheCollected && !mt_rand(0, 50));
  139. }
  140. public function remove($file)
  141. {
  142. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  143. if ($this->enabled && file_exists($this->root . $file)) {
  144. return $this->filesystem->unlink($this->root . $file);
  145. }
  146. return false;
  147. }
  148. public function gc($ttl, $maxSize)
  149. {
  150. if ($this->enabled) {
  151. $expire = new \DateTime();
  152. $expire->modify('-'.$ttl.' seconds');
  153. $finder = $this->getFinder()->date('until '.$expire->format('Y-m-d H:i:s'));
  154. foreach ($finder as $file) {
  155. $this->filesystem->unlink($file->getPathname());
  156. }
  157. $totalSize = $this->filesystem->size($this->root);
  158. if ($totalSize > $maxSize) {
  159. $iterator = $this->getFinder()->sortByAccessedTime()->getIterator();
  160. while ($totalSize > $maxSize && $iterator->valid()) {
  161. $filepath = $iterator->current()->getPathname();
  162. $totalSize -= $this->filesystem->size($filepath);
  163. $this->filesystem->unlink($filepath);
  164. $iterator->next();
  165. }
  166. }
  167. self::$cacheCollected = true;
  168. return true;
  169. }
  170. return false;
  171. }
  172. public function sha1($file)
  173. {
  174. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  175. if ($this->enabled && file_exists($this->root . $file)) {
  176. return sha1_file($this->root . $file);
  177. }
  178. return false;
  179. }
  180. public function sha256($file)
  181. {
  182. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  183. if ($this->enabled && file_exists($this->root . $file)) {
  184. return hash_file('sha256', $this->root . $file);
  185. }
  186. return false;
  187. }
  188. protected function getFinder()
  189. {
  190. return Finder::create()->in($this->root)->files();
  191. }
  192. }