Skip to content

Commit

Permalink
Merge pull request #39 from iFixit/add-psr-16-adapter
Browse files Browse the repository at this point in the history
Add PSR16 adapter
  • Loading branch information
aburke07 authored Jul 22, 2024
2 parents e11f9b0 + 08585b2 commit ab81f01
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
}
],
"require": {
"php": "^8.0"
"php": "^8.0",
"psr/simple-cache": "^3.0"
},
"autoload": {
"psr-0": {"iFixit": "library/"}
Expand Down
64 changes: 64 additions & 0 deletions library/iFixit/Matryoshka/PSR16Adapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace iFixit\Matryoshka;

use DateInterval;
use DateTime;
use Psr\SimpleCache\CacheInterface;

class PSR16Adapter implements CacheInterface {
private Scope $scope;

public function __construct(Backend $backend, string $scopeName) {
$this->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<string, mixed> $missed
* @var array<string, mixed> $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;
}
}

0 comments on commit ab81f01

Please sign in to comment.