Cache.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. /**
  14. * Reads/writes to a filesystem cache
  15. *
  16. * @author Jordi Boggiano <j.boggiano@seld.be>
  17. */
  18. class Cache
  19. {
  20. private $io;
  21. private $root;
  22. private $enabled = true;
  23. public function __construct(IOInterface $io, $cacheDir)
  24. {
  25. $this->io = $io;
  26. $this->root = rtrim($cacheDir, '/\\') . '/';
  27. if (!is_dir($this->root)) {
  28. if (!@mkdir($this->root, 0777, true)) {
  29. $this->enabled = false;
  30. }
  31. }
  32. }
  33. public function getRoot()
  34. {
  35. return $this->root;
  36. }
  37. public function read($file)
  38. {
  39. $file = preg_replace('{[^a-z0-9.]}i', '-', $file);
  40. if ($this->enabled && file_exists($this->root . $file)) {
  41. return file_get_contents($this->root . $file);
  42. }
  43. }
  44. public function write($file, $contents)
  45. {
  46. if ($this->enabled) {
  47. $file = preg_replace('{[^a-z0-9.]}i', '-', $file);
  48. file_put_contents($this->root . $file, $contents);
  49. }
  50. }
  51. public function sha1($file)
  52. {
  53. $file = preg_replace('{[^a-z0-9.]}i', '-', $file);
  54. if ($this->enabled && file_exists($this->root . $file)) {
  55. return sha1_file($this->root . $file);
  56. }
  57. }
  58. public function sha256($file)
  59. {
  60. $file = preg_replace('{[^a-z0-9.]}i', '-', $file);
  61. if ($this->enabled && file_exists($this->root . $file)) {
  62. return hash_file('sha256', $this->root . $file);
  63. }
  64. }
  65. }