ShiftedNumber::shift()   B
last analyzed

Complexity

Conditions 8
Paths 40

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 12
nc 40
nop 2
dl 0
loc 20
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gambling\Tech;
6
7
/**
8
 * Base value shifting by hash
9
 */
10
class ShiftedNumber
11
{
12
    private int $min = 0;
13
14
    private int $max = 100;
15
16
    /**
17
     * @param float $number
18
     * @param string $hash
19
     * @return int
20
     */
21
    public function __invoke(float $number, string $hash): int
22
    {
23
        $shiftValue = $this->getShiftValue($hash);
24
25
        return (int)$this->shift($number, $shiftValue);
26
    }
27
28
    /**
29
     * @param int $min
30
     * @return $this
31
     */
32
    public function setMin(int $min): self
33
    {
34
        $this->min = $min;
35
36
        return $this;
37
    }
38
39
    /**
40
     * @param int $max
41
     * @return $this
42
     */
43
    public function setMax(int $max): self
44
    {
45
        $this->max = $max;
46
47
        return $this;
48
    }
49
50
    /**
51
     * @param float $number
52
     * @param int $shift
53
     * @return float
54
     */
55
    protected function shift(float $number, int $shift): float
56
    {
57
        if ($shift > $this->max) {
58
            $shift %= ($this->max - $this->min + 1);
59
        }
60
61
        $shift = $shift === 0 ? (int)(7 / 100 * $this->max) : $shift;
62
63
        $result = $number + $shift <= $this->max ?
64
            $number + $shift :
65
            $this->min + ($number + $shift - $this->max) - 1;
66
67
        if ($result < $this->min || $result > $this->max) {
68
            $float = round(($this->min / ($this->max + 1)) + M_PI, 5);
69
            $percent = (int)mb_substr((string)$float, -2, 2);
70
            $result = ($this->min === 0 ? $this->max / 2 : $this->min) + ($percent / 100 * $this->min);
71
            $result = $result > $this->max ? $this->max : $result;
72
        }
73
74
        return $result;
75
    }
76
77
    /**
78
     * @param string $hash
79
     * @return int
80
     */
81
    protected function getShiftValue(string $hash): int
82
    {
83
        if (preg_match("/^([a-f0-9])$/", $hash) === 0) {
84
            $hash = sha1($hash);
85
        }
86
87
        return (int)hexdec(mb_substr($hash, -5));
88
    }
89
}
90