<?php

class Serenity_Config_Parser_Ini
{
    public function parse($contents, $file)
    {
        $data = parse_ini_file((string) $file, true);
        if ($data === false) {
            return null;
        }

        $result = new stdClass();
        foreach ($data as $section => $sectionData) {
            // Inherit parent section(s).
            $parents = explode(':', $section);
            $section = trim(array_shift($parents));
            foreach ($parents as $parent) {
                $data[$section] = $sectionData += $data[trim($parent)];
            }

            $result->$section = new stdClass();
			$replaces = array("/^'/", "/'$/");
            foreach ($sectionData as $key => $value) {
                $parts = explode('.', $key);
                $partsNum = count($parts);
                $pointer = &$result->$section;

                foreach ($parts as $index => $part) {
                    if ($index == $partsNum - 1) {
                        $pointer->$part = preg_replace($replaces, '', $value);
                    } else {
                        if (!property_exists($pointer, $part)) {
                            $pointer->$part = new stdClass();
                        }

                        $pointer = &$pointer->$part;
                    }
                }
            }
        }

        return $result;
    }
}
