Completed
Push — master ( a4deca...b10287 )
by Ori
01:31
created

src/Fields/NumberField.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
        $isPercent = false;
17
        if (is_string($val)) {
18
            if (substr($val, -1) == '%') {
19
                $val = rtrim($val, '%');
20
                $isPercent = true;
21
            }
22
            if (isset($this->descriptor()->groupChar)) {
23
                $val = str_replace($this->descriptor()->groupChar, '', $val);
24
            }
25
            if (isset($this->descriptor()->decimalChar) && $this->descriptor()->decimalChar != '.') {
26
                $val = str_replace($this->descriptor()->decimalChar, '.', $val);
27
            }
28
            if (isset($this->descriptor()->currency) && $this->descriptor()->currency) {
29
                $newval = '';
30
                foreach (str_split($val) as $chr) {
31
                    if (is_numeric($chr) || $chr == '.' || $chr == '+' || $chr == '-') {
32
                        $newval .= $chr;
33
                    }
34
                }
35
                $val = $newval;
36
            }
37
        }
38 View Code Duplication
        if (!is_numeric($val)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
39
            throw $this->getValidationException('value must be numeric', $val);
40
        } else {
41
            $val = (float) $val;
42
            if ($isPercent) {
43
                $val = $val / 100;
44
            }
45
46
            return $val;
47
        }
48
    }
49
50
    public static function type()
51
    {
52
        return 'number';
53
    }
54
}
55