Completed
Push — master ( c091a3...52a46f )
by Petrică
02:24
created

ConfigLoader::load()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 31
ccs 0
cts 26
cp 0
rs 8.439
cc 5
eloc 18
nc 5
nop 0
crap 30
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Petrica
5
 * Date: 3/26/2016
6
 * Time: 1:23
7
 */
8
namespace Petrica\StatsdSystem\Config;
9
10
use Petrica\StatsdSystem\Config\Definition\ConfigDefinition;
11
use Symfony\Component\Config\Definition\Processor;
12
use Symfony\Component\Yaml\Parser;
13
14
class ConfigLoader
15
{
16
    /**
17
     * Filepath to Yaml configuration file
18
     * @var String
19
     */
20
    private $filepath;
21
22
    /**
23
     * ConfigLoader constructor.
24
     * @param $filepath
25
     */
26
    public function __construct($filepath)
27
    {
28
        $this->filepath = $filepath;
29
    }
30
31
    /**
32
     * Process configuration and make sure the configuration format is as expected
33
     *
34
     * @return array
35
     */
36
    public function load()
37
    {
38
        if (file_exists($this->filepath) && ($contents = file_get_contents($this->filepath))) {
39
            $yaml = new Parser();
40
            $config = $yaml->parse($contents);
41
42
            if (null === $config) {
43
                $config = array();
44
            }
45
46
            $processor = new Processor();
47
            $configDefinition = new ConfigDefinition();
48
            $processedConfiguration = $processor->processConfiguration(
49
                $configDefinition,
50
                $config
51
            );
52
53
            if (empty($processedConfiguration)) {
54
                throw new Exception(
55
                    'You need to specify at least one gaguge in the configuration file'
56
                );
57
            }
58
59
            return $processedConfiguration;
60
        }
61
        else {
62
            throw new \RuntimeException(sprintf('Configuration file does not exist or is not accessible %s',
63
                $this->filepath));
64
        }
65
66
    }
67
}
68