Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow set driver using closure #395

Merged
merged 4 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
public function getDriver(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->getDriver($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'));
}
}
Loading