<?php

namespace Heanup\Frame;

/**
 * 配置文件
 */
class Config
{
    protected static $dataFile = ''; // 配置文件目录,绝对路径,json格式,优先使用覆盖$data
    protected static $data = array();

    /**
     * 获取配置信息,
     * 如果配置了$dataFile则读取后者中的数据
     * @param null $section
     * @return mixed
     */
    public static function getData($section = null)
    {
        $class = get_called_class();
        // 只读取一次文件
        if ($class::$dataFile) {
            $path = self::getPathByMode($class::$dataFile);
            $class::$data = self::readFile($path);
            $class::$dataFile = '';
        }
        $data = $class::$data;
        if (!is_null($section)) {
            if (isset($data[$section])) {
                return $data[$section];
            } else {
                return null;
            }
        }
        return $data;
    }

    /**
     * 根据后缀读取文件内容并且返回
     * ini 直接解析
     * json 读取后解析,如果解析失败返回空
     * php 文件, include
     * 其他文件 直接读取内容并且返回
     *
     * @param $path
     * @return array | string;
     */
    public static function readFile($path)
    {
        $data = array();
        if (!file_exists($path)) {
            return $data;
        }
        $pathInfo = pathinfo($path);
        $extension = strtolower($pathInfo['extension']);
        if ($extension == 'ini') {
            $data = parse_ini_file($path);
        } elseif ($extension == 'json') {
            $content = file_get_contents($path);
            if (!$content) {
                return $data;
            }
            $content = json_decode($content, true);
            if (!$content) {
                return $data;
            }
            $data = $content;
            unset($content);
        } elseif ($extension == 'php') {
            $data = include($path);
        } else {
            $data = file_get_contents($path);
        }
        return $data;
    }

    /**
     * 根据环境变量$mode获取文件路径
     * @param $filename
     * @return string
     */
    protected static function getPathByMode($filename)
    {
        $envPath = dirname(__DIR__) . '/env';
        $mode = Request::getMode();
        $path = $envPath.'/product/';
        switch ($mode) {
            case Request::MODE_ONLINE:
                $path = $envPath.'/product/';
                break;
        }
        $filename = $path . ltrim($filename, '/');
        return $filename;
    }


}
