SingleParameter::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 3
nc 2
nop 2
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