Passed
Push — main ( 4bfbca...f41f09 )
by Thomas
03:11
created

Config::validateApp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Conia\Chuck;
6
7
use Closure;
8
use Conia\Chuck\Exception\OutOfBoundsException;
9
use Conia\Chuck\Exception\ValueError;
10
use Psr\Log\LoggerInterface;
11
use Throwable;
12
13
class Config
14
{
15
    public const DEFAULT = 'default';
16
17
    /** @var null|Closure():LoggerInterface */
18
    protected ?Closure $loggerCallback = null;
19
    protected ?LoggerInterface $logger = null;
20
21
    /**
22
     * @param array<never, never>|array<string, mixed> -- Stores additional user defined settings
23
     */
24 117
    public function __construct(
25
        public readonly string $app,
26
        public readonly bool $debug = false,
27
        public readonly string $env = '',
28
        protected array $settings = [],
29
    ) {
30 117
        $this->validateApp($app);
31
    }
32
33 1
    public function set(string $key, mixed $value): void
34
    {
35 1
        $this->settings[$key] = $value;
36
    }
37
38 1
    public function has(string $key): bool
39
    {
40 1
        return array_key_exists($key, $this->settings);
41
    }
42
43 3
    public function get(string $key, mixed $default = null): mixed
44
    {
45
        try {
46 3
            return $this->settings[$key];
47 2
        } catch (Throwable) {
48 2
            if (func_num_args() > 1) {
49 1
                return $default;
50
            }
51
52 1
            throw new OutOfBoundsException(
53 1
                "The configuration key '{$key}' does not exist"
54 1
            );
55
        }
56
    }
57
58 16
    public function app(): string
59
    {
60 16
        return $this->app;
61
    }
62
63 5
    public function debug(): bool
64
    {
65 5
        return $this->debug;
66
    }
67
68 2
    public function env(): string
69
    {
70 2
        return $this->env;
71
    }
72
73 117
    protected function validateApp(string $app): void
74
    {
75 117
        if (!preg_match('/^[a-z0-9_$-]{1,64}$/', $app)) {
76 1
            throw new ValueError(
77 1
                'The app name must be a nonempty string which consist only of lower case ' .
78 1
                    'letters and numbers. Its length must not be longer than 32 characters.'
79 1
            );
80
        }
81
    }
82
}
83