Context::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 9.9
c 1
b 0
f 0
cc 4
nc 4
nop 1
crap 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Level23\Druid\Context;
5
6
use InvalidArgumentException;
7
8
abstract class Context
9
{
10
    /**
11
     * @var array<string,string|int|bool>
12
     */
13
    protected array $properties = [];
14
15
    /**
16
     * Context constructor.
17
     *
18
     * @param array<string,string|int|bool> $properties
19
     */
20 65
    public function __construct(array $properties = [])
21
    {
22 65
        foreach ($properties as $key => $value) {
23
24 35
            $method = 'set' . $key;
25
26 35
            if (!is_scalar($value)) {
27 1
                throw new InvalidArgumentException(
28 1
                    'Invalid value ' . var_export($value, true) .
29 1
                    ' for ' . $key . ' in ' . __CLASS__
30 1
                );
31
            }
32
33 34
            $callable = [$this, $method];
34 34
            if (!is_callable($callable)) {
35
                // From now on, we support setting properties where no setters are defined for.
36
                // This is because the context settings can vary per version. In this way we can support new
37
                // non-existing properties.
38 2
                $this->properties[$key] = $value;
39 2
                continue;
40
            }
41
42 32
            call_user_func($callable, $value);
43
        }
44
    }
45
46
    /**
47
     * Return the context as it can be used in the druid query.
48
     *
49
     * @return array<string,string|int|bool>
50
     */
51 32
    public function toArray(): array
52
    {
53 32
        return $this->properties;
54
    }
55
}