diff --git a/src/System/Cache/CacheManager.php b/src/System/Cache/CacheManager.php index 6d39b56c..51f16fa0 100644 --- a/src/System/Cache/CacheManager.php +++ b/src/System/Cache/CacheManager.php @@ -8,7 +8,7 @@ class CacheManager implements CacheInterface { - /** @var array */ + /** @var array */ private $driver = []; private CacheInterface $default_driver; @@ -25,17 +25,35 @@ public function setDefaultDriver(CacheInterface $driver): self return $this; } - public function setDriver(string $driver_name, CacheInterface $driver): self + /** + * @param CacheInterface|\Closure(): CacheInterface $driver + */ + public function setDriver(string $driver_name, $driver): self { $this->driver[$driver_name] = $driver; return $this; } - public function driver(?string $driver = null): CacheInterface + private function resolve(string $driver_name): CacheInterface + { + $driver = $this->driver[$driver_name]; + + if (\is_callable($driver)) { + $driver = $driver(); + } + + if (null === $driver) { + throw new \Exception("Can use driver {$driver_name}."); + } + + return $this->driver[$driver_name] = $driver; + } + + public function driver(?string $driver_name = null): CacheInterface { - if (array_key_exists($driver, $this->driver)) { - return $this->driver[$driver]; + if (isset($this->driver[$driver_name])) { + return $this->resolve($driver_name); } return $this->default_driver; diff --git a/tests/Cache/CacheManagerTest.php b/tests/Cache/CacheManagerTest.php index 141529fb..e2a1af4e 100644 --- a/tests/Cache/CacheManagerTest.php +++ b/tests/Cache/CacheManagerTest.php @@ -20,4 +20,14 @@ public function testSetDefaultDriver(): void $this->assertTrue($cache->set('key1', 'value1')); $this->assertEquals('value1', $cache->get('key1')); } + + public function testDriver(): void + { + $cache = new CacheManager(); + $cache->setDriver('array2', fn (): CacheInterface => new ArrayStorage()); + $this->assertInstanceOf(CacheInterface::class, $cache->driver('array2')); + + $this->assertTrue($cache->driver('array2')->set('key1', 'value1')); + $this->assertEquals('value1', $cache->driver('array2')->get('key1')); + } }