fix bug with expected class type
[m6w6/merry] / lib / merry / Config.php
1 <?php
2
3 /**
4 * merry\Config
5 *
6 * @author Michael Wallner <mike@php.net>
7 */
8 namespace merry;
9
10 /**
11 * A merry config container
12 *
13 * @see https://github.com/m6w6/merry
14 * @package merry\Config
15 */
16 class Config extends Container
17 {
18 /**
19 * Create a new configuration container
20 * @param array $array the configuration array
21 * @param string $section the section to use (i.e. first level key)
22 * @param string $section_sep a separator for section extension
23 * @param string $key_sep a separator for key traversal
24 */
25 public function __construct(array $array = null, $section = null, $section_sep = ":", $key_sep = ".") {
26 if (isset($section) && strlen($section_sep)) {
27 $array = $this->combine($array, $section_sep)[$section];
28 }
29 if ($array) {
30 $config = array();
31
32 if (strlen($key_sep)) {
33 foreach ($array as $key => $val) {
34 $this->walk($config, $key, $val, $key_sep);
35 }
36 }
37 parent::__construct($config, false);
38 }
39 }
40
41 /**
42 * Combine individual sections with their parent section
43 * @param array $array the config array
44 * @param string $section_sep the section extension separator
45 * @return array merged sections
46 */
47 protected function combine($array, $section_sep) {
48 foreach ($array as $section_spec => $settings) {
49 $section_spec = array_map("trim", explode($section_sep, $section_spec));
50 if (count($section_spec) > 1) {
51 $sections[$section_spec[0]] = array_merge(
52 $sections[$section_spec[1]],
53 $settings
54 );
55 } else {
56 $sections[$section_spec[0]] = $settings;
57 }
58 }
59 return $sections;
60 }
61
62 /**
63 * Walk a key split by the key separator into an array up and set the
64 * respective value on the leaf
65 * @param mixed $ptr current leaf pointer in the array
66 * @param string $key the array key
67 * @param mixed $val the value to set
68 * @param string $key_sep the key separator for traversal
69 */
70 protected function walk(&$ptr, $key, $val, $key_sep) {
71 foreach (explode($key_sep, $key) as $sub) {
72 $ptr = &$ptr[$sub];
73 }
74 $ptr = $val;
75 }
76 }
77
78 /* vim: set noet ts=4 sw=4: */