Passed
Push — main ( e0645a...0cadd9 )
by Anatolyi
05:26
created

ShiftedNumber::shift()   B

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