IdentifierSuffixer   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 63.64%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 0
dl 0
loc 33
ccs 7
cts 11
cp 0.6364
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A loadBaseHashSalt() 0 4 1
A __construct() 0 3 1
A getIdentifier() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ProxyManager\Generator\Util;
6
7
use PackageVersions\Versions;
8
use function preg_match;
9
use function serialize;
10
use function sha1;
11
use function substr;
12
13
/**
14
 * Utility class capable of generating
15
 * valid class/property/method identifiers
16
 * with a deterministic attached suffix,
17
 * in order to prevent property name collisions
18
 * and tampering from userland
19
 */
20
abstract class IdentifierSuffixer
21
{
22
    public const VALID_IDENTIFIER_FORMAT = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/';
23
    public const DEFAULT_IDENTIFIER      = 'g';
24
25
    final private function __construct()
26
    {
27
    }
28
29
    /**
30
     * Generates a valid unique identifier from the given name,
31
     * with a suffix attached to it
32
     */
33
    public static function getIdentifier(string $name) : string
34 28
    {
35
        /** @var string|null $salt */
36 28
        static $salt;
37
38 28
        $salt   = $salt ?? $salt = self::loadBaseHashSalt();
39 28
        $suffix = substr(sha1($name . $salt), 0, 5);
40
41 28
        if (! preg_match(self::VALID_IDENTIFIER_FORMAT, $name)) {
42 8
            return self::DEFAULT_IDENTIFIER . $suffix;
43
        }
44
45 20
        return $name . $suffix;
46
    }
47
48
    private static function loadBaseHashSalt() : string
49
    {
50
        return sha1(serialize(Versions::VERSIONS));
51
    }
52
}
53