php parse_ini_file oop & deep

前端 未结 3 1663
囚心锁ツ
囚心锁ツ 2020-12-20 03:47

I would like to make use of somehting like [parse_ini_file][1].

Lets say for instance I have a boot.ini file that I will load for further procedure:



        
3条回答
  •  隐瞒了意图╮
    2020-12-20 04:34

    I got an elegant solution for you. This implementation allows inheritance and vectors using dots as our collegue "zerkms" showed us before. In truth, I took his solution and improved it. Thus the solution be like Zend Parser :) I tested it and works. But, as we know, is impossible test all possibilities. Then, I hope attent people detect troubles and propose corrections.

    Here goes the code (as a function):

    function parse($filename) {
    
            $ini_array = parse_ini_file ( $filename, true );
    
            if (! $ini_array)
                throw new Exception ( 'Error on parsing ini file!', - 1 );
    
            $ini = new stdClass ();
    
            //Parse section...
            foreach ( $ini_array as $namespace => $prop ) {
    
                $section = $namespace;
                $ext = explode ( ':', $namespace );
    
                if (count ( $ext ) == 2) {
    
                    $section = trim ( $ext [0] );
                    $extend = trim ( $ext [1] );
    
                    if (! isset ( $ini->$extend ))
                        throw new Exception ( 'Parent section doesn\'t exists!', - 1 );
    
                    $ini->$section = clone $ini->$extend;
    
                } else
                    $ini->$section = new stdClass ();
    
                foreach ( $prop as $key => $value ) {
    
                    $arr = explode ( '.', $key );
                    $n = count ( $arr ) - 1;
    
                    if ($n) {
                        $aux = $ini->$section;
                        for($i = 0; $i < $n; ++ $i) {
    
                            if(!isset($aux->$arr [$i]))
                                $aux->$arr [$i] = new stdClass ();
    
                            $aux = $aux->$arr [$i];
                        }
                        $aux->$arr [$n] = $value;
                    } else
                        $ini->$section->$key = $value;
    
                }
    
            }
    
            return $ini;
    
    }
    

    And here goes an example of .ini file:

    [environment]
    env_name = production
    x.y = 3

    [oi : environment]
    z = 5

提交回复
热议问题