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

Adding symfony cache #62

Merged
merged 9 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"php": ">=8.0",
"ext-json": "*",
"guzzlehttp/guzzle": "^6.3||^7.0",
"sabre/cache": "^1.0",
"symfony/cache": "^6.3",
"symfony/http-foundation": "^6.2"
},
"require-dev": {
Expand Down
20 changes: 13 additions & 7 deletions src/cache/DefaultCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace ipinfo\ipinfo\cache;

use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Contracts\Cache\ItemInterface;

/**
* Default implementation of the CacheInterface. Provides in-memory caching.
*/
Expand All @@ -16,7 +19,7 @@ class DefaultCache implements CacheInterface

public function __construct(int $maxsize, int $ttl)
{
$this->cache = new \Sabre\Cache\Memory();
$this->cache = new ArrayAdapter();
$this->element_queue = array();
$this->maxsize = $maxsize;
$this->ttl = $ttl;
Expand All @@ -27,9 +30,9 @@ public function __construct(int $maxsize, int $ttl)
* @param string $ip_address IP address to lookup.
* @return boolean Is the IP address data in the cache.
*/
public function has(string $name)
public function has(string $name): bool
{
return $this->cache->has($name);
return $this->cache->hasItem($name);
}

/**
Expand All @@ -39,11 +42,14 @@ public function has(string $name)
*/
public function set(string $name, $value)
{
if (!$this->cache->has($name)) {
if (!$this->cache->hasItem($name)) {
$this->element_queue[] = $name;
}

$this->cache->set($name, $value, $this->ttl);
$this->cache->get($name, function (ItemInterface $item) use ($value) {
$item->set($value)->expiresAfter($this->ttl);
return $item->get();
});

$this->manageSize();
}
Expand All @@ -55,7 +61,7 @@ public function set(string $name, $value)
*/
public function get(string $name)
{
return $this->cache->get($name);
return $this->cache->getItem($name)->get();
}

/**
Expand All @@ -66,7 +72,7 @@ private function manageSize()
$overflow = count($this->element_queue) - $this->maxsize;
if ($overflow > 0) {
foreach (array_slice($this->element_queue, 0, $overflow) as $name) {
if ($this->cache->has($name)) {
if ($this->has($name)) {
$this->cache->delete($name);
}
}
Expand Down
Loading