ResponseAPI

Run Settings
LanguagePHP
Language Version
Run Command
<?php /** * Class ResponseAPI * @package App\Singleton */ class ResponseAPI { private static $instance = null; public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * @param null|string|array|\Eloquent $result * @return \Illuminate\Http\JsonResponse */ public function success($result = null) { return $this->response([ 'data' => $result, 'status' => 'success', ]); } /** * @param $message * @param int $code * @param array $messages * @return \Illuminate\Http\JsonResponse */ public function error($message, $code = 0, $messages = []) { $status = 'error'; $resources = compact('code', 'message', 'messages', 'status'); return $this->response(array_filter($resources)); } /** * @param $data * @param int $code * @return \Illuminate\Http\JsonResponse */ public function response($data, $code = 200) { return response()->json($data, $code, [ 'Access-Control-Allow-Origin' => '*', //允许域名eg:http://www.baidu.com //'Access-Control-Allow-Methods' => '*', //允许GET、PUT、DELETE的外域请求 //'Access-Control-Allow-Headers' => '', //允许跨域请求包含content-type头 'Access-Control-Max-Age' => 60 * 60 * 24, //在N秒内,不需要再发送预检验请求,可以缓存该结果 ]); } /** * @param null|string|array|\Eloquent $data * @return string */ public function toString($data) { if (is_bool($data)) { return $data ? '1' : '0'; } else if (is_numeric($data)) { return (string)$data; } else if (is_string($data)) { return $data; } else if (is_null($data)) { return null; } else if (is_object($data)) { if (is_callable([$data, 'toArray'])) { return $this->toString($data->toArray()); } else if (get_class($data) == 'stdClass') { return null; } else { return $this->toString((array)$data); } } else if (is_array($data)) { $output = []; foreach ($data as $key => $value) { $output[$key] = $this->toString($value); } return $output; } else { return (string)$data; } } public static function __callStatic($method, $arguments) { if (!self::$instance) { self::$instance = new self(); } return call_user_func_array([self::$instance, $method], $arguments); } }
Editor Settings
Theme
Key bindings
Full width
Lines