vendor/symfony/cache/Adapter/PhpFilesAdapter.php line 243

  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Cache\Adapter;
  11. use Symfony\Component\Cache\Exception\CacheException;
  12. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. use Symfony\Component\Cache\PruneableInterface;
  14. use Symfony\Component\Cache\Traits\FilesystemCommonTrait;
  15. use Symfony\Component\VarExporter\VarExporter;
  16. /**
  17.  * @author Piotr Stankowski <git@trakos.pl>
  18.  * @author Nicolas Grekas <p@tchwork.com>
  19.  * @author Rob Frawley 2nd <rmf@src.run>
  20.  */
  21. class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
  22. {
  23.     use FilesystemCommonTrait {
  24.         doClear as private doCommonClear;
  25.         doDelete as private doCommonDelete;
  26.     }
  27.     private \Closure $includeHandler;
  28.     private bool $appendOnly;
  29.     private array $values = [];
  30.     private array $files = [];
  31.     private static int $startTime;
  32.     private static array $valuesCache = [];
  33.     /**
  34.      * @param $appendOnly Set to `true` to gain extra performance when the items stored in this pool never expire.
  35.      *                    Doing so is encouraged because it fits perfectly OPcache's memory model.
  36.      *
  37.      * @throws CacheException if OPcache is not enabled
  38.      */
  39.     public function __construct(string $namespace ''int $defaultLifetime 0string $directory nullbool $appendOnly false)
  40.     {
  41.         $this->appendOnly $appendOnly;
  42.         self::$startTime ??= $_SERVER['REQUEST_TIME'] ?? time();
  43.         parent::__construct(''$defaultLifetime);
  44.         $this->init($namespace$directory);
  45.         $this->includeHandler = static function ($type$msg$file$line) {
  46.             throw new \ErrorException($msg0$type$file$line);
  47.         };
  48.     }
  49.     public static function isSupported()
  50.     {
  51.         self::$startTime ??= $_SERVER['REQUEST_TIME'] ?? time();
  52.         return \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOL) && (!\in_array(\PHP_SAPI, ['cli''phpdbg'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOL));
  53.     }
  54.     public function prune(): bool
  55.     {
  56.         $time time();
  57.         $pruned true;
  58.         $getExpiry true;
  59.         set_error_handler($this->includeHandler);
  60.         try {
  61.             foreach ($this->scanHashDir($this->directory) as $file) {
  62.                 try {
  63.                     if (\is_array($expiresAt = include $file)) {
  64.                         $expiresAt $expiresAt[0];
  65.                     }
  66.                 } catch (\ErrorException $e) {
  67.                     $expiresAt $time;
  68.                 }
  69.                 if ($time >= $expiresAt) {
  70.                     $pruned $this->doUnlink($file) && !file_exists($file) && $pruned;
  71.                 }
  72.             }
  73.         } finally {
  74.             restore_error_handler();
  75.         }
  76.         return $pruned;
  77.     }
  78.     protected function doFetch(array $ids): iterable
  79.     {
  80.         if ($this->appendOnly) {
  81.             $now 0;
  82.             $missingIds = [];
  83.         } else {
  84.             $now time();
  85.             $missingIds $ids;
  86.             $ids = [];
  87.         }
  88.         $values = [];
  89.         begin:
  90.         $getExpiry false;
  91.         foreach ($ids as $id) {
  92.             if (null === $value $this->values[$id] ?? null) {
  93.                 $missingIds[] = $id;
  94.             } elseif ('N;' === $value) {
  95.                 $values[$id] = null;
  96.             } elseif (!\is_object($value)) {
  97.                 $values[$id] = $value;
  98.             } elseif (!$value instanceof LazyValue) {
  99.                 $values[$id] = $value();
  100.             } elseif (false === $values[$id] = include $value->file) {
  101.                 unset($values[$id], $this->values[$id]);
  102.                 $missingIds[] = $id;
  103.             }
  104.             if (!$this->appendOnly) {
  105.                 unset($this->values[$id]);
  106.             }
  107.         }
  108.         if (!$missingIds) {
  109.             return $values;
  110.         }
  111.         set_error_handler($this->includeHandler);
  112.         try {
  113.             $getExpiry true;
  114.             foreach ($missingIds as $k => $id) {
  115.                 try {
  116.                     $file $this->files[$id] ??= $this->getFile($id);
  117.                     if (isset(self::$valuesCache[$file])) {
  118.                         [$expiresAt$this->values[$id]] = self::$valuesCache[$file];
  119.                     } elseif (\is_array($expiresAt = include $file)) {
  120.                         if ($this->appendOnly) {
  121.                             self::$valuesCache[$file] = $expiresAt;
  122.                         }
  123.                         [$expiresAt$this->values[$id]] = $expiresAt;
  124.                     } elseif ($now $expiresAt) {
  125.                         $this->values[$id] = new LazyValue($file);
  126.                     }
  127.                     if ($now >= $expiresAt) {
  128.                         unset($this->values[$id], $missingIds[$k], self::$valuesCache[$file]);
  129.                     }
  130.                 } catch (\ErrorException $e) {
  131.                     unset($missingIds[$k]);
  132.                 }
  133.             }
  134.         } finally {
  135.             restore_error_handler();
  136.         }
  137.         $ids $missingIds;
  138.         $missingIds = [];
  139.         goto begin;
  140.     }
  141.     protected function doHave(string $id): bool
  142.     {
  143.         if ($this->appendOnly && isset($this->values[$id])) {
  144.             return true;
  145.         }
  146.         set_error_handler($this->includeHandler);
  147.         try {
  148.             $file $this->files[$id] ??= $this->getFile($id);
  149.             $getExpiry true;
  150.             if (isset(self::$valuesCache[$file])) {
  151.                 [$expiresAt$value] = self::$valuesCache[$file];
  152.             } elseif (\is_array($expiresAt = include $file)) {
  153.                 if ($this->appendOnly) {
  154.                     self::$valuesCache[$file] = $expiresAt;
  155.                 }
  156.                 [$expiresAt$value] = $expiresAt;
  157.             } elseif ($this->appendOnly) {
  158.                 $value = new LazyValue($file);
  159.             }
  160.         } catch (\ErrorException) {
  161.             return false;
  162.         } finally {
  163.             restore_error_handler();
  164.         }
  165.         if ($this->appendOnly) {
  166.             $now 0;
  167.             $this->values[$id] = $value;
  168.         } else {
  169.             $now time();
  170.         }
  171.         return $now $expiresAt;
  172.     }
  173.     protected function doSave(array $valuesint $lifetime): array|bool
  174.     {
  175.         $ok true;
  176.         $expiry $lifetime time() + $lifetime 'PHP_INT_MAX';
  177.         $allowCompile self::isSupported();
  178.         foreach ($values as $key => $value) {
  179.             unset($this->values[$key]);
  180.             $isStaticValue true;
  181.             if (null === $value) {
  182.                 $value "'N;'";
  183.             } elseif (\is_object($value) || \is_array($value)) {
  184.                 try {
  185.                     $value VarExporter::export($value$isStaticValue);
  186.                 } catch (\Exception $e) {
  187.                     throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.'$keyget_debug_type($value)), 0$e);
  188.                 }
  189.             } elseif (\is_string($value)) {
  190.                 // Wrap "N;" in a closure to not confuse it with an encoded `null`
  191.                 if ('N;' === $value) {
  192.                     $isStaticValue false;
  193.                 }
  194.                 $value var_export($valuetrue);
  195.             } elseif (!\is_scalar($value)) {
  196.                 throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.'$keyget_debug_type($value)));
  197.             } else {
  198.                 $value var_export($valuetrue);
  199.             }
  200.             $encodedKey rawurlencode($key);
  201.             if ($isStaticValue) {
  202.                 $value "return [{$expiry}{$value}];";
  203.             } elseif ($this->appendOnly) {
  204.                 $value "return [{$expiry}, static function () { return {$value}; }];";
  205.             } else {
  206.                 // We cannot use a closure here because of https://bugs.php.net/76982
  207.                 $value str_replace('\Symfony\Component\VarExporter\Internal\\'''$value);
  208.                 $value "namespace Symfony\Component\VarExporter\Internal;\n\nreturn \$getExpiry ? {$expiry} : {$value};";
  209.             }
  210.             $file $this->files[$key] = $this->getFile($keytrue);
  211.             // Since OPcache only compiles files older than the script execution start, set the file's mtime in the past
  212.             $ok $this->write($file"<?php //{$encodedKey}\n\n{$value}\n"self::$startTime 10) && $ok;
  213.             if ($allowCompile) {
  214.                 @opcache_invalidate($filetrue);
  215.                 @opcache_compile_file($file);
  216.             }
  217.             unset(self::$valuesCache[$file]);
  218.         }
  219.         if (!$ok && !is_writable($this->directory)) {
  220.             throw new CacheException(sprintf('Cache directory is not writable (%s).'$this->directory));
  221.         }
  222.         return $ok;
  223.     }
  224.     protected function doClear(string $namespace): bool
  225.     {
  226.         $this->values = [];
  227.         return $this->doCommonClear($namespace);
  228.     }
  229.     protected function doDelete(array $ids): bool
  230.     {
  231.         foreach ($ids as $id) {
  232.             unset($this->values[$id]);
  233.         }
  234.         return $this->doCommonDelete($ids);
  235.     }
  236.     protected function doUnlink(string $file)
  237.     {
  238.         unset(self::$valuesCache[$file]);
  239.         if (self::isSupported()) {
  240.             @opcache_invalidate($filetrue);
  241.         }
  242.         return @unlink($file);
  243.     }
  244.     private function getFileKey(string $file): string
  245.     {
  246.         if (!$h = @fopen($file'r')) {
  247.             return '';
  248.         }
  249.         $encodedKey substr(fgets($h), 8);
  250.         fclose($h);
  251.         return rawurldecode(rtrim($encodedKey));
  252.     }
  253. }
  254. /**
  255.  * @internal
  256.  */
  257. class LazyValue
  258. {
  259.     public string $file;
  260.     public function __construct(string $file)
  261.     {
  262.         $this->file $file;
  263.     }
  264. }