| 1 |
<?php |
| 2 |
|
| 3 |
namespace ElementorDeps\DI\Definition\Source; |
| 4 |
|
| 5 |
use ElementorDeps\DI\Definition\AutowireDefinition; |
| 6 |
use ElementorDeps\DI\Definition\Definition; |
| 7 |
use ElementorDeps\DI\Definition\ObjectDefinition; |
| 8 |
/** |
| 9 |
* Decorator that caches another definition source. |
| 10 |
* |
| 11 |
* @author Matthieu Napoli <matthieu@mnapoli.fr> |
| 12 |
*/ |
| 13 |
class SourceCache implements DefinitionSource, MutableDefinitionSource |
| 14 |
{ |
| 15 |
/** |
| 16 |
* @var string |
| 17 |
*/ |
| 18 |
const CACHE_KEY = 'php-di.definitions.'; |
| 19 |
/** |
| 20 |
* @var DefinitionSource |
| 21 |
*/ |
| 22 |
private $cachedSource; |
| 23 |
/** |
| 24 |
* @var string |
| 25 |
*/ |
| 26 |
private $cacheNamespace; |
| 27 |
public function __construct(DefinitionSource $cachedSource, string $cacheNamespace = '') |
| 28 |
{ |
| 29 |
$this->cachedSource = $cachedSource; |
| 30 |
$this->cacheNamespace = $cacheNamespace; |
| 31 |
} |
| 32 |
public function getDefinition(string $name) |
| 33 |
{ |
| 34 |
$definition = \apcu_fetch($this->getCacheKey($name)); |
| 35 |
if ($definition === \false) { |
| 36 |
$definition = $this->cachedSource->getDefinition($name); |
| 37 |
// Update the cache |
| 38 |
if ($this->shouldBeCached($definition)) { |
| 39 |
\apcu_store($this->getCacheKey($name), $definition); |
| 40 |
} |
| 41 |
} |
| 42 |
return $definition; |
| 43 |
} |
| 44 |
/** |
| 45 |
* Used only for the compilation so we can skip the cache safely. |
| 46 |
*/ |
| 47 |
public function getDefinitions() : array |
| 48 |
{ |
| 49 |
return $this->cachedSource->getDefinitions(); |
| 50 |
} |
| 51 |
public static function isSupported() : bool |
| 52 |
{ |
| 53 |
return \function_exists('apcu_fetch') && \ini_get('apc.enabled') && !('cli' === \PHP_SAPI && !\ini_get('apc.enable_cli')); |
| 54 |
} |
| 55 |
public function getCacheKey(string $name) : string |
| 56 |
{ |
| 57 |
return self::CACHE_KEY . $this->cacheNamespace . $name; |
| 58 |
} |
| 59 |
public function addDefinition(Definition $definition) |
| 60 |
{ |
| 61 |
throw new \LogicException('You cannot set a definition at runtime on a container that has caching enabled. Doing so would risk caching the definition for the next execution, where it might be different. You can either put your definitions in a file, remove the cache or ->set() a raw value directly (PHP object, string, int, ...) instead of a PHP-DI definition.'); |
| 62 |
} |
| 63 |
private function shouldBeCached(Definition $definition = null) : bool |
| 64 |
{ |
| 65 |
return $definition === null || $definition instanceof ObjectDefinition || $definition instanceof AutowireDefinition; |
| 66 |
} |
| 67 |
} |
| 68 |
|