<?php
namespace App\lib\Html;
// Class to safely encode array to JSON object
// Reference Zend_Json
class Json
{
    public static function encode($mVar)
    {
        return preg_replace_callback(
            '#"[ ]{0,}function[ ]{0,}\([^)$]{0,}\)[ ]{0,}\{[ ]{0,}(?(?![ ]{0,}}[ ]{0,}").){0,}[ ]{0,}\}[ ]{0,}"#si', 'self::_res', json_encode($mVar)
        );
    }

    public static function decode($jsonString, $returnAsArray = true)
    {
        return json_decode($jsonString, $returnAsArray);
    }

    public static function _res($aRes = array())
    {
        for ($aRes[0] = substr($aRes[0], 1), $sOut = "", $i = 0, $iOpen = 0, $iClose = 0; $i <= strlen($aRes[0]) && $sOut.= substr($aRes[0], $i, 1); $i++)
            if (substr($aRes[0], $i, 1) == "{")
                $iOpen++;
            else if (substr($aRes[0], $i, 1) == "}" AND $iOpen == ++$iClose)
                break;
        return stripcslashes($sOut);
    }

}
