generated from yii-tools/template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adpot `PSR-16` simple cache in `UrlManager::class`. (#46)
- Loading branch information
1 parent
df4ba3f
commit 8e85e5d
Showing
7 changed files
with
358 additions
and
176 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
Oops, something went wrong.