Decoder.php

<?php

namespace ROF\Resource;

class Decoder {

    public function parseString($string,$type='rof'){
        if ($type=='rof'){
            $string = "\n".$string;
            $token = new ROFToken('beforeParam',$string);
            $data = $token->asArray();
            $nested = $this->decodeFlatData($data);
            return $nested;
        } else if ($type=='json'){
            return json_decode($string,TRUE);
        } else {
            throw new \Exception("Type '{$type}' could not be parsed");
        }
    }
    public function parseFile($file){
        $ext = pathinfo($file,PATHINFO_EXTENSION);
        $data = $this->parseString(file_get_contents($file),$ext);
        if ($ext=='rof'){
            // var_dump($data);
            // exit;
        }
        return $data;
    }

    public function decodeFlatData($data){
        // $hierarchy = new \stdClass;
        // $hierarchy->name = null;
        // $hierarchy->child = null;
        // ['Mz.cats.something' => 'fromg'];
        // ['mz'=>
        //     ['cats'=>
        //         ['something'=>'fromg']
        //     ]
        // ];
        $array = [];
        // $array[$parts[0]] = [$parts[1]=>[$parts[2]=>$value];
        // $all = []
        $all = [];
        foreach ($data as $lookupString=>$value){
            $array = [];
            $next = &$array;
            $parts = explode('.',$lookupString);
            foreach ($parts as $key){
                $next = [$key=>[]];
                $next = &$next[$key];
            }
            $next = $value;
            $null = null;
            $next = &$null;
            $all = array_merge_recursive($all,$array);
        }
        return $all;
        // return $token->asArray();
    }
    public function rofDecodeFile($file){
        $data = $this->parseString(file_get_contents($file),'rof');
        return $this->decodeFlatData($data);
        
    }

    public function jsonDecode($file){

        return json_decode(file_get_contents($file),TRUE);;
    }
}