FloatFromString.php 877 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
<?php

namespace Application\Filter;

use Zend\Filter\AbstractFilter;

class FloatFromString extends AbstractFilter
{
    private static $instance;


12

13
14
    public function filter($value)
    {
lecluse's avatar
#10705    
lecluse committed
15
16
        if ($value === '') return null;

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
        if (false !== strpos($value, '/')) {
            [$f1, $f2] = explode('/', $value);

            return $this->convert($f1) / $this->convert($f2);
        } else {
            return $this->convert($value);
        }
    }



    protected function convert($value): float
    {
        $value = preg_replace("/[^0-9,\.-]/", "", $value);
        $value = str_replace(',', '.', $value);
32
33
34
35
36
37
38
        $value = floatval($value);

        return $value;
    }



39
    public static function run($value)
40
    {
41
        if (!self::$instance) {
42
43
44
            self::$instance = new self;
        }

45
        return self::$instance->filter($value);
46
47
    }
}