<?PHP

class JsonHelper
{

    private $Data;
    private $Warnings;

    public function __construct()
    {
        $this->Data = array();
        $this->Warnings = array();
    }

    public function AddDatum($Key, $Value)
    {
        $this->Data[$Key] = $Value;
    }

    public function AddWarning($Message)
    {
        $this->Warnings[] = strval($Message);
    }

    public function Error($Message)
    {
        $this->SendResult($this->GenerateResult("ERROR", $Message));
    }

    public function Success($Message="")
    {
        $this->SendResult($this->GenerateResult("OK", $Message));
    }

    private function SendResult(array $Result)
    {
        header("Content-Type: application/json;  charset=utf-8");
        print $this->ArrayToJson($Result);
    }

    private function GenerateResult($State, $Message)
    {
        return array(
            "data" => $this->Data,
            "status" => array(
                "state" => strval($State),
                "message" => strval($Message),
                "numWarnings" => count($this->Warnings),
                "warnings" => $this->Warnings));
    }

    private function ArrayToJson(array $Array)
    {
        # initialize
        $JSON = "";
        $counter = 0;

        foreach ($Array as $key => $value)
        {
            # add key
            $JSON .= "'".$key."':";

            # recur if the value is an array
            if (is_array($value))
            {
                $JSON .= $this->ArrayToJson($value);
            }

            # add the value
            else
            {
                # escape
                $value = $this->ConvertSmartQuotes($value);
                $value = str_replace("\r", "", $value);
                $value = htmlentities($value, ENT_QUOTES);

                # if the value is a number, parse it and don't put in quotes
                if (is_numeric($value))
                {
                    $JSON .= intval($value);
                }

                # for everything else, get the string value and put in quotes
                else
                {
                    $JSON .= "'".strval($value)."'";
                }
            }

            # add comma if necessary
            $counter++;
            $JSON .= ($counter < count($Array)) ? "," : "" ;
        }

        # return JSON-ified array
        return "{".$JSON."}";
    }

    private function ConvertSmartQuotes($String)
    {
        $search = array(chr(145), chr(146), chr(147), chr(148), chr(151));
        $replace = array("'", "'", '"', '"', '-');
        return str_replace($search, $replace, $String);
    }

}

?>
