DecimalGuesser::determineMaxValue()   A
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 20
rs 9.2222
cc 6
nc 9
nop 1
1
<?php
2
3
namespace Knp\FriendlyContexts\Guesser;
4
5
class DecimalGuesser extends AbstractGuesser implements GuesserInterface
6
{
7
    public function supports(array $mapping)
8
    {
9
        $mapping = array_merge([ 'type' => null ], $mapping);
10
11
        return in_array($mapping['type'], [ 'decimal', 'float' ]);
12
    }
13
14
    public function transform($str, array $mapping = null)
15
    {
16
        return (float) $str;
17
    }
18
19
    public function fake(array $mapping)
20
    {
21
        $maxNumOfDecimals = $this->determineMaxNumOfDecimals($mapping);
22
        $min = 0;
23
        $max = $this->determineMaxValue($mapping);
24
25
        return current($this->fakers)->fake('randomFloat', [$maxNumOfDecimals, $min, $max]);
26
    }
27
28
    /**
29
     * @param array $mapping
30
     *
31
     * @return int|null
32
     */
33
    private function determineMaxNumOfDecimals(array $mapping)
34
    {
35
        if (isset($mapping['scale'])) {
36
            return $mapping['scale'];
37
        }
38
39
        if (isset($mapping['precision'])) {
40
            return 0;
41
        }
42
43
        return null;
44
    }
45
46
    /**
47
     * @param array $mapping
48
     *
49
     * @return float|null
50
     */
51
    private function determineMaxValue(array $mapping)
52
    {
53
        if (!isset($mapping['precision']) && !isset($mapping['scale'])) {
54
            return null;
55
        }
56
57
        $scale = isset($mapping['scale']) ? (int)$mapping['scale'] : 0;
58
        $precision = isset($mapping['precision']) ? (int)$mapping['precision'] : 0;
59
        if ($precision < $scale) {
60
            $precision = $scale;
61
        }
62
63
        $maxValueStr = (int)str_repeat('9', $precision);
64
        $integerPartLength = $precision - $scale;
65
66
        $fractionalPart = substr($maxValueStr, 0, $integerPartLength);
67
        $integerPart = substr($maxValueStr, $integerPartLength);
68
        $maxValue = (float)"$fractionalPart.$integerPart";
69
70
        return $maxValue;
71
    }
72
73
    public function getName()
74
    {
75
        return 'decimal';
76
    }
77
}
78