NumberField::validateCastValue()   D
last analyzed

Complexity

Conditions 10
Paths 28

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 19
nc 28
nop 1
dl 0
loc 29
rs 4.8196
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace frictionlessdata\tableschema\Fields;
4
5
class NumberField extends BaseField
6
{
7
    /**
8
     * @param mixed $val
9
     *
10
     * @return float
11
     *
12
     * @throws \frictionlessdata\tableschema\Exceptions\FieldValidationException;
13
     */
14
    protected function validateCastValue($val)
15
    {
16
        if (isset($this->descriptor()->bareNumber) && $this->descriptor()->bareNumber === false) {
17
            return mb_ereg_replace('((^\D*)|(\D*$))', '', $val);
18
        }
19
        $isPercent = false;
20
        if (is_string($val)) {
21
            if (substr($val, -1) == '%') {
22
                $val = rtrim($val, '%');
23
                $isPercent = true;
24
            }
25
            if (isset($this->descriptor()->groupChar)) {
26
                $val = str_replace($this->descriptor()->groupChar, '', $val);
27
            }
28
            if (isset($this->descriptor()->decimalChar) && $this->descriptor()->decimalChar != '.') {
29
                $val = str_replace($this->descriptor()->decimalChar, '.', $val);
30
            }
31
        }
32
        if (!is_numeric($val)) {
33
            throw $this->getValidationException('value must be numeric', $val);
34
        } else {
35
            $val = (float) $val;
36
            if ($isPercent) {
37
                $val = $val / 100;
38
            }
39
40
            return $val;
41
        }
42
    }
43
44
    public static function type()
45
    {
46
        return 'number';
47
    }
48
}
49