CompiledFile.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Grav\Common\File;
  3. use RocketTheme\Toolbox\File\PhpFile;
  4. /**
  5. * Class CompiledFile
  6. * @package Grav\Common\File
  7. *
  8. * @property string $filename
  9. * @property string $extension
  10. * @property string $raw
  11. * @property array|string $content
  12. */
  13. trait CompiledFile
  14. {
  15. /**
  16. * Get/set parsed file contents.
  17. *
  18. * @param mixed $var
  19. * @return string
  20. */
  21. public function content($var = null)
  22. {
  23. // Set some options
  24. $this->settings(['native' => true, 'compat' => true]);
  25. // If nothing has been loaded, attempt to get pre-compiled version of the file first.
  26. if ($var === null && $this->raw === null && $this->content === null) {
  27. $key = md5($this->filename);
  28. $file = PhpFile::instance(CACHE_DIR . "compiled/files/{$key}{$this->extension}.php");
  29. $modified = $this->modified();
  30. if (!$modified) {
  31. return $this->decode($this->raw());
  32. }
  33. $class = get_class($this);
  34. $cache = $file->exists() ? $file->content() : null;
  35. // Load real file if cache isn't up to date (or is invalid).
  36. if (
  37. !isset($cache['@class'])
  38. || $cache['@class'] != $class
  39. || $cache['modified'] != $modified
  40. || $cache['filename'] != $this->filename
  41. ) {
  42. // Attempt to lock the file for writing.
  43. $file->lock(false);
  44. // Decode RAW file into compiled array.
  45. $data = (array) $this->decode($this->raw());
  46. $cache = [
  47. '@class' => $class,
  48. 'filename' => $this->filename,
  49. 'modified' => $modified,
  50. 'data' => $data
  51. ];
  52. // If compiled file wasn't already locked by another process, save it.
  53. if ($file->locked() !== false) {
  54. $file->save($cache);
  55. $file->unlock();
  56. }
  57. }
  58. $this->content = $cache['data'];
  59. }
  60. return parent::content($var);
  61. }
  62. }