Filesystem.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2015 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Implements a cache on the filesystem.
  12. *
  13. * @author Andrew Tch <andrew@noop.lv>
  14. */
  15. class Twig_Cache_Filesystem implements Twig_CacheInterface
  16. {
  17. const FORCE_BYTECODE_INVALIDATION = 1;
  18. private $directory;
  19. private $options;
  20. /**
  21. * @param $directory string The root cache directory
  22. * @param $options int A set of options
  23. */
  24. public function __construct($directory, $options = 0)
  25. {
  26. $this->directory = rtrim($directory, '\/').'/';
  27. $this->options = $options;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function generateKey($name, $className)
  33. {
  34. $hash = hash('sha256', $className);
  35. return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php';
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function load($key)
  41. {
  42. @include_once $key;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function write($key, $content)
  48. {
  49. $dir = dirname($key);
  50. if (!is_dir($dir)) {
  51. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  52. throw new RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir));
  53. }
  54. } elseif (!is_writable($dir)) {
  55. throw new RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir));
  56. }
  57. $tmpFile = tempnam($dir, basename($key));
  58. if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) {
  59. @chmod($key, 0666 & ~umask());
  60. if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) {
  61. // Compile cached file into bytecode cache
  62. if (function_exists('opcache_invalidate')) {
  63. opcache_invalidate($key, true);
  64. } elseif (function_exists('apc_compile_file')) {
  65. apc_compile_file($key);
  66. }
  67. }
  68. return;
  69. }
  70. throw new RuntimeException(sprintf('Failed to write cache file "%s".', $key));
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function getTimestamp($key)
  76. {
  77. if (!file_exists($key)) {
  78. return 0;
  79. }
  80. return (int) @filemtime($key);
  81. }
  82. }