Passed
Push — master ( fa224c...2f97ae )
by Бабичев
01:45
created

Filter::__callStatic()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 8
cp 0
rs 9.3142
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 2
crap 6
1
<?php
2
3
namespace Bavix\Slice;
4
5
use Bavix\Exceptions\Invalid;
6
7
/**
8
 * Class Filter
9
 *
10
 * @package Bavix\Slice
11
 *
12
 * @method static int getInt(Slice $slice, $offset)
13
 * @method static float getFloat(Slice $slice, $offset)
14
 * @method static bool getBool(Slice $slice, $offset)
15
 * @method static string getEmail(Slice $slice, $offset)
16
 * @method static string getIP(Slice $slice, $offset)
17
 * @method static string getURL(Slice $slice, $offset)
18
 */
19
class Filter
20
{
21
22
    /**
23
     * @var array
24
     */
25
    protected static $filters = [
26
        'getInt'   => FILTER_VALIDATE_INT,
27
        'getFloat' => FILTER_VALIDATE_FLOAT,
28
        'getBool'  => FILTER_VALIDATE_BOOLEAN,
29
        'getEmail' => FILTER_VALIDATE_EMAIL,
30
        'getIP'    => FILTER_VALIDATE_IP,
31
        'getURL'   => FILTER_VALIDATE_URL
32
    ];
33
34
    /**
35
     * @var array
36
     */
37
    protected static $defaults = [
38
        'getInt'   => 0,
39
        'getFloat' => .0,
40
        'getBool'  => false,
41
        'getEmail' => '',
42
        'getIP'    => '',
43
        'getURL'   => '',
44
    ];
45
46
    /**
47
     * @param mixed $data
48
     * @param mixed $type
49
     * @param mixed $default
50
     *
51
     * @return mixed
52
     */
53
    protected static function filterVariable($data, $type, $default)
54
    {
55
        return \filter_var($data, $type, [
56
            'options' => ['default' => $default]
57
        ]);
58
    }
59
60
    /**
61
     * @param $name
62
     * @param $arguments
63
     *
64
     * @return mixed
65
     *
66
     * @throws \BadFunctionCallException
67
     */
68
    public static function __callStatic($name, $arguments)
69
    {
70
71
        if (empty(static::$filters[$name]))
72
        {
73
            throw new Invalid('Filter `' . $name . '` not found');
74
        }
75
76
        /**
77
         * @var Slice  $slice
78
         * @var string $offset
79
         */
80
        list ($slice, $offset) = $arguments;
81
82
        return static::filterVariable(
83
            $slice->getData($offset),
84
            static::$filters[$name],
85
            static::$defaults[$name]
86
        );
87
88
    }
89
90
}
91