Config::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Psecio\Invoke;
4
5
class Config
6
{
7
	/**
8
	 * Current configuration settings
9
	 * @var array
10
	 */
11
	private $config = array();
12
13
	/**
14
	 * Init the object and set the path
15
	 * 	Loading happens by default unless second param is false
16
	 *
17
	 * @param string $path Path to configuration file
18
	 * @param boolean $load Turn autoloading on/off [optional]
19
	 */
20
	public function __construct($path, $load = true)
21
	{
22
		$this->setPath($path);
23
		if ($load === true) {
24
			$this->load();
25
		}
26
	}
27
28
	/**
29
	 * Set the path to the configuration file
30
	 *
31
	 * @param string $path Configuration file path
32
	 */
33
	public function setPath($path)
34
	{
35
		if (!is_file($path)) {
36
			throw new \InvalidArgumentException('Invalid path: '.$path);
37
		}
38
		$this->path = $path;
0 ignored issues
show
Bug introduced by
The property path does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
39
	}
40
41
	/**
42
	 * Get the current path setting
43
	 *
44
	 * @return string Path to current configuration file
45
	 */
46
	public function getPath()
47
	{
48
		return $this->path;
49
	}
50
51
	/**
52
	 * Load the configuration data into the object
53
	 * 	from the defined YAML file
54
	 *
55
	 * @return array Set of configuration data
56
	 */
57
	public function load()
58
	{
59
		$yaml = new \Symfony\Component\Yaml\Parser();
60
	    $config = $yaml->parse(file_get_contents($this->path));
61
62
	    foreach ($config as $route => $setup) {
63
	        $this->config[$route] = new \Psecio\Invoke\RouteContainer($route, $setup);
64
	    }
65
	    return $this->config;
66
	}
67
68
	/**
69
	 * Get the current configuration data
70
	 * 	Optionally, if a key is provided and set, onyl that value is returned
71
	 *
72
	 * @param string $key Configuration key to locate [optional]
73
	 * @return array|string All config data or just key if found
74
	 */
75
	public function getConfig($key = null)
76
	{
77
		return ($key !== null && isset($this->config[$key]))
78
			? $this->config[$key] : $this->config;
79
	}
80
}