Util::arrayGet()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 3
eloc 2
nc 4
nop 3
1
<?php
2
3
4
namespace Feature;
5
6
/**
7
 * Class Util
8
 * @package Feature
9
 */
10
class Util
11
{
12
    /**
13
     * @return float
14
     */
15
    public static function random()
16
    {
17
        return mt_rand(0, mt_getrandmax() - 1) / mt_getrandmax();
18
    }
19
20
    /**
21
     * @param $id
22
     * @return float
23
     */
24
    public static function randomById($id)
25
    {
26
        return static::mapHex(hash('sha256', $id));
0 ignored issues
show
Bug introduced by Prasetyo
Since mapHex() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of mapHex() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
27
    }
28
29
    /**
30
     * @param array $array
31
     * @param string $key
32
     * @param null|mixed $default
33
     * @return null|mixed
34
     */
35
    public static function arrayGet(array $array, $key, $default = null)
36
    {
37
        return is_array($array) && array_key_exists($key, $array) ? $array[$key] : $default;
38
    }
39
40
    /**
41
     * @param string $hex
42
     * @return float
43
     */
44
    private static function mapHex($hex)
45
    {
46
        $len = min(40, strlen($hex));
47
        $vMax = 1 << $len;
48
        $v = 0;
49
        for ($i = 0; $i < $len; $i++) {
50
            $bit = hexdec($hex[$i]) < 8 ? 0 : 1;
51
            $v = ($v << 1) + $bit;
52
        }
53
        $w = $v / $vMax;
54
        return $w;
55
    }
56
}
57