123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- <?php
- namespace Grav\Common\File;
- use Exception;
- use Grav\Common\Utils;
- use RocketTheme\Toolbox\File\PhpFile;
- use RuntimeException;
- use Throwable;
- use function function_exists;
- use function get_class;
- trait CompiledFile
- {
-
- public function content($var = null)
- {
- try {
-
- if ($var === null && $this->raw === null && $this->content === null) {
- $key = md5($this->filename);
- $file = PhpFile::instance(CACHE_DIR . "compiled/files/{$key}{$this->extension}.php");
- $modified = $this->modified();
- if (!$modified) {
- try {
- return $this->decode($this->raw());
- } catch (Throwable $e) {
-
- }
- }
- $class = get_class($this);
- $cache = $file->exists() ? $file->content() : null;
-
- if (!isset($cache['@class'])
- || $cache['@class'] !== $class
- || $cache['modified'] !== $modified
- || $cache['filename'] !== $this->filename
- ) {
-
- try {
- $file->lock(false);
- } catch (Exception $e) {
-
- }
-
- $data = (array)$this->decode($this->raw());
- $cache = [
- '@class' => $class,
- 'filename' => $this->filename,
- 'modified' => $modified,
- 'data' => $data
- ];
-
- if ($file->locked() !== false) {
- $file->save($cache);
- $file->unlock();
-
- if (function_exists('opcache_invalidate')) {
-
- @opcache_invalidate($file->filename(), true);
- }
- }
- }
- $file->free();
- $this->content = $cache['data'];
- }
- } catch (Exception $e) {
- throw new RuntimeException(sprintf('Failed to read %s: %s', Utils::basename($this->filename), $e->getMessage()), 500, $e);
- }
- return parent::content($var);
- }
-
- public function __sleep()
- {
- return [
- 'filename',
- 'extension',
- 'raw',
- 'content',
- 'settings'
- ];
- }
-
- public function __wakeup()
- {
- if (!isset(static::$instances[$this->filename])) {
- static::$instances[$this->filename] = $this;
- }
- }
- }
|