This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php

326 lines
9.2 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Adapter;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ContractsTrait;
use Symfony\Component\Cache\Traits\PhpArrayTrait;
2018-08-01 09:02:13 +01:00
use Symfony\Contracts\Cache\CacheInterface;
/**
* Caches items at warm up time using a PHP array that is stored in shared memory by OPCache since PHP 7.0.
* Warmed up items are read-only and run-time discovered items are cached using a fallback adapter.
*
* @author Titouan Galopin <galopintitouan@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
*/
class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInterface, ResettableInterface
{
use PhpArrayTrait;
use ContractsTrait;
private $createCacheItem;
/**
* @param string $file The PHP file were values are cached
* @param AdapterInterface $fallbackPool A pool to fallback on when an item is not hit
*/
public function __construct(string $file, AdapterInterface $fallbackPool)
{
$this->file = $file;
$this->pool = $fallbackPool;
$this->createCacheItem = \Closure::bind(
function ($key, $value, $isHit) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
$item->isHit = $isHit;
return $item;
},
null,
CacheItem::class
);
}
/**
2017-05-22 08:27:42 +01:00
* This adapter takes advantage of how PHP stores arrays in its latest versions.
*
Fix @param in PHPDoc Errors reported by Sami API Doc generator on branch 3.2 ERROR: The "factory" @param tag variable name is wrong (should be "objectLoader") on "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader::__construct" in src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php:68 ERROR: The "objectLoader" @param tag variable name is wrong (should be "factory") on "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader::__construct" in src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php:68 ERROR: "7" @param tags are expected but only "6" found on "Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController::__construct" in src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php:50 ERROR: "3" @param tags are expected but only "2" found on "Symfony\Component\Asset\PathPackage::__construct" in src/Symfony/Component/Asset/PathPackage.php:35 ERROR: "2" @param tags are expected but only "1" found on "Symfony\Component\Cache\Adapter\PhpArrayAdapter::create" in src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php:64 ERROR: "3" @param tags are expected but only "1" found on "Symfony\Component\Cache\Adapter\RedisAdapter::__construct" in src/Symfony/Component/Cache/Adapter/RedisAdapter.php:39 ERROR: The "format" @param tag variable name is wrong (should be "fileLinkFormat") on "Symfony\Component\Debug\ExceptionHandler::setFileLinkFormat" in src/Symfony/Component/Debug/ExceptionHandler.php:90 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\Compiler\Compiler::addPass" in src/Symfony/Component/DependencyInjection/Compiler/Compiler.php:73 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\Compiler\PassConfig::addPass" in src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php:97 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\ContainerBuilder::addCompilerPass" in src/Symfony/Component/DependencyInjection/ContainerBuilder.php:311 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface::getProxyFactoryCode" in src/Symfony/Component/DependencyInjection/LazyProxy/PhpDumper/DumperInterface.php:41 ERROR: "0" @param tags are expected but only "1" found on "Symfony\Component\HttpFoundation\Request::isMethodSafe" in src/Symfony/Component/HttpFoundation/Request.php:1458 ERROR: "5" @param tags are expected but only "6" found on "Symfony\Component\Serializer\Normalizer\AbstractNormalizer::instantiateObject" in src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php:291
2017-03-28 22:38:21 +01:00
* @param string $file The PHP file were values are cached
2017-05-21 10:14:40 +01:00
* @param CacheItemPoolInterface $fallbackPool Fallback when opcache is disabled
*
* @return CacheItemPoolInterface
*/
public static function create($file, CacheItemPoolInterface $fallbackPool)
{
2017-06-17 17:01:46 +01:00
// Shared memory is available in PHP 7.0+ with OPCache enabled
if (filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN)) {
if (!$fallbackPool instanceof AdapterInterface) {
$fallbackPool = new ProxyAdapter($fallbackPool);
}
return new static($file, $fallbackPool);
}
return $fallbackPool;
}
/**
* {@inheritdoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
if (null === $this->values) {
$this->initialize();
}
if (!isset($this->keys[$key])) {
get_from_pool:
if ($this->pool instanceof CacheInterface) {
return $this->pool->get($key, $callback, $beta, $metadata);
}
return $this->doGet($this->pool, $key, $callback, $beta, $metadata);
}
$value = $this->values[$this->keys[$key]];
if ('N;' === $value) {
return null;
}
try {
if ($value instanceof \Closure) {
return $value();
}
} catch (\Throwable $e) {
unset($this->keys[$key]);
goto get_from_pool;
}
return $value;
}
/**
* {@inheritdoc}
*/
public function getItem($key)
{
2018-04-19 15:46:47 +01:00
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
}
if (!isset($this->keys[$key])) {
return $this->pool->getItem($key);
}
$value = $this->values[$this->keys[$key]];
$isHit = true;
if ('N;' === $value) {
$value = null;
} elseif ($value instanceof \Closure) {
try {
$value = $value();
} catch (\Throwable $e) {
$value = null;
$isHit = false;
}
}
$f = $this->createCacheItem;
return $f($key, $value, $isHit);
}
/**
* {@inheritdoc}
*/
2019-01-16 09:39:14 +00:00
public function getItems(array $keys = [])
{
foreach ($keys as $key) {
2018-04-19 15:46:47 +01:00
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
}
if (null === $this->values) {
$this->initialize();
}
return $this->generateItems($keys);
}
/**
* {@inheritdoc}
*/
public function hasItem($key)
{
2018-04-19 15:46:47 +01:00
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
}
return isset($this->keys[$key]) || $this->pool->hasItem($key);
}
/**
* {@inheritdoc}
*/
public function deleteItem($key)
{
2018-04-19 15:46:47 +01:00
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
}
return !isset($this->keys[$key]) && $this->pool->deleteItem($key);
}
/**
* {@inheritdoc}
*/
public function deleteItems(array $keys)
{
$deleted = true;
2019-01-16 09:39:14 +00:00
$fallbackKeys = [];
foreach ($keys as $key) {
2018-04-19 15:46:47 +01:00
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (isset($this->keys[$key])) {
$deleted = false;
} else {
$fallbackKeys[] = $key;
}
}
if (null === $this->values) {
$this->initialize();
}
if ($fallbackKeys) {
$deleted = $this->pool->deleteItems($fallbackKeys) && $deleted;
}
return $deleted;
}
/**
* {@inheritdoc}
*/
public function save(CacheItemInterface $item)
{
if (null === $this->values) {
$this->initialize();
}
return !isset($this->keys[$item->getKey()]) && $this->pool->save($item);
}
/**
* {@inheritdoc}
*/
public function saveDeferred(CacheItemInterface $item)
{
if (null === $this->values) {
$this->initialize();
}
return !isset($this->keys[$item->getKey()]) && $this->pool->saveDeferred($item);
}
/**
* {@inheritdoc}
*/
public function commit()
{
return $this->pool->commit();
}
2017-10-28 19:15:32 +01:00
private function generateItems(array $keys): \Generator
{
$f = $this->createCacheItem;
2019-01-16 09:39:14 +00:00
$fallbackKeys = [];
foreach ($keys as $key) {
if (isset($this->keys[$key])) {
$value = $this->values[$this->keys[$key]];
if ('N;' === $value) {
yield $key => $f($key, null, true);
} elseif ($value instanceof \Closure) {
try {
yield $key => $f($key, $value(), true);
} catch (\Throwable $e) {
yield $key => $f($key, null, false);
}
} else {
yield $key => $f($key, $value, true);
}
} else {
$fallbackKeys[] = $key;
}
}
if ($fallbackKeys) {
yield from $this->pool->getItems($fallbackKeys);
}
}
/**
* @throws \ReflectionException When $class is not found and is required
*
* @internal
*/
public static function throwOnRequiredClass($class)
{
$e = new \ReflectionException("Class $class does not exist");
$trace = $e->getTrace();
2019-01-16 09:39:14 +00:00
$autoloadFrame = [
'function' => 'spl_autoload_call',
2019-01-16 09:39:14 +00:00
'args' => [$class],
];
$i = 1 + array_search($autoloadFrame, $trace, true);
if (isset($trace[$i]['function']) && !isset($trace[$i]['class'])) {
switch ($trace[$i]['function']) {
case 'get_class_methods':
case 'get_class_vars':
case 'get_parent_class':
case 'is_a':
case 'is_subclass_of':
case 'class_exists':
case 'class_implements':
case 'class_parents':
case 'trait_exists':
case 'defined':
case 'interface_exists':
case 'method_exists':
case 'property_exists':
case 'is_callable':
return;
}
}
throw $e;
}
}