FilesystemCache.php 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of the Assetic package, an OpenSky project.
  4. *
  5. * (c) 2010-2011 OpenSky Project Inc
  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 Assetic\Cache;
  11. /**
  12. * A simple filesystem cache.
  13. *
  14. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  15. */
  16. class FilesystemCache implements CacheInterface
  17. {
  18. private $dir;
  19. public function __construct($dir)
  20. {
  21. $this->dir = $dir;
  22. }
  23. public function has($key)
  24. {
  25. return file_exists($this->dir.'/'.$key);
  26. }
  27. public function get($key)
  28. {
  29. $path = $this->dir.'/'.$key;
  30. if (!file_exists($path)) {
  31. throw new \RuntimeException('There is no cached value for '.$key);
  32. }
  33. return file_get_contents($path);
  34. }
  35. public function set($key, $value)
  36. {
  37. if (!is_dir($this->dir) && false === @mkdir($this->dir, 0777, true)) {
  38. throw new \RuntimeException('Unable to create directory '.$this->dir);
  39. }
  40. $path = $this->dir.'/'.$key;
  41. if (false === @file_put_contents($path, $value)) {
  42. throw new \RuntimeException('Unable to write file '.$path);
  43. }
  44. }
  45. public function remove($key)
  46. {
  47. $path = $this->dir.'/'.$key;
  48. if (file_exists($path) && false === @unlink($path)) {
  49. throw new \RuntimeException('Unable to remove file '.$path);
  50. }
  51. }
  52. }