Random   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 5
c 1
b 0
f 1
lcom 0
cbo 2
dl 0
loc 48
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 8 2
A createFromState() 0 17 3
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')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
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')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
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