create() public static method

创建Response对象
public static create ( mixed $data = '', string $type = '', integer $code = 200, array $header = [], array $options = [] ) : Response | Json | View | Xml | Redirect | Jsonp
$data mixed 输出数据
$type string 输出类型
$code integer
$header array
$options array 输出参数
return Response | Json | View | Xml | Redirect | Jsonp
Exemplo n.º 1
0
 /**
  * kindeditor 图片上传
  */
 public function kindeditor($dir = '')
 {
     if (!in_array($dir, ['image', 'file', 'flash', 'media'])) {
         $return = ['error' => 1, 'message' => '不支持的上传类型'];
         Response::create($return, 'json')->send();
     }
     $Storage = Loader::model('Storage');
     $return = ['error' => 0, 'info' => '上传成功'];
     switch ($dir) {
         case 'image':
             $options['ext'] = ['jpg', 'gif', 'png', 'jpeg'];
             break;
         case 'file':
             $options['ext'] = ['xls', 'xlsx', 'doc', 'docx', 'txt', 'zip', 'rar'];
             break;
         case 'flash':
             $options['ext'] = ['flv', 'swf'];
             break;
         case 'media':
             $options['ext'] = ['mp4', 'avi'];
             break;
     }
     $info = $Storage->upload('imgFile', $options);
     if (false !== $info) {
         $return['url'] = $info['path'];
     } else {
         $return['error'] = 1;
         $return['message'] = $Storage->getError();
     }
     Response::create($return, 'json')->send();
 }
Exemplo n.º 2
0
 /**
  * @param HttpException $e
  * @return Response
  */
 protected function renderHttpException(HttpException $e)
 {
     $status = $e->getStatusCode();
     $template = Config::get('http_exception_template');
     if (!Config::get('DEBUG') && !empty($template[$status])) {
         return Response::create($template[$status], 'view', $status)->assign(['e' => $e]);
     } else {
         return $this->convertExceptionToResponse($e);
     }
 }
Exemplo n.º 3
0
 /**
  * @covers think\Response::send
  * @todo Implement testSend().
  */
 public function testSend()
 {
     $dataArr = [];
     $dataArr["key"] = "value";
     $response = Response::create($dataArr, 'json');
     $result = $response->getContent();
     $this->assertEquals('{"key":"value"}', $result);
     $request = Request::instance();
     $request->get(['callback' => 'callback']);
     $response = Response::create($dataArr, 'jsonp');
     $result = $response->getContent();
     $this->assertEquals('callback({"key":"value"});', $result);
 }
Exemplo n.º 4
0
 /**
  * 读取或者设置缓存
  * @access public
  * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id
  * @param mixed  $expire 缓存有效期
  * @return mixed
  */
 public function cache($key, $expire = null)
 {
     if ($this->isGet()) {
         if (false !== strpos($key, ':')) {
             $param = $this->param();
             foreach ($param as $item => $val) {
                 if (is_string($val) && false !== strpos($key, ':' . $item)) {
                     $key = str_replace(':' . $item, $val, $key);
                 }
             }
         } elseif ('__URL__' == $key) {
             // 当前URL地址作为缓存标识
             $key = md5($this->url());
         } elseif (strpos($key, ']')) {
             if ('[' . $this->ext() . ']' == $key) {
                 // 缓存某个后缀的请求
                 $key = md5($this->url());
             } else {
                 return;
             }
         }
         if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) {
             // 读取缓存
             $response = Response::create()->code(304);
             throw new \think\exception\HttpResponseException($response);
         } elseif (Cache::has($key)) {
             list($content, $header) = Cache::get($key);
             $response = Response::create($content)->header($header);
             throw new \think\exception\HttpResponseException($response);
         } else {
             $this->cache = [$key, $expire];
         }
     }
 }
Exemplo n.º 5
0
 /**
  * 获取\think\response\Redirect对象实例
  * @param mixed         $url 重定向地址 支持Url::build方法的地址
  * @param array|integer $params 额外参数
  * @param integer       $code 状态码
  * @return \think\response\Redirect
  */
 function redirect($url = [], $params = [], $code = 302)
 {
     if (is_integer($params)) {
         $code = $params;
         $params = [];
     }
     return Response::create($url, 'redirect', $code)->params($params);
 }
Exemplo n.º 6
0
Arquivo: App.php Projeto: GDdark/cici
 /**
  * 执行应用程序
  * @access public
  * @param Request $request Request对象
  * @return Response
  * @throws Exception
  */
 public static function run(Request $request = null)
 {
     is_null($request) && ($request = Request::instance());
     if ('ico' == $request->ext()) {
         throw new HttpException(404, 'ico file not exists');
     }
     $config = self::initCommon();
     try {
         // 开启多语言机制
         if ($config['lang_switch_on']) {
             // 获取当前语言
             $request->langset(Lang::detect());
             // 加载系统语言包
             Lang::load(THINK_PATH . 'lang' . DS . $request->langset() . EXT);
             if (!$config['app_multi_module']) {
                 Lang::load(APP_PATH . 'lang' . DS . $request->langset() . EXT);
             }
         }
         // 获取应用调度信息
         $dispatch = self::$dispatch;
         if (empty($dispatch)) {
             // 进行URL路由检测
             $dispatch = self::routeCheck($request, $config);
         }
         // 记录当前调度信息
         $request->dispatch($dispatch);
         // 记录路由信息
         self::$debug && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info');
         // 监听app_begin
         Hook::listen('app_begin', $dispatch);
         switch ($dispatch['type']) {
             case 'redirect':
                 // 执行重定向跳转
                 $data = Response::create($dispatch['url'], 'redirect')->code($dispatch['status']);
                 break;
             case 'module':
                 // 模块/控制器/操作
                 $data = self::module($dispatch['module'], $config, isset($dispatch['convert']) ? $dispatch['convert'] : null);
                 break;
             case 'controller':
                 // 执行控制器操作
                 $data = Loader::action($dispatch['controller'], $dispatch['params']);
                 break;
             case 'method':
                 // 执行回调方法
                 $data = self::invokeMethod($dispatch['method'], $dispatch['params']);
                 break;
             case 'function':
                 // 执行闭包
                 $data = self::invokeFunction($dispatch['function'], $dispatch['params']);
                 break;
             case 'response':
                 $data = $dispatch['response'];
                 break;
             default:
                 throw new \InvalidArgumentException('dispatch type not support');
         }
     } catch (HttpResponseException $exception) {
         $data = $exception->getResponse();
     }
     // 清空类的实例化
     Loader::clearInstance();
     // 输出数据到客户端
     if ($data instanceof Response) {
         $response = $data;
     } elseif (!is_null($data)) {
         // 默认自动识别响应输出类型
         $isAjax = $request->isAjax();
         $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type');
         $response = Response::create($data, $type);
     } else {
         $response = Response::create();
     }
     // 监听app_end
     Hook::listen('app_end', $response);
     // Trace调试注入
     if (Config::get('app_trace')) {
         Debug::inject($response);
     }
     return $response;
 }
Exemplo n.º 7
0
Arquivo: Jump.php Projeto: GDdark/cici
 /**
  * 返回封装后的API数据到客户端
  * @access protected
  * @param mixed $data 要返回的数据
  * @param integer $code 返回的code
  * @param mixed $msg 提示信息
  * @param string $type 返回数据格式
  * @return mixed
  */
 protected function result($data, $code = 0, $msg = '', $type = '')
 {
     $result = ['code' => $code, 'msg' => $msg, 'time' => $_SERVER['REQUEST_TIME'], 'data' => $data];
     $type = $type ?: $this->getResponseType();
     return Response::create($result, $type);
 }
Exemplo n.º 8
0
 /**
  * 返回封装后的API数据到客户端
  * @access protected
  * @param mixed     $data 要返回的数据
  * @param integer   $code 返回的code
  * @param mixed     $msg 提示信息
  * @param string    $type 返回数据格式
  * @param array     $header 发送的Header信息
  * @return void
  */
 protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
 {
     $result = ['code' => $code, 'msg' => $msg, 'time' => $_SERVER['REQUEST_TIME'], 'data' => $data];
     $type = $type ?: $this->getResponseType();
     $response = Response::create($result, $type)->header($header);
     throw new HttpResponseException($response);
 }
Exemplo n.º 9
0
 /**
  * 设置当前地址的请求缓存
  * @access public
  * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id
  * @param mixed  $expire 缓存有效期
  * @return void
  */
 public function cache($key, $expire = null)
 {
     if (false !== $key && $this->isGet() && !$this->isCheckCache) {
         // 标记请求缓存检查
         $this->isCheckCache = true;
         if (false === $expire) {
             // 关闭当前缓存
             return;
         }
         if ($key instanceof \Closure) {
             $key = call_user_func_array($key, [$this]);
         } elseif (true === $key) {
             // 自动缓存功能
             $key = '__URL__';
         } elseif (strpos($key, '|')) {
             list($key, $fun) = explode('|', $key);
         }
         // 特殊规则替换
         if (false !== strpos($key, '__')) {
             $key = str_replace(['__MODULE__', '__CONTROLLER__', '__ACTION__', '__URL__'], [$this->module, $this->controller, $this->action, md5($this->url())], $key);
         }
         if (false !== strpos($key, ':')) {
             $param = $this->param();
             foreach ($param as $item => $val) {
                 if (is_string($val) && false !== strpos($key, ':' . $item)) {
                     $key = str_replace(':' . $item, $val, $key);
                 }
             }
         } elseif (strpos($key, ']')) {
             if ('[' . $this->ext() . ']' == $key) {
                 // 缓存某个后缀的请求
                 $key = md5($this->url());
             } else {
                 return;
             }
         }
         if (isset($fun)) {
             $key = $fun($key);
         }
         if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) {
             // 读取缓存
             $response = Response::create()->code(304);
             throw new \think\exception\HttpResponseException($response);
         } elseif (Cache::has($key)) {
             list($content, $header) = Cache::get($key);
             $response = Response::create($content)->header($header);
             throw new \think\exception\HttpResponseException($response);
         } else {
             $this->cache = [$key, $expire];
         }
     }
 }
Exemplo n.º 10
0
 /**
  * 执行应用程序
  * @access public
  * @param Request $request Request对象
  * @return Response
  * @throws Exception
  */
 public static function run(Request $request = null)
 {
     is_null($request) && ($request = Request::instance());
     try {
         $config = self::initCommon();
         if (defined('BIND_MODULE')) {
             // 模块/控制器绑定
             BIND_MODULE && Route::bind(BIND_MODULE);
         } elseif ($config['auto_bind_module']) {
             // 入口自动绑定
             $name = pathinfo($request->baseFile(), PATHINFO_FILENAME);
             if ($name && 'index' != $name && is_dir(APP_PATH . $name)) {
                 Route::bind($name);
             }
         }
         $request->filter($config['default_filter']);
         if ($config['lang_switch_on']) {
             // 开启多语言机制 检测当前语言
             Lang::detect();
         } else {
             // 读取默认语言
             Lang::range($config['default_lang']);
         }
         $request->langset(Lang::range());
         // 加载系统语言包
         Lang::load([THINK_PATH . 'lang' . DS . $request->langset() . EXT, APP_PATH . 'lang' . DS . $request->langset() . EXT]);
         // 获取应用调度信息
         $dispatch = self::$dispatch;
         if (empty($dispatch)) {
             // 进行URL路由检测
             $dispatch = self::routeCheck($request, $config);
         }
         // 记录当前调度信息
         $request->dispatch($dispatch);
         // 记录路由和请求信息
         if (self::$debug) {
             Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info');
             Log::record('[ HEADER ] ' . var_export($request->header(), true), 'info');
             Log::record('[ PARAM ] ' . var_export($request->param(), true), 'info');
         }
         // 监听app_begin
         Hook::listen('app_begin', $dispatch);
         switch ($dispatch['type']) {
             case 'redirect':
                 // 执行重定向跳转
                 $data = Response::create($dispatch['url'], 'redirect')->code($dispatch['status']);
                 break;
             case 'module':
                 // 模块/控制器/操作
                 $data = self::module($dispatch['module'], $config, isset($dispatch['convert']) ? $dispatch['convert'] : null);
                 break;
             case 'controller':
                 // 执行控制器操作
                 $data = Loader::action($dispatch['controller']);
                 break;
             case 'method':
                 // 执行回调方法
                 $data = self::invokeMethod($dispatch['method']);
                 break;
             case 'function':
                 // 执行闭包
                 $data = self::invokeFunction($dispatch['function']);
                 break;
             case 'response':
                 $data = $dispatch['response'];
                 break;
             default:
                 throw new \InvalidArgumentException('dispatch type not support');
         }
     } catch (HttpResponseException $exception) {
         $data = $exception->getResponse();
     }
     // 清空类的实例化
     Loader::clearInstance();
     // 输出数据到客户端
     if ($data instanceof Response) {
         $response = $data;
     } elseif (!is_null($data)) {
         // 默认自动识别响应输出类型
         $isAjax = $request->isAjax();
         $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type');
         $response = Response::create($data, $type);
     } else {
         $response = Response::create();
     }
     // 监听app_end
     Hook::listen('app_end', $response);
     return $response;
 }
Exemplo n.º 11
0
Arquivo: Rest.php Projeto: GDdark/cici
 /**
  * 输出返回数据
  * @access protected
  * @param mixed     $data 要返回的数据
  * @param String    $type 返回类型 JSON XML
  * @param integer   $code HTTP状态码
  * @return Response
  */
 protected function response($data, $type = 'json', $code = 200)
 {
     return Response::create($data, $type)->code($code);
 }
Exemplo n.º 12
0
 /**
  * 还原数据库
  * @param  integer $time  [description]
  * @param  [type]  $part  [description]
  * @param  [type]  $start [description]
  */
 public function import($time = 0, $part = null, $start = null)
 {
     if (is_numeric($time) && !empty($time) && is_null($part) && is_null($start)) {
         //初始化
         //获取备份文件信息
         $name = date('Ymd-His', $time) . '-*.sql*';
         $path = config('backdata.path') . $name;
         $files = glob($path);
         $list = [];
         foreach ($files as $name) {
             $basename = basename($name);
             $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
             $gz = preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql.gz$/', $basename);
             $list[$match[6]] = [$match[6], $name, $gz];
         }
         ksort($list);
         //检测文件正确性
         $last = end($list);
         if (count($list) === $last[0]) {
             session('backup_list', $list);
             //缓存备份列表
             $response = ['code' => 1, 'msg' => '初始化完成!', 'part' => 1, 'start' => 0];
             Response::create($response, 'json')->send();
         } else {
             $response = ['code' => 0, 'msg' => '备份文件可能已经损坏,请检查!'];
             Response::create($response, 'json')->send();
         }
     } elseif (is_numeric($part) && is_numeric($start)) {
         $list = session('backup_list');
         $db = new \tools\Database($list[$part], ['path' => config('backdata.path'), 'compress' => $list[$part][2]]);
         $start = $db->import($start);
         if (false === $start) {
             $response = ['code' => 0, 'msg' => '还原数据出错!'];
             Response::create($response, 'json')->send();
         } elseif (0 == $start) {
             //下一卷
             if (isset($list[++$part])) {
                 $response = ['code' => 1, 'msg' => "正在还原...#{$part}", 'part' => $part, 'start' => 0];
                 Response::create($response, 'json')->send();
             } else {
                 session('backup_list', null);
                 $response = ['code' => 1, 'msg' => '还原完成!'];
                 Response::create($response, 'json')->send();
             }
         } else {
             $data = array('part' => $part, 'start' => $start[0], 'status' => 1);
             if ($start[1]) {
                 $rate = floor(100 * ($start[0] / $start[1]));
                 $response = ['code' => 1, 'msg' => "正在还原...#{$part} ({$rate}%)", 'part' => $part, 'start' => $start[0]];
                 Response::create($response, 'json')->send();
             } else {
                 $response = ['code' => 1, 'msg' => "正在还原...#{$part}", 'part' => $part, 'start' => $start[0], 'gz' => 1];
                 Response::create($response, 'json')->send();
             }
         }
     } else {
         $path = config('backdata.path');
         $list = [];
         if (is_dir($path)) {
             $flag = \FilesystemIterator::KEY_AS_FILENAME;
             $glob = new \FilesystemIterator($path, $flag);
             $list = [];
             foreach ($glob as $name => $file) {
                 if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) {
                     $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
                     $date = "{$name[0]}-{$name[1]}-{$name[2]}";
                     $time = "{$name[3]}:{$name[4]}:{$name[5]}";
                     $part = $name[6];
                     if (isset($list["{$date} {$time}"])) {
                         $info = $list["{$date} {$time}"];
                         $info['part'] = max($info['part'], $part);
                         $info['size'] = $info['size'] + $file->getSize();
                     } else {
                         $info['part'] = $part;
                         $info['size'] = $file->getSize();
                     }
                     $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
                     $info['compress'] = $extension === 'SQL' ? '-' : $extension;
                     $info['time'] = strtotime("{$date} {$time}");
                     $list["{$date} {$time}"] = $info;
                 }
                 krsort($list);
             }
         }
         $this->assign('__list__', $list);
         $this->meta_title = '还原数据';
         return $this->fetch();
     }
 }
Exemplo n.º 13
0
 private function ResponseCreate($code, $msg, $data, $url, $wait, $header)
 {
     if (!empty($url)) {
         $url = preg_match('/^(https?:|\\/)/', $url) ? $url : Url::build($url);
     }
     $result = ['code' => $code, 'msg' => $msg, 'data' => $data, 'url' => $url, 'wait' => $wait];
     $type = $this->getResponseType();
     if ('html' == strtolower($type)) {
         $result = $this->fetch(Config::get('dispatch_success_tmpl'), $result);
     }
     return Response::create($result, $type)->header($header);
 }
Exemplo n.º 14
0
 /**
  * 读取或者设置缓存
  * @access public
  * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id
  * @param mixed  $expire 缓存有效期
  * @return mixed
  */
 public function cache($key, $expire = null)
 {
     if (false !== strpos($key, ':')) {
         $param = $this->param();
         foreach ($param as $item => $val) {
             if (is_string($val) && false !== strpos($key, ':' . $item)) {
                 $key = str_replace(':' . $item, $val, $key);
             }
         }
     }
     if (Cache::has($key)) {
         // 读取缓存
         $content = Cache::get($key);
         $response = Response::create($content)->code(304)->header('Content-Type', Cache::get($key . '_header'));
         throw new \think\exception\HttpResponseException($response);
     } else {
         $this->cache = [$key, $expire];
     }
 }