<?php

namespace Heanup\Frame\Helper;

/**
 * 格式转换
 */
class Format extends \Heanup\Frame\Helper
{
    /**
     * @hack 转换数字类型到字符串
     * @param $data
     * @return mixed
     */
    public static function convertNumberToString($data)
    {
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                if (is_array($v)) {
                    $data[$k] = self::convertNumberToString($v);
                } else if (is_numeric($v)) {
                    $data[$k] = (string)$v;
                }
            }
        } else if (is_numeric($data)) {
            $data = (string)$data;
        }
        return $data;
    }

    /**
     * Json数据格式化，拷贝自网上
     * @param  Mixed $data 数据
     * @param  String $indent 缩进字符，默认4个空格
     * @return JSON
     */
    public static function jsonFormat($data, $indent = null)
    {
        // 对数组中每个元素递归进行url_encode操作，保护中文字符
        array_walk_recursive($data, 'self::jsonFormatProtect');
        // json encode
        $data = json_encode($data);
        // 将url_encode的内容进行url_decode
        $data = urldecode($data);
        // 缩进处理
        $ret = '';
        $pos = 0;
        $length = strlen($data);
        $indent = isset($indent) ? $indent : '    ';
        $newline = "\n";
        $prevChar = '';
        $outOfQuotes = true;

        for ($i = 0; $i <= $length; $i++) {
            $char = substr($data, $i, 1);
            if ($char == '"' && $prevChar != '\\') {
                $outOfQuotes = !$outOfQuotes;
            } elseif (($char == '}' || $char == ']') && $outOfQuotes) {
                $ret .= $newline;
                $pos--;
                for ($j = 0; $j < $pos; $j++) {
                    $ret .= $indent;
                }
            }
            $ret .= $char;
            if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
                $ret .= $newline;
                if ($char == '{' || $char == '[') {
                    $pos++;
                }
                for ($j = 0; $j < $pos; $j++) {
                    $ret .= $indent;
                }
            }
            $prevChar = $char;
        }
        return $ret;
    }

    /**
     * 将数组元素进行
     * @param String $val
     */
    protected static function jsonFormatProtect(&$val)
    {
        if ($val !== true && $val !== false && $val !== null) {
            $val = urldecode($val);
        }
    }

}

