Passed
Pull Request — main (#1)
by Anatolyi
10:58
created

SeedPairGenerator::getCurrentSeedPairOrGenerate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gambling\Tech\Game;
6
7
use Gambling\Tech\Random;
8
use Gambling\Tech\Exception\GamblingTechException;
9
use Gambling\Tech\Exception\InvalidArgumentException;
10
11
class SeedPairGenerator
12
{
13
    private StoreInterface $store;
14
15
    public function __construct(StoreInterface $store)
16
    {
17
        $this->store = $store;
18
    }
19
20
    /**
21
     * Generation new random seed pair
22
     *
23
     * @param string|null $clientSeed
24
     * @param SeedPair|null $seedPair
25
     * @return SeedPair
26
     * @throws GamblingTechException
27
     * @throws InvalidArgumentException
28
     */
29
    public function generate(?string $clientSeed = null, ?SeedPair $seedPair = null): SeedPair
30
    {
31
        $serverSeed = $seedPair !== null ? $seedPair->getNextServerSeed() : hash('sha256', Random::getString(32));
32
33
        $nextServerSeed = hash('sha256', Random::getString(32));
34
35
        if ($clientSeed === null) {
36
            $clientSeed = $seedPair ?
37
                $seedPair->getClientSeed() :
38
                Random::getString(16, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
39
        }
40
41
        $nonce = 1; // each new generation resets nonce
42
43
        return $this->createSeedPair($serverSeed, $nextServerSeed, $clientSeed, $nonce);
44
    }
45
46
    /**
47
     * Get current seed pair or generation new random seed pair
48
     *
49
     * @param object $condition
50
     * @return SeedPair
51
     * @throws GamblingTechException
52
     * @throws InvalidArgumentException
53
     */
54
    public function getCurrentSeedPairOrGenerate(object $condition): SeedPair
55
    {
56
        if ($seed = $this->getCurrentSeedPair($condition)) {
57
            return $seed;
58
        }
59
60
        return $this->generate();
61
    }
62
63
    /**
64
     * Get the current active seed by an arbitrary condition
65
     *
66
     * @param object $condition
67
     * @return SeedPair|null
68
     */
69
    public function getCurrentSeedPair(object $condition): ?SeedPair
70
    {
71
        return $this->store->getCurrentSeedPair($condition);
72
    }
73
74
    /**
75
     * @param string $serverSeed
76
     * @param string $nextServerSeed
77
     * @param string $clientSeed
78
     * @param int $nonce
79
     * @return SeedPair
80
     */
81
    protected function createSeedPair(
82
        string $serverSeed,
83
        string $nextServerSeed,
84
        string $clientSeed,
85
        int $nonce
86
    ): SeedPair {
87
        return new SeedPair($serverSeed, $nextServerSeed, $clientSeed, $nonce);
88
    }
89
}
90