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

Sanitize cache keys to prevent an exception on IPv6 addresses #78

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all 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
18 changes: 17 additions & 1 deletion src/cache/DefaultCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace ipinfo\ipinfo\cache;

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

/**
Expand Down Expand Up @@ -32,6 +33,8 @@ public function __construct(int $maxsize, int $ttl)
*/
public function has(string $name): bool
{
$name = $this->sanitizeName($name);

return $this->cache->hasItem($name);
}

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

$this->cache->get($name, function (ItemInterface $item) use ($value) {
$this->cache->get($name, function (ItemInterface $item) use ($value) {
$item->set($value)->expiresAfter($this->ttl);
return $item->get();
});
Expand All @@ -61,6 +65,8 @@ public function set(string $name, $value)
*/
public function get(string $name)
{
$name = $this->sanitizeName($name);

return $this->cache->getItem($name)->get();
}

Expand All @@ -79,4 +85,14 @@ private function manageSize()
$this->element_queue = array_slice($this->element_queue, $overflow);
}
}

/**
* Remove forbidden characters from cache keys
*/
private function sanitizeName(string $name): string
{
$forbiddenCharacters = str_split(CacheItem::RESERVED_CHARACTERS);

return str_replace($forbiddenCharacters, "", $name);
}
}