Passed
Push — master ( 42cc05...b677af )
by duan
01:52
created

Zval::getRefCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
4
namespace Yiranzai\Tools;
5
6
/**
7
 * Class Zval
8
 * @package Yiranzai\Tools
9
 */
10
class Zval
11
{
12
    /**
13
     * @param $var
14
     * @return bool
15
     */
16
    public static function isRef($var): bool
17
    {
18
        $info = self::getZvalRefCountInfo($var);
19
        return (boolean)$info['is_ref'];
20
    }
21
22
    /**
23
     * @param $var
24
     * @return mixed
25
     */
26
    public static function getRefCount($var)
27
    {
28
        $info = self::getZvalRefCountInfo($var);
29
        return $info['refcount'];
30
    }
31
32
    /**
33
     * @param $var
34
     * @return bool
35
     */
36
    public static function canCopyOnWrite($var): bool
37
    {
38
        $info = self::getZvalRefCountInfo($var);
39
        return $info['is_ref'] === 0;
40
    }
41
42
    /**
43
     * @param $var
44
     * @return bool
45
     */
46
    public static function canReferenceWithoutCopy($var): bool
47
    {
48
        $info = self::getZvalRefCountInfo($var);
49
        return $info['is_ref'] === 1 || $info['refcount'] === 1;
50
    }
51
52
    /**
53
     * @param $var
54
     * @return array
55
     */
56
    public static function getZvalRefCountInfo($var): array
57
    {
58
        ob_start();
59
        xdebug_debug_zval($var);
60
        $info = ob_get_clean();
61
        preg_match('(: \(refcount=(\d+), is_ref=(\d+)\))', $info, $match);
62
        return array('refcount' => (int)$match[1], 'is_ref' => (int)$match[2]);
63
    }
64
65
    /**
66
     * @param $a
67
     * @param $b
68
     * @return bool
69
     */
70
    public static function isRefto(&$a, &$b): bool
71
    {
72
        if ($a !== $b) {
73
            return false;
74
        }
75
        $t = $a;
76
        if ($r = ($b === ($a = 1))) {
77
            $r = ($b === ($a = 0));
78
        }
79
        $a = $t;
80
        return $r;
81
    }
82
83
    /**
84
     * @param $a
85
     * @param $b
86
     * @return bool
87
     */
88
    public static function isReferenceOf(&$a, &$b): bool
89
    {
90
        if (!self::isRef('a') || self::getZvalRefCountInfo('a') !== self::getZvalRefCountInfo('b')) {
91
            return false;
92
        }
93
        $tmp = $a;
94
        if (is_object($a) || is_array($a)) {
95
            $a   = 'test';
96
            $ret = $b === 'test';
97
            $a   = $tmp;
98
        } else {
99
            $a   = [];
100
            $ret = $b === [];
101
            $a   = $tmp;
102
        }
103
        return $ret;
104
    }
105
}
106