Skip to content

Commit

Permalink
Merge pull request #14 from ray-di/ps6-local-cache
Browse files Browse the repository at this point in the history
Create Psr6LocalCacheModule
  • Loading branch information
koriym committed Oct 15, 2022
2 parents b2717a3 + 5c75de0 commit af715ee
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 33 deletions.
32 changes: 0 additions & 32 deletions src-deprecated/LocalCacheProvider.php

This file was deleted.

41 changes: 41 additions & 0 deletions src/LocalCacheProvider.php
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace Ray\PsrCacheModule;

use Ray\Di\ProviderInterface;
use Ray\PsrCacheModule\Annotation\CacheDir;
use Ray\PsrCacheModule\Annotation\CacheNamespace;
use Symfony\Component\Cache\Adapter\AbstractAdapter;

use function sys_get_temp_dir;

/**
* Provide APCu cache adapter if available, otherwise file cache adapter
*
* @implements ProviderInterface<ApcuAdapter|FilesystemAdapter>
*/
final class LocalCacheProvider implements ProviderInterface
{
/** @var string */
private $cacheDir;

/** @var string */
private $namespace;

#[CacheDir('cacheDir')]
#[CacheNamespace('namespace')]
public function __construct(string $cacheDir = '', string $namespace = '')
{
$this->cacheDir = $cacheDir ?: sys_get_temp_dir();
$this->namespace = $namespace;
}

public function get(): AbstractAdapter
{
return ApcuAdapter::isSupported() ?
new ApcuAdapter($this->namespace) :
new FilesystemAdapter($this->namespace, 0, $this->cacheDir);
}
}
20 changes: 20 additions & 0 deletions src/Psr6LocalCacheModule.php
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Ray\PsrCacheModule;

use Psr\Cache\CacheItemPoolInterface;
use Ray\Di\AbstractModule;
use Ray\Di\Scope;
use Ray\PsrCacheModule\Annotation\Local;
use Ray\PsrCacheModule\Annotation\Shared;

final class Psr6LocalCacheModule extends AbstractModule
{
protected function configure(): void
{
$this->bind(CacheItemPoolInterface::class)->annotatedWith(Local::class)->toProvider(LocalCacheProvider::class)->in(Scope::SINGLETON);
$this->bind(CacheItemPoolInterface::class)->annotatedWith(Shared::class)->toProvider(LocalCacheProvider::class)->in(Scope::SINGLETON);
}
}
9 changes: 8 additions & 1 deletion tests/Psr6CacheTest.php
Expand Up @@ -29,7 +29,14 @@ public function testArrayCacheModule(): void
public function testCacheDirModule(): void
{
$module = new CacheDirModule('/tmp');
$cacheDir = (new Injector($module))->getInstance('', CacheDir::class); // @phpstan-ignore-line
$cacheDir = (new Injector($module))->getInstance('', CacheDir::class);
$this->assertSame('/tmp', $cacheDir);
}

public function testPsr6LocalCacheModule(): void
{
$module = new Psr6LocalCacheModule();
$cache = (new Injector($module))->getInstance(CacheItemPoolInterface::class, Shared::class);
$this->assertTrue($cache instanceof ApcuAdapter || $cache instanceof FilesystemAdapter);
}
}

0 comments on commit af715ee

Please sign in to comment.