Cache.php 7.1 KB

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