1<?php
2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
3//
4// All Rights Reserved. See copyright.txt for details and a complete list of authors.
5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6// $Id$
7
8class Tiki_Config_Ini extends Zend\Config\Reader\Ini
9{
10
11	const SECTION_SEPARATOR = ':';
12	const SECTION_EXTENDS_KEY = ';extends';
13
14	protected $filterSection = null;
15
16	public function setFilterSection($filter)
17	{
18		$this->filterSection = $filter;
19	}
20
21	/**
22	 * Process data from the parsed ini file.
23	 *
24	 * @param  array $data
25	 * @return array
26	 */
27	protected function process(array $data)
28	{
29		$data = $this->preProcessSectionInheritance($data);
30		$config = parent::process($data);
31		$config = $this->posProcessSectionInheritance($config);
32
33		if (! is_null($this->filterSection)) {
34			if (array_key_exists($this->filterSection, $config)) {
35				return $config[$this->filterSection];
36			} else {
37				return [];
38			}
39		}
40
41		return $config;
42	}
43
44	protected function preProcessSectionInheritance(array $data)
45	{
46		$result = [];
47
48		foreach ($data as $key => $value) {
49			$tokens = explode(self::SECTION_SEPARATOR, $key);
50			$section = trim($tokens[0]);
51			if (count($tokens) == 2 && is_array($value)) {
52				$value[self::SECTION_EXTENDS_KEY] = trim($tokens[1]);
53			}
54			$result[$section] = $value;
55		}
56		return $result;
57	}
58
59	protected function posProcessSectionInheritance(array $config)
60	{
61		$result = [];
62
63		foreach ($config as $key => $value) {
64			if (is_array($value) && array_key_exists(self::SECTION_EXTENDS_KEY, $value)) {
65				$value = $this->resolveSectionInheritance($config, $key);
66			}
67			$result[$key] = $value;
68		}
69		return $result;
70	}
71
72	protected function resolveSectionInheritance($config, $section)
73	{
74		$result = [];
75
76		if (array_key_exists(self::SECTION_EXTENDS_KEY, $config[$section])) {
77			$parentSection = $config[$section][self::SECTION_EXTENDS_KEY];
78			unset($config[$section][self::SECTION_EXTENDS_KEY]);
79			$result = $this->resolveSectionInheritance($config, $parentSection);
80		}
81		$result = array_replace_recursive($result, $config[$section]);
82
83		return $result;
84	}
85}
86