Completed
Push — 4.0 ( 0bf83a )
by Serhii
03:33
created

YamlLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * @author Serhii Nekhaienko <[email protected]>
4
 * @license GPL
5
 * @copyright Serhii Nekhaienko &copy 2018
6
 * @version 4.0.0
7
 * @project browser-detector
8
 */
9
10
namespace EndorphinStudio\Detector;
11
12
use Symfony\Component\Yaml\Exception\ParseException;
13
use Symfony\Component\Yaml\Parser;
14
15
/**
16
 * Class for loading data from yml files
17
 * @pattern Singleton
18
 * @package EndorphinStudio\Detector
19
 */
20
class YamlLoader
21
{
22
    private $parameters = [];
23
24
    /**
25
     * @throws ParseException
26
     */
27
    public function __construct()
28
    {
29
        $this->load();
30
    }
31
32
    /**
33
     * Load data from yml files into associative array
34
     * @throws ParseException
35
     */
36
    private function load(): void
37
    {
38
        $parameters = [];
39
        $parser = new Parser();
40
        $dataDir = \dirname(__DIR__) . '/var/data/';
41
        foreach (new \DirectoryIterator($dataDir) as $file) {
42
            if ($file->getExtension() === '.yml') {
43
                $data = $parser->parseFile($file->getRealPath());
44
                $parameters = \array_merge($parameters, $data);
45
            }
46
        }
47
        $this->parameters = $parameters;
48
    }
49
50
    /**
51
     * Return list of params (key must be os, device, .etc)
52
     * @param string $name
53
     * @return array
54
     * @throws DetectorException
55
     */
56
    public function getParameter(string $name): array
57
    {
58
        if (!array_key_exists($name, $this->parameters)) {
59
            throw new DetectorException(sprintf('% not exist in data' . $name), 1);
60
        }
61
        return $this->parameters[$name];
62
    }
63
}