Passed
Push — master ( c2b4c4...fd18cf )
by Alexander
03:23 queued 01:03
created

CacheKeyNormalizer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 7
c 2
b 0
f 0
dl 0
loc 30
ccs 8
cts 8
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B normalize() 0 13 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Cache;
6
7
use Yiisoft\Cache\Exception\InvalidArgumentException;
8
9
use function json_encode;
10
use function json_last_error_msg;
11
use function is_int;
12
use function is_string;
13
use function md5;
14
use function mb_strlen;
15
use function strpbrk;
16
17
/**
18
 * CacheKeyNormalizer normalizes the cache key to a string.
19
 */
20
final class CacheKeyNormalizer
21
{
22
    /**
23
     * Normalizes the cache key from a given key.
24
     *
25
     * If the given key is a string that does not contain characters `{}()/\@:` and no more than 64 characters,
26
     * then the key will be returned back as it is, integers will be converted to strings. Otherwise,
27
     * a normalized key is generated by serializing the given key and applying MD5 hashing.
28
     *
29
     * @see https://www.php-fig.org/psr/psr-16/#12-definitions
30
     *
31
     * @param mixed $key The key to be normalized.
32
     *
33
     * @throws InvalidArgumentException For invalid key.
34
     *
35
     * @return string The normalized cache key.
36
     */
37 62
    public function normalize($key): string
38
    {
39 62
        if (is_string($key) || is_int($key)) {
40 43
            $key = (string) $key;
41 43
            $length = mb_strlen($key, '8bit');
42 43
            return (strpbrk($key, '{}()/\@:') || $length < 1 || $length > 64) ? md5($key) : $key;
43
        }
44
45 19
        if (($key = json_encode($key)) === false) {
46 3
            throw new InvalidArgumentException('Invalid key. ' . json_last_error_msg());
47
        }
48
49 16
        return md5($key);
50
    }
51
}
52