5 Commits

Author SHA1 Message Date
3d01196b0a Update to PHP 8 2021-04-10 12:45:25 +02:00
d992c767e8 Improve code, fix filesystem test failing after first run 2018-03-25 12:49:02 +02:00
5b94961691 Fix link in readme 2018-03-05 12:09:53 +01:00
9cc7739f26 Update readme 2018-02-28 15:45:18 +01:00
13cc8d2577 Add scrutinizer 2018-02-28 15:33:18 +01:00
18 changed files with 151 additions and 92 deletions

3
.gitignore vendored
View File

@@ -4,4 +4,5 @@ composer.lock
vendor/
tmp/
.vs/
.vscode/
.vscode/
.phpunit*

10
.scrutinizer.yml Normal file
View File

@@ -0,0 +1,10 @@
filter:
paths: ["src/*"]
tools:
external_code_coverage: true
php_code_coverage: true
php_sim: true
php_mess_detector: true
php_pdepend: true
php_analyzer: true
php_cpd: true

View File

@@ -4,10 +4,17 @@ PHP Cache library with namespace, filesystem and (p)redis implementations.
### Requirements
Requires PHP 7.0+. Older versions might work but have not been tested.
### Installation
`composer require iqparts/cache`
### Another cache library
This cache library has been highly inspired by [Genkgo.Cache](https://raw.githubusercontent.com/genkgo/cache). We recommend using this library as it implements more adapters. The reason for this library was the need to have a backup for redis which still was able to store cached values with a variable TTL.
This cache library has been highly inspired by [Genkgo.Cache](https://github.com/genkgo/cache). We recommend using Genkgo's library as it implements more adapters. The reason for this library was the need to have a backup for redis which still was able to store cached values with a **variable** TTL.
### Code
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/IQParts/cache/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/IQParts/cache/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/IQParts/cache/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/IQParts/cache/?branch=master)
[![Build Status](https://scrutinizer-ci.com/g/IQParts/cache/badges/build.png?b=master)](https://scrutinizer-ci.com/g/IQParts/cache/build-status/master)
This library attempts to comply with [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md), [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) & [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md).
### Create your own adapter

View File

@@ -1,13 +1,14 @@
{
"name": "iqparts/cache",
"type": "library",
"description": "Simple cache library with Redis and Filesystem adapters.",
"license": "MIT",
"require": {
"php": "^8.0",
"predis/predis": "^1.1"
},
"require-dev": {
"phpunit/phpunit": "^6.3",
"phpstan/phpstan": "^0.9.1"
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {

View File

@@ -5,11 +5,12 @@ namespace IQParts\Cache\Adapter;
interface CacheAdapterInterface
{
public const NO_TTL = -1;
/**
* @param string $key
* @return mixed
*/
public function get(string $key);
public function get(string $key): mixed;
/**
* @param string $key
@@ -17,19 +18,19 @@ interface CacheAdapterInterface
* @param int|null $ttl
* @return void
*/
public function set(string $key, $value, int $ttl = null);
public function set(string $key, $value, int $ttl = null): void;
/**
* @param string $key
* @return mixed
* @return void
*/
public function delete(string $key);
public function delete(string $key): void;
/**
* @param string $key
* @return mixed
* @return array
*/
public function keys($key = '*');
public function keys($key = '*'): array;
/**
* @param $key

View File

@@ -9,39 +9,39 @@ class FilesystemAdapter implements CacheAdapterInterface
/**
* @var string
*/
private $directory;
private string $directory;
/**
* @var null|int
*/
private $chmod;
private ?int $chmod;
/**
* @var string
*/
private $directorySeparator;
private ?string $directorySeparator;
/**
* @var int|null
*/
private $ttl;
private ?int $ttl;
/**
* @var array
*/
private $timeToLive;
private mixed $timeToLive;
/**
* @var SerializerInterface
*/
private $serializer;
private SerializerInterface $serializer;
/**
* @var array
*/
private $index;
private mixed $index;
/**
* @var string
*/
private $indexLocation;
private string $indexLocation;
/**
* @var string
*/
private $ttlLocation;
private string $ttlLocation;
/**
* FilesystemAdapter constructor.
@@ -49,21 +49,21 @@ class FilesystemAdapter implements CacheAdapterInterface
* @param SerializerInterface $serializer
* @param int|null $chmod
* @param int|null $ttl
* @param string|null $directorySeperator
* @param string|null $directorySeparator
*/
public function __construct(
string $directory,
SerializerInterface $serializer,
int $chmod = null,
int $ttl = null,
string $directorySeperator = null
string $directorySeparator = null
)
{
$this->indexLocation = $directory . '/' . md5($directory) . 'index';
$this->ttlLocation = $directory . '/' . md5($directory) . 'ttl';
$this->directory = $directory;
$this->serializer = $serializer;
$this->directorySeparator = $directorySeperator;
$this->directorySeparator = $directorySeparator;
$this->chmod = $chmod;
$this->ttl = $ttl;
@@ -84,7 +84,7 @@ class FilesystemAdapter implements CacheAdapterInterface
* @param string $key
* @return mixed
*/
public function get(string $key)
public function get(string $key): mixed
{
$file = $this->getFilename($key);
if ($this->exists($file)) {
@@ -106,7 +106,7 @@ class FilesystemAdapter implements CacheAdapterInterface
* @param int|null $ttl
* @return void
*/
public function set(string $key, $value, int $ttl = null)
public function set(string $key, $value, int $ttl = null): void
{
$file = $this->getFilename($key);
file_put_contents($file, $this->serializer->serialize($value));
@@ -126,9 +126,9 @@ class FilesystemAdapter implements CacheAdapterInterface
/**
* @param string $key
*/
public function delete(string $key)
public function delete(string $key): void
{
if (strpos($key, '*') !== false) {
if (str_contains($key, '*')) {
$this->deleteGlob($key);
$this->saveIndex();
} else {
@@ -136,17 +136,16 @@ class FilesystemAdapter implements CacheAdapterInterface
if ($this->exists($file)) {
unlink($file);
}
unset($this->index[$key]);
unset($this->timeToLive[$key]);
unset($this->index[$key], $this->timeToLive[$key]);
$this->saveIndex();
}
}
/**
* @param string $key
* @return mixed
* @return array
*/
public function keys($key = '*')
public function keys($key = '*'): array
{
$matches = [];
foreach ($this->index as $name => $index) {
@@ -175,7 +174,7 @@ class FilesystemAdapter implements CacheAdapterInterface
/**
* @param $pattern
*/
private function deleteGlob($pattern)
private function deleteGlob($pattern): void
{
foreach ($this->index as $key => $value) {
if (fnmatch($pattern, $key)) {
@@ -188,7 +187,7 @@ class FilesystemAdapter implements CacheAdapterInterface
* @param $file
* @return bool
*/
private function exists(string $file)
private function exists(string $file): bool
{
return file_exists($file);
}
@@ -197,9 +196,9 @@ class FilesystemAdapter implements CacheAdapterInterface
* @param $key
* @return string
*/
private function getFilename(string $key)
private function getFilename(string $key): string
{
list($directory, $file) = $this->getDirectoryAndFile($key);
[$directory, $file] = $this->getDirectoryAndFile($key);
return $directory . '/' . md5($file);
}
@@ -207,7 +206,7 @@ class FilesystemAdapter implements CacheAdapterInterface
* @param string $key
* @return array
*/
private function getDirectoryAndFile(string $key)
private function getDirectoryAndFile(string $key): array
{
$directory = $this->directory;
if ($this->directorySeparator !== null) {
@@ -224,17 +223,19 @@ class FilesystemAdapter implements CacheAdapterInterface
/**
* @param $directory
*/
private function createSubDirectoryIfNotExists($directory)
private function createSubDirectoryIfNotExists($directory): void
{
if (file_exists($directory) === false) {
mkdir($directory);
if (!mkdir($directory) && !is_dir($directory)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $directory));
}
if ($this->chmod !== null) {
chmod($directory, $this->chmod);
}
}
}
private function saveIndex()
private function saveIndex(): void
{
file_put_contents($this->indexLocation, json_encode($this->index));
file_put_contents($this->ttlLocation, json_encode($this->timeToLive));

View File

@@ -8,17 +8,17 @@ final class MemoryAdapter implements CacheAdapterInterface
/**
* @var array
*/
private $data = [];
private array $data = [];
/**
* @var array
*/
private $timeToLive = [];
private array $timeToLive = [];
/**
* @param string $key
* @return mixed
*/
public function get(string $key)
public function get(string $key): mixed
{
if (!isset($this->data[$key])) {
return null;
@@ -32,8 +32,7 @@ final class MemoryAdapter implements CacheAdapterInterface
return $this->data[$key];
}
unset($this->timeToLive[$key]);
unset($this->data[$key]);
unset($this->timeToLive[$key], $this->data[$key]);
return null;
}
@@ -43,7 +42,7 @@ final class MemoryAdapter implements CacheAdapterInterface
* @param int|null $ttl
* @return void
*/
public function set(string $key, $value, int $ttl = null)
public function set(string $key, $value, int $ttl = null): void
{
$this->data[$key] = $value;
if ($ttl !== null) {
@@ -53,20 +52,18 @@ final class MemoryAdapter implements CacheAdapterInterface
/**
* @param string $key
* @return mixed
* @return void
*/
public function delete(string $key)
public function delete(string $key): void
{
unset($this->data[$key]);
unset($this->timeToLive[$key]);
return 1;
unset($this->data[$key], $this->timeToLive[$key]);
}
/**
* @param string $key
* @return mixed
* @return array
*/
public function keys($key = '*')
public function keys($key = '*'): array
{
$matches = [];
foreach ($this->data as $name => $value) {

View File

@@ -7,11 +7,11 @@ final class NamespaceAdapter implements CacheAdapterInterface
/**
* @var string
*/
private $namespace;
private string $namespace;
/**
* @var CacheAdapterInterface
*/
private $cacheAdapter;
private CacheAdapterInterface $cacheAdapter;
/**
* NamespaceAdapter constructor.
@@ -28,7 +28,7 @@ final class NamespaceAdapter implements CacheAdapterInterface
* @param string $key
* @return mixed
*/
public function get(string $key)
public function get(string $key): mixed
{
return $this->cacheAdapter->get($this->namespace . $key);
}
@@ -48,7 +48,7 @@ final class NamespaceAdapter implements CacheAdapterInterface
* @param string $key
* @return void
*/
public function delete(string $key)
public function delete(string $key): void
{
$this->cacheAdapter->delete($this->namespace . $key);
}
@@ -57,19 +57,20 @@ final class NamespaceAdapter implements CacheAdapterInterface
* @param string $key
* @return array
*/
public function keys($key = '*')
public function keys($key = '*'): array
{
if (substr($key, -1) !== '*') {
$key = $key . '*';
$key .= '*';
}
/** @var string[] $keys */
$keys = $this->cacheAdapter->keys($this->namespace . $key);
$allowed = [];
$len = strlen($this->namespace);
$len = \strlen($this->namespace);
foreach ($keys as $key) {
if (substr($key, 0, $len) === $this->namespace) {
$allowed[] = substr($key, $len);
foreach ($keys as $cacheKey) {
if (str_starts_with($cacheKey, $this->namespace)) {
$allowed[] = substr($cacheKey, $len);
}
}

View File

@@ -9,7 +9,7 @@ final class NullAdapter implements CacheAdapterInterface
* @param string $key
* @return mixed
*/
public function get(string $key)
public function get(string $key): mixed
{
return null;
}
@@ -20,7 +20,7 @@ final class NullAdapter implements CacheAdapterInterface
* @param int|null $ttl
* @return void
*/
public function set(string $key, $value, int $ttl = null)
public function set(string $key, $value, int $ttl = null): void
{
}
@@ -28,15 +28,15 @@ final class NullAdapter implements CacheAdapterInterface
* @param string $key
* @return void
*/
public function delete(string $key)
public function delete(string $key): void
{
}
/**
* @param string $key
* @return mixed
* @return array
*/
public function keys($key = '')
public function keys($key = ''): array
{
return [];
}

View File

@@ -9,17 +9,17 @@ use Predis\ClientInterface;
final class PredisAdapter implements CacheAdapterInterface
{
/**
* @var Client
* @var ClientInterface
*/
private $client;
private ClientInterface $client;
/**
* @var SerializerInterface
*/
private $serializer;
private SerializerInterface $serializer;
/**
* @var null
*/
private $defaultTtl;
private ?int $defaultTtl;
/**
* PredisAdapter constructor.
@@ -38,7 +38,7 @@ final class PredisAdapter implements CacheAdapterInterface
* @param string $key
* @return mixed
*/
public function get(string $key)
public function get(string $key): mixed
{
return $this->serializer->deserialize($this->client->get($key));
}
@@ -48,7 +48,7 @@ final class PredisAdapter implements CacheAdapterInterface
* @param $value
* @param int|null $ttl TTL in seconds
*/
public function set(string $key, $value, int $ttl = null)
public function set(string $key, $value, int $ttl = null): void
{
if ($ttl !== null && $ttl !== 0) {
$this->client->setex($key, $ttl ?? $this->defaultTtl, $this->serializer->serialize($value));
@@ -59,18 +59,18 @@ final class PredisAdapter implements CacheAdapterInterface
/**
* @param string $key
* @return integer
* @return void
*/
public function delete(string $key): int
public function delete(string $key): void
{
return $this->client->del([$key]);
$this->client->del([$key]);
}
/**
* @param string $key
* @return mixed
* @return array
*/
public function keys($key = '*')
public function keys($key = '*'): array
{
return $this->client->keys($key);
}

View File

@@ -4,16 +4,24 @@ namespace IQParts\Cache\Serializer;
final class JsonSerializer implements SerializerInterface
{
public function serialize($input)
/**
* @param $input
* @return string
*/
public function serialize($input): string
{
if (is_array($input)) {
if (\is_array($input)) {
return json_encode($input);
}
return $input;
}
public function deserialize($string)
/**
* @param $string
* @return mixed
*/
public function deserialize($string): mixed
{
return json_decode($string, true) ?? $string;
}

View File

@@ -5,12 +5,12 @@ namespace IQParts\Cache\Serializer;
final class NoSerializer implements SerializerInterface
{
public function serialize($input)
public function serialize($input): string
{
return $input;
}
public function deserialize($string)
public function deserialize($string): mixed
{
return $string;
}

View File

@@ -4,7 +4,15 @@ namespace IQParts\Cache\Serializer;
interface SerializerInterface
{
public function serialize($input);
/**
* @param $input
* @return string
*/
public function serialize($input): string;
public function deserialize($string);
/**
* @param $string
* @return mixed
*/
public function deserialize($string): mixed;
}

View File

@@ -6,11 +6,14 @@ use PHPUnit\Framework\TestCase;
abstract class AbstractTestCase extends TestCase
{
public function getTmpDirectory()
/**
* @return string
*/
public function getTmpDirectory(): string
{
$location = __DIR__ . '/../tmp';
if (!file_exists($location)) {
if (!mkdir($location)) {
if (!mkdir($location) && !is_dir($location)) {
throw new \RuntimeException('Could not create directory: ' . $location);
}
chmod($location, 0777);

View File

@@ -6,6 +6,8 @@ namespace IQParts\CacheTest\Unit\Adapter;
use IQParts\Cache\Adapter\FilesystemAdapter;
use IQParts\Cache\Serializer\JsonSerializer;
use IQParts\CacheTest\AbstractTestCase;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
final class FilesystemAdapterTest extends AbstractTestCase
{
@@ -27,7 +29,7 @@ final class FilesystemAdapterTest extends AbstractTestCase
$adapter->set('ttl', 'b', 200);
$this->assertTrue($adapter->ttl('ttl') > 0);
$this->assertTrue($adapter->ttl('b') === $adapter::NO_TTL);
$this->assertSame($adapter->ttl('b'), $adapter::NO_TTL);
$adapter->set('a-keys', 'a');
$adapter->set('b-keys', 'a');
@@ -118,4 +120,22 @@ final class FilesystemAdapterTest extends AbstractTestCase
$this->assertEquals('a', $adapter->get('a/b'));
$adapter->delete('a/b');
}
protected function tearDown(): void
{
parent::tearDown();
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($this->getTmpDirectory(), RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
}
}

View File

@@ -8,6 +8,9 @@ use IQParts\CacheTest\AbstractTestCase;
final class MemoryAdapterTest extends AbstractTestCase
{
/**
*
*/
public function testAdapter()
{
$adapter = new MemoryAdapter();
@@ -25,7 +28,7 @@ final class MemoryAdapterTest extends AbstractTestCase
$adapter->set('a', 'b', 200);
$this->assertTrue($adapter->ttl('a') > 0);
$this->assertTrue($adapter->ttl('c') === MemoryAdapter::NO_TTL);
$this->assertSame($adapter->ttl('c'), MemoryAdapter::NO_TTL);
}
public function testTtl()

View File

@@ -15,7 +15,7 @@ final class NamespaceAdapterTest extends AbstractTestCase
*/
private $adapter;
public function setUp()
public function setUp(): void
{
$this->adapter = new MemoryAdapter();
}

View File

@@ -10,12 +10,10 @@ final class JsonSerializerTest extends AbstractTestCase
public function testSerialize()
{
$serializer = new JsonSerializer();
$string = "myString";
$string = 'myString';
$array = [0 => '1', 1 => '2', 2 => '3'];
$this->assertTrue(is_string($serializer->serialize($array)));
$this->assertEquals($string, $serializer->serialize($string));
$this->assertEquals($array, $serializer->deserialize($serializer->serialize($array)));
}