OptionalParam::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use Override;
8
use Ray\Di\InjectorInterface;
9
10
use function ltrim;
11
use function preg_replace;
12
use function strtolower;
13 19
14
/** @template T */
15 19
final class OptionalParam implements ParamInterface
16 19
{
17
    /** @param T $defaultValue */
18
    public function __construct(
19
        private $defaultValue,
20
    ) {
21 19
    }
22
23 19
    /**
24 19
     * {@inheritDoc}
25 10
     */
26
    #[Override]
27
    public function __invoke(string $varName, array $query, InjectorInterface $injector)
28 9
    {
29
        unset($injector);
30
        if (isset($query[$varName])) {
31
            return $query[$varName];
32
        }
33
34
        // try camelCase variable name
35
        $snakeName = ltrim(strtolower((string) preg_replace('/[A-Z]/', '_\0', $varName)), '_');
36
37
        return $query[$snakeName] ?? $this->defaultValue;
38
    }
39
}
40