Completed
Push — master ( adc131...6e9eb4 )
by Kevin
03:32
created

NumericGenerator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 66
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A generateRandomValue() 0 13 6
A bigRandomNumber() 0 5 1
1
<?php
2
namespace DBFaker\Generators;
3
4
5
use DBFaker\Exceptions\UnsupportedDataTypeException;
6
use Doctrine\DBAL\Schema\Column;
7
use Doctrine\DBAL\Types\Type;
8
use Faker\Factory;
9
use Faker\Generator;
10
11
class NumericGenerator extends UniqueAbleGenerator
12
{
13
14
    /**
15
     * @var mixed
16
     */
17
    private $min;
18
    /**
19
     * @var mixed
20
     */
21
    private $max;
22
    /**
23
     * @var Column
24
     */
25
    private $column;
26
27
    /**
28
     * @var Generator
29
     */
30
    private $faker;
31
32
    /**
33
     * NumericGenerator constructor.
34
     * @param Column $column
35
     * @param mixed $min
36
     * @param mixed $max
37
     * @param bool $generateUniqueValues
38
     */
39
    public function __construct(Column $column, $min, $max, $generateUniqueValues = false)
40
    {
41
        parent::__construct($column, $generateUniqueValues);
42
        $this->faker = Factory::create();
43
        $this->min = $min;
44
        $this->max = $max;
45
        $this->column = $column;
46
    }
47
48
    /**
49
     * @param Column $column
50
     * @return int|string|float
51
     * @throws \Exception
52
     */
53
    protected function generateRandomValue(Column $column)
54
    {
55
        switch ($column->getType()->getName()){
56
            case Type::BIGINT:
57
                return $this->bigRandomNumber();
58
            case Type::INTEGER:
59
            case Type::SMALLINT:
60
                return random_int($this->min, $this->max);
61
            case Type::DECIMAL:
62
            case Type::FLOAT:
63
                return $this->faker->randomFloat(10, $this->min, $this->max);
64
            default:
65
                throw new UnsupportedDataTypeException("Cannot generate numeric value for Type : '".$column->getType()->getName()."'");
66
        }
67
    }
68
69
    /**
70
     * @return string
71
     */
72
    private function bigRandomNumber() : string
73
    {
74
        $difference   = bcadd(bcsub($this->max,$this->min),"1");
75
        $rand_percent = bcdiv((string) mt_rand(), (string) mt_getrandmax(), 8); // 0 - 1.0
76
        return bcadd($this->min, bcmul($difference, $rand_percent, 8), 0);
77
    }
78
79
}