<?php
/**
 * Link         :   http://www.phpcorner.net
 * User         :   qingbing<780042175@qq.com>
 * Date         :   2018-12-11
 * Version      :   1.0
 */

namespace Helper;

defined('APP_CHARSET') or define('APP_CHARSET', 'utf-8');

class JsonOutput
{
    /**
     * 操作成功的JSON输出
     * @param array $data
     * @param string $message
     */
    public static function success($data = [], $message = 'success')
    {
        self::output($message, $data, 0);
    }

    /**
     * 操作失败的JSON输出
     * @param string $message
     * @param array $data
     * @param int $code
     */
    public static function failure($message = 'failure', $data = [], $code = -1)
    {
        self::output($message, $data, $code);
    }

    /**
     * 返回一个json字符串，然后终结应用
     * @param string $message
     * @param array $data
     * @param int $code
     */
    public static function output($message, $data = [], $code = 0)
    {
        header('Content-Type:text/html;Charset=' . APP_CHARSET);
        $output = [
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ];
        if (isset($_GET['e_callback']) && $_GET['e_callback']) {
            echo $_GET['e_callback'] . '(' . json_encode($output) . ')';
        } else {
            if (!headers_sent()) header('Content-type: application/json');
            echo json_encode($output);
        }
    }
}