Skip to content

Commit

Permalink
fix: allow set driver using closure (#395)
Browse files Browse the repository at this point in the history
* fix: allow set driver using closure

- allowing lazy load driver without initial driver

* test

* test

* change method name
  • Loading branch information
SonyPradana authored Oct 8, 2024
1 parent 24c17f8 commit 805abf6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/System/Cache/CacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class CacheManager implements CacheInterface
{
/** @var array<string, CacheInterface> */
/** @var array<string, CacheInterface|\Closure(): CacheInterface> */
private $driver = [];

private CacheInterface $default_driver;
Expand All @@ -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;
Expand Down
10 changes: 10 additions & 0 deletions tests/Cache/CacheManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
}
}

0 comments on commit 805abf6

Please sign in to comment.