Passed
Push — master ( e76d90...348fca )
by Smoren
02:26
created

UniqueExtractor   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 69.57%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 25
c 1
b 0
f 1
dl 0
loc 48
ccs 16
cts 23
cp 0.6957
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 169
    public static function getString($var, bool $strict): string
40
    {
41
        switch (true) {
42 169
            case is_array($var):
43 16
                return 'array_'.serialize($var);
44 153
            case is_resource($var):
45 16
                preg_match('/#([0-9]+)$/', (string)$var, $matches);
46 16
                return 'resource_'.$matches[1];
47 137
            case $var instanceof Generator:
48 16
                return 'generator_'.spl_object_id($var);
49 121
            case $var instanceof Closure:
50 16
                return 'closure_'.spl_object_id($var);
51 105
            case is_object($var):
52 16
                return 'object_'.($strict ? spl_object_id($var) : serialize($var));
53 89
            case gettype($var) === 'boolean':
54 32
                return 'boolean_'.(int)$var;
55 69
            case $strict:
56 69
                return gettype($var).'_'.$var;
57
            case !$var:
58
                return 'boolean_0';
59
            case strval($var) === '1':
60
                return 'boolean_1';
61
            case is_numeric($var):
62
                return 'numeric_'.(float)$var;
63
            default:
64
                return 'scalar_'.$var;
65
        }
66
    }
67
}
68