Config::__construct()   A
last analyzed

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
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Genkgo\Srvcleaner;
3
4
use stdClass;
5
use Genkgo\Srvcleaner\Exceptions\ConfigurationException;
6
7
/**
8
 * Class Config
9
 * @package Genkgo\Srvcleaner
10
 */
11
class Config
12
{
13
    /**
14
     * @var stdClass
15
     */
16
    private $document;
17
18
    /**
19
     * @param stdClass $document
20
     */
21
    public function __construct(stdClass $document)
22
    {
23
        $this->setDocument($document);
24
    }
25
26
    /**
27
     * @param stdClass $document
28
     */
29
    public function setDocument(stdClass $document)
30
    {
31
        $this->document = $document;
32
    }
33
34
    /**
35
     * @return TaskList
36
     */
37
    public function getTasks()
38
    {
39
        $taskList = new TaskList;
40
41
        if (!isset($this->document->tasks) || !is_array($this->document->tasks)) {
42
            throw new ConfigurationException('No tasks found');
43
        }
44
45
        foreach ($this->document->tasks as $taskJson) {
46
            if (!isset($taskJson->name) || !isset($taskJson->src)) {
47
                throw new ConfigurationException('Task name and src are required');
48
            }
49
50
            $name = $taskJson->name;
51
            $className = $taskJson->src;
52
            $config = $taskJson->config;
53
54
            if (!$name || !$className) {
55
                throw new ConfigurationException('Task name and src cannot be empty');
56
            }
57
58
            if (strpos($className, '\\') === false) {
59
                $className = 'Genkgo\\Srvcleaner\\Tasks\\' . $className;
60
            }
61
62
            if (!class_exists($className)) {
63
                throw new ConfigurationException("Task {$name} not found. Unknown class {$className}");
64
            }
65
66
            $task = new $className ;
67
            if ($task instanceof TaskInterface) {
68
                $task->setConfig($config);
69
                $taskList->add($name, $task);
70
            } else {
71
                throw new ConfigurationException("Task is not implementing TaskInterface");
72
            }
73
        }
74
75
        return $taskList;
76
    }
77
78
    /**
79
     * @param $fileName
80
     * @return Config
81
     */
82
    public static function fromFile($fileName)
83
    {
84
        if (!file_exists($fileName)) {
85
            throw new ConfigurationException('Config file not found');
86
        }
87
88
        $source = file_get_contents($fileName);
89
        $json = json_decode($source);
90
        if ($json === null) {
91
            throw new ConfigurationException('Config is not valid json');
92
        }
93
        return new static ($json);
94
    }
95
}
96