1 | <?php |
||
5 | class DecimalGuesser extends AbstractGuesser implements GuesserInterface |
||
6 | { |
||
7 | public function supports(array $mapping) |
||
13 | |||
14 | public function transform($str, array $mapping = null) |
||
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() |
||
77 | } |
||
78 |
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.