Passed
Push — master ( 4bca98...db059b )
by James
03:07
created

Config   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A sanitize() 0 12 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
class Config extends ArrayObject
10
{
11
    /**
12
     * Construct a new config
13
     *
14
     * @param  string  $filename
15
     * @return void
16
     */
17 2
    public function __construct(array $input = [])
18
    {
19 2
        parent::__construct($input + [
20
            // 'workdir' => getcwd(),
21 2
            'port' => 9501,
22
            'events' => [],
23
        ]);
24 2
        $this->sanitize();
25 1
    }
26
27
    /**
28
     * load config.yaml
29
     *
30
     * @param  string  $filename
31
     * @return void
32
     */
33 1
    public function loadYaml(string $filename)
34
    {
35 1
        $config = Yaml::parseFile($filename);
36 1
        $this->exchangeArray($config + $this->getArrayCopy());
37 1
        $this->sanitize();
38 1
    }
39
40
    /**
41
     * Sanitize config values.
42
     * 
43
     * @return void
44
     * 
45
     * @throws \InvalidArgumentException
46
     */
47 2
    private function sanitize(): void
48
    {
49
        // Well-known ports: 0 to 1023
50
        // Registered/user ports: 1024 to 49151
51
        // Dynamic/private ports: 49152 to 65535
52 2
        $port = filter_var($this['port'], FILTER_VALIDATE_INT, [
53 2
            'options' => ['min_range' => 0, 'max_range' => 49151]
54
        ]);
55 2
        if ($port === false) {
56 1
            throw new InvalidArgumentException('Invalid port: '.$this['port'].'.', 1001);
57
        }
58 1
        $this['port'] = $port;
59
    }
60
}