banker/src/KeyValidateTrait.php

48 lines
1.2 KiB
PHP

<?php declare(strict_types=1);
/**
* Banker
*
* A Caching library implementing psr/cache (PSR 6) and psr/simple-cache (PSR 16)
*
* PHP version 8+
*
* @package Banker
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2016 - 2023 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.1.1
* @link https://git.timshomepage.net/timw4mail/banker
*/
namespace Aviat\Banker;
use Aviat\Banker\Exception\InvalidArgumentException;
trait KeyValidateTrait {
/**
* @param iterable $keys
* @param bool $hash
*/
protected function validateKeys(iterable $keys, bool $hash = FALSE): void
{
$keys = ($hash) ? array_keys((array)$keys) : (array)$keys;
// Check each key
array_walk($keys, [$this, 'validateKey']);
}
/**
* @param mixed $key
* @throws InvalidArgumentException
*/
protected function validateKey(mixed $key): void
{
if ( ! is_string($key))
{
throw new InvalidArgumentException('Cache key must be a string.');
}
else if (preg_match("`[{}()/@:\\\]`", $key) === 1)
{
throw new InvalidArgumentException('Invalid characters in cache key');
}
}
}