diff --git a/composer.json b/composer.json index aaeb4dc..d05dd40 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ } ], "require": { - "php": "^8.0" + "php": "^8.0", + "psr/simple-cache": "^3.0" }, "autoload": { "psr-0": {"iFixit": "library/"} diff --git a/library/iFixit/Matryoshka/PSR16Adapter.php b/library/iFixit/Matryoshka/PSR16Adapter.php new file mode 100644 index 0000000..0783f80 --- /dev/null +++ b/library/iFixit/Matryoshka/PSR16Adapter.php @@ -0,0 +1,64 @@ +scope = new Scope($backend, $scopeName); + } + + public function get(string $key, mixed $default = null): mixed { + return $this->scope->get($key) ?: $default; + } + + public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool { + return $this->scope->set($key, $value, $this->getSeconds($ttl)); + } + + public function delete(string $key): bool { + return $this->scope->delete($key); + } + + public function clear(): bool { + return $this->scope->deleteScope(); + } + + public function getMultiple(iterable $keys, mixed $default = null): iterable { + /** + * @var array $missed + * @var array $found + */ + [$found, $missed] = $this->scope->getMultiple([...$keys]); + $missedWithDefault = []; + + foreach ($missed as $key => $_value) { + $missedWithDefault[$key] = $default; + } + + return array_merge($missedWithDefault, $found); + } + + public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { + return $this->scope->setMultiple([...$values], $this->getSeconds($ttl)); + } + + public function deleteMultiple(iterable $keys): bool { + return $this->scope->deleteMultiple([...$keys]); + } + + public function has(string $key): bool { + $isMiss = $this->scope->get($key) === Backend::MISS; + return !$isMiss; + } + + private function getSeconds(null|int|DateInterval $secs) { + $seconds = $secs instanceof DateInterval ? (new DateTime('@0'))->add($secs)->getTimestamp() : $secs; + return $seconds ?: 0; + } +}