1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Savvot\Random; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Static helper class. |
7
|
|
|
* Provides uniform way to create RNG objects from different generators and states |
8
|
|
|
* |
9
|
|
|
* @package Savvot\Random |
10
|
|
|
* @author SavvoT <[email protected]> |
11
|
|
|
*/ |
12
|
|
|
class Random |
13
|
|
|
{ |
14
|
|
|
const MT = '\Savvot\Random\MtRand'; |
15
|
|
|
const XORSHIFT = '\Savvot\Random\XorShiftRand'; |
16
|
|
|
const HASH = '\Savvot\Random\HashRand'; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Creates RNG from specified class and initializes it with given seed |
20
|
|
|
* |
21
|
|
|
* @param string $seed Seed to initialize generator's state. Defaults to null (auto) |
22
|
|
|
* @param string $rngClass Generator's class. Must be the child of AbstractRand. Defaults to XorShiftRand |
23
|
|
|
* @return AbstractRand Newly created PRNG |
24
|
|
|
* @throws RandException if generator class is invalid |
25
|
|
|
*/ |
26
|
|
|
public static function create($seed = null, $rngClass = self::XORSHIFT) |
27
|
|
|
{ |
28
|
|
|
if (!is_subclass_of($rngClass, '\Savvot\Random\AbstractRand')) { |
|
|
|
|
29
|
|
|
throw new RandException('PRNG class must extend AbstractRand'); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
return new $rngClass($seed); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Creates RNG from previously saved state |
37
|
|
|
* |
38
|
|
|
* @param array $state State array created with getState() method |
39
|
|
|
* @return AbstractRand Newly created PRNG |
40
|
|
|
* @throws RandException if specified state is invalid |
41
|
|
|
*/ |
42
|
|
|
public static function createFromState(array $state) |
43
|
|
|
{ |
44
|
|
|
if (!isset($state['class'])) { |
45
|
|
|
throw new RandException('Invalid state'); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$class = $state['class']; |
49
|
|
|
if (!is_subclass_of($class, '\Savvot\Random\AbstractRand')) { |
|
|
|
|
50
|
|
|
throw new RandException('Invalid RNG class in state'); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** @var \Savvot\Random\AbstractRand $prng */ |
54
|
|
|
$prng = new $class; |
55
|
|
|
$prng->setState($state); |
56
|
|
|
|
57
|
|
|
return $prng; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|