Skip to content

Commit

Permalink
Adpot PSR-16 simple cache in UrlManager::class. (#46)
Browse files Browse the repository at this point in the history
Adpot `PSR-16` simple cache in `UrlManager::class`. (#46)
  • Loading branch information
terabytesoftw authored Jul 17, 2024
1 parent df4ba3f commit 8e85e5d
Show file tree
Hide file tree
Showing 7 changed files with 358 additions and 176 deletions.
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,15 @@
"ezyang/htmlpurifier": "^4.17",
"php-forge/foxy":"^0.1",
"psr/container": "^2.0",
"psr/simple-cache": "^3.0",
"yiisoft/yii2-composer": "^2.0.10"
},
"require-dev": {
"dms/phpunit-arraysubset-asserts": "^0.5",
"maglnet/composer-require-checker": "^4.7",
"phpunit/phpunit": "^9.5"
"phpunit/phpunit": "^9.5",
"yiisoft/cache": "^3.0",
"yiisoft/cache-file": "^3.1"
},
"autoload": {
"psr-4": {
Expand Down
51 changes: 51 additions & 0 deletions src/caching/CacheKeyNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace yii\caching;

use yii\base\InvalidArgumentException;

use function json_encode;
use function json_last_error_msg;
use function is_int;
use function is_string;
use function md5;
use function mb_strlen;
use function strpbrk;

/**
* CacheKeyNormalizer normalizes the cache key to a string.
*/
final class CacheKeyNormalizer
{
/**
* Normalizes the cache key from a given key.
*
* If the given key is a string that does not contain characters `{}()/\@:` and no more than 64 characters,
* then the key will be returned back as it is, integers will be converted to strings. Otherwise,
* a normalized key is generated by serializing the given key and applying MD5 hashing.
*
* @see https://www.php-fig.org/psr/psr-16/#12-definitions
*
* @param mixed $key the key to be normalized.
*
* @throws InvalidArgumentException for invalid key.
*
* @return string the normalized cache key.
*/
public static function normalize(mixed $key): string
{
if (is_string($key) || is_int($key)) {
$key = (string) $key;
$length = mb_strlen($key, '8bit');
return (strpbrk($key, '{}()/\@:') || $length < 1 || $length > 64) ? md5($key) : $key;
}

if (($key = json_encode($key)) === false) {
throw new InvalidArgumentException('Invalid key. ' . json_last_error_msg());
}

return md5($key);
}
}
Loading

0 comments on commit 8e85e5d

Please sign in to comment.