UniqueExtractor   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 25
c 1
b 0
f 1
dl 0
loc 48
ccs 23
cts 23
cp 1
rs 10
wmc 12

1 Method

Rating   Name   Duplication   Size   Complexity  
C getString() 0 26 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Smoren\PartialIntersection\Util;
6
7
use Closure;
8
use Generator;
9
10
/**
11
 * Tool for extracting unique IDs and hashes of any PHP variables and data structures.
12
 *
13
 * Based on PHP Type Tool's UniqueExtractor.
14
 * @see https://github.com/Smoren/type-tools-php
15
 * @see https://github.com/Smoren/type-tools-php/blob/master/src/UniqueExtractor.php
16
 */
17
class UniqueExtractor
18
{
19
    /**
20
     * Returns unique ID string of given variable by its value and type.
21
     *
22
     * If $strict is true:
23
     *  - scalars: result is unique strictly by type;
24
     *  - objects: result is unique by instance;
25
     *  - arrays: result is unique by serialized value;
26
     *  - resources: result is unique by instance.
27
     *
28
     * If $strict is false:
29
     *  - scalars: result is unique by value;
30
     *  - objects: result is unique by serialized value;
31
     *  - arrays: result is unique by serialized value.
32
     *  - resources: result is unique by instance.
33
     *
34
     * @param mixed $var
35
     * @param bool $strict
36
     *
37
     * @return string
38
     */
39 622
    public static function getString($var, bool $strict): string
40
    {
41
        switch (true) {
42 622
            case is_array($var):
43 64
                return 'array_'.serialize($var);
44 558
            case is_resource($var):
45 64
                preg_match('/#([0-9]+)$/', (string)$var, $matches);
46 64
                return 'resource_'.$matches[1];
47 494
            case $var instanceof Generator:
48 64
                return 'generator_'.spl_object_id($var);
49 430
            case $var instanceof Closure:
50 64
                return 'closure_'.spl_object_id($var);
51 366
            case is_object($var):
52 64
                return 'object_'.($strict ? spl_object_id($var) : serialize($var));
53 302
            case gettype($var) === 'boolean':
54 92
                return 'boolean_'.(int)$var;
55 222
            case $strict:
56 111
                return gettype($var).'_'.$var;
57 111
            case !$var:
58 8
                return 'boolean_0';
59 111
            case strval($var) === '1':
60 85
                return 'boolean_1';
61 111
            case is_numeric($var):
62 109
                return 'numeric_'.(float)$var;
63
            default:
64 9
                return 'scalar_'.$var;
65
        }
66
    }
67
}
68