SingleParameter   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 17
c 1
b 0
f 0
dl 0
loc 35
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A filter() 0 9 2
A __construct() 0 8 3
1
<?php
2
3
namespace Jasny\Controller\Parameter;
4
5
abstract class SingleParameter implements Parameter
6
{
7
    public static array $types = [
8
        'bool' => [FILTER_VALIDATE_BOOL],
9
        'int' => [FILTER_VALIDATE_INT],
10
        'float' => [FILTER_VALIDATE_FLOAT],
11
        'email' => [FILTER_VALIDATE_EMAIL],
12
        'url' => [FILTER_VALIDATE_URL],
13
    ];
14
15
    public ?string $key;
16
    public ?string $type;
17
18
    public function __construct(?string $key = null, ?string $type = null)
19
    {
20
        if ($type !== null && !isset(self::$types[$type])) {
21
            throw new \DomainException("Undefined parameter type '$type'");
22
        }
23
24
        $this->key = $key;
25
        $this->type = $type;
26
    }
27
28
    /**
29
     * Apply sanitize filter to value.
30
     */
31
    protected function filter(mixed $value, ?string $type): mixed
32
    {
33
        if ($value === null) {
34
            return null;
35
        }
36
37
        [$filter, $options] = (self::$types[$type ?? ''] ?? []) + [FILTER_DEFAULT, 0];
38
39
        return filter_var($value, $filter, $options);
40
    }
41
}
42