Config   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 16
c 1
b 0
f 0
dl 0
loc 57
ccs 18
cts 18
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A sanitize() 0 13 2
A loadYaml() 0 5 1
1
<?php
2
3
namespace App;
4
5
use ArrayObject;
6
use InvalidArgumentException;
7
use Symfony\Component\Yaml\Yaml;
8
9
/**
10
 * Load config with sanitization
11
 */
12
class Config extends ArrayObject
13
{
14
    /**
15
     * Construct a new config
16
     *
17
     * @param array $input Input array
18
     */
19 2
    public function __construct(array $input = [])
20
    {
21 2
        parent::__construct(
22
            $input + [
23
            // 'workdir' => getcwd(),
24 2
                'port'   => 9501,
25
                'events' => []
26
            ]
27
        );
28 2
        $this->sanitize();
29 1
    }
30
31
    /**
32
     * Load config.yaml
33
     *
34
     * @param string $filename The path to the YAML file to be parsed
35
     *
36
     * @return void
37
     */
38 1
    public function loadYaml(string $filename)
39
    {
40 1
        $config = Yaml::parseFile($filename);
41 1
        $this->exchangeArray($config + $this->getArrayCopy());
42 1
        $this->sanitize();
43 1
    }
44
45
    /**
46
     * Sanitize config values
47
     *
48
     * Port:
49
     * - Well-known ports: 0 to 1023
50
     * - Registered/user ports: 1024 to 49151
51
     * - Dynamic/private ports: 49152 to 65535
52
     *
53
     * @return void
54
     * @throws \InvalidArgumentException
55
     */
56 2
    private function sanitize(): void
57
    {
58 2
        $port = filter_var(
59 2
            $this['port'],
60 2
            FILTER_VALIDATE_INT,
61
            [
62 2
                'options' => ['min_range' => 0, 'max_range' => 49151]
63
            ]
64
        );
65 2
        if ($port === false) {
66 1
            throw new InvalidArgumentException('Invalid port: ' . $this['port'] . '.', 1001);
67
        }
68 1
        $this['port'] = $port;
69 1
    }
70
}
71