Passed
Push — main ( 2b8b68...c2075e )
by Anatolyi
05:44
created

SiftedNumberAlgorithm::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 3
c 1
b 0
f 1
dl 0
loc 6
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gambling\Tech;
6
7
class SiftedNumberAlgorithm
8
{
9
    private float $min = 0;
10
11
    private float $max = 100;
12
13
    private string $serverSeed;
14
15
    private string $clientSeed;
16
17
    /**
18
     * @param float $number
19
     * @return int
20
     */
21
    public function __invoke(float $number): int
22
    {
23
        $clientHash = $this->getClientHash($number);
24
        $shiftValue = $this->getShiftValue($clientHash);
25
26
        return $this->shift($number, $shiftValue);
27
    }
28
29
    /**
30
     * @param float $min
31
     * @return $this
32
     */
33
    public function setMin(float $min): self
34
    {
35
        $this->min = $min;
36
37
        return $this;
38
    }
39
40
    /**
41
     * @param float $max
42
     * @return $this
43
     */
44
    public function setMax(float $max): self
45
    {
46
        $this->max = $max;
47
48
        return $this;
49
    }
50
51
    /**
52
     * @param float $number
53
     * @param int $shift
54
     * @return int
55
     */
56
    protected function shift(float $number, int $shift): int
57
    {
58
        if ($shift > $this->max) {
59
            $shift %= ($this->max - $this->min + 1);
60
        }
61
62
        return $number + $shift <= $this->max ?
0 ignored issues
show
Bug Best Practice introduced by
The expression return $number + $shift ...$shift - $this->max - 1 returns the type double which is incompatible with the type-hinted return integer.
Loading history...
63
            $number + $shift :
64
            $this->min + ($number + $shift - $this->max) - 1;
65
    }
66
67
    /**
68
     * @param float $secret
69
     * @return string
70
     */
71
    protected function getClientHash(float $secret): string
72
    {
73
        return hash_hmac('sha256', (string)$secret . $this->serverSeed, $this->clientSeed);
74
    }
75
76
    /**
77
     * @param string $clientHash
78
     * @return int
79
     */
80
    protected function getShiftValue(string $clientHash): int
81
    {
82
        return (int)hexdec(substr($clientHash, -5));
83
    }
84
}
85