Passed
Push — master ( 5cc235...2f8a96 )
by Alexander
02:00
created

CacheKeyNormalizer::normalize()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.2222
cc 6
nc 6
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Cache;
6
7
use Yiisoft\Cache\Exception\InvalidArgumentException;
8
9
use function ctype_alnum;
10
use function json_encode;
11
use function json_last_error_msg;
12
use function is_int;
13
use function is_string;
14
use function md5;
15
use function mb_strlen;
16
17
final class CacheKeyNormalizer
18
{
19
    /**
20
     * Normalizes cache key from a given key.
21
     *
22
     * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
23
     * then the key will be returned back as it is, integers will be converted to strings. Otherwise,
24
     * a normalized key is generated by serializing the given key and applying MD5 hashing.
25
     *
26
     * @param mixed $key The key to be normalized.
27
     * @return string The normalized cache key.
28
     */
29 12
    public function normalize($key): string
30
    {
31 12
        if (is_string($key) || is_int($key)) {
32 3
            $key = (string) $key;
33 3
            return ctype_alnum($key) && mb_strlen($key, '8bit') <= 32 ? $key : md5($key);
34
        }
35
36 9
        if (($key = json_encode($key)) === false) {
37 1
            throw new InvalidArgumentException('Invalid key. ' . json_last_error_msg());
38
        }
39
40 8
        return md5($key);
41
    }
42
}
43