NumericGenerator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Importance

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