It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client. It also controls the HTTP [[statusCode|status code]]. Response is configured as an application component in Application by default. You can access that instance via Yii::$app->response. You can modify its configuration by adding an array to your application config under components as it is shown in the following example: php 'response' => [ 'format' => yii\web\Response::FORMAT_JSON, 'charset' => 'UTF-8', ... ] For more details and usage information on Response, see the guide article on responses.
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Author: Carsten Brandt (mail@cebe.cc)
Inheritance: extends yii\base\Response
Ejemplo n.º 1
4
 /**
  * Formats the specified response.
  * @param \yii\web\Response $response the response to be formatted.
  */
 public function format($response)
 {
     //$response->getHeaders()->set('Content-Type', 'text/csv; charset=UTF-8');
     $response->setDownloadHeaders(basename(\Yii::$app->request->pathInfo) . '.csv', 'text/csv');
     if ($response->data === null) {
         return;
     }
     $handle = fopen('php://memory', 'r+');
     /** @var array $data should be output of \yii\rest\Serializer configured in current controller */
     $data = $response->data;
     if (!isset($data['items'])) {
         // single model
         fputcsv($handle, array_keys($data));
         fputcsv($handle, array_map(function ($value) {
             return is_array($value) ? print_r($value, true) : (string) $value;
         }, array_values($data)));
     } else {
         // a collection of models
         if (($firstRow = reset($data['items'])) !== false) {
             fputcsv($handle, array_keys($firstRow));
         }
         foreach ($data['items'] as $item) {
             fputcsv($handle, $item);
         }
     }
     rewind($handle);
     // mb_convert_encoding($csv, 'iso-8859-2', 'utf-8')
     $response->content = stream_get_contents($handle);
     fclose($handle);
 }
Ejemplo n.º 2
0
 private function giveUserFile($filename)
 {
     $var = new Response();
     $var->sendFile(Yii::$app->params['uploadPath'] . $filename);
     $var->send();
     unlink(Yii::$app->params['uploadPath'] . $filename);
 }
Ejemplo n.º 3
0
 /**
  * Formats the specified response.
  * @param \yii\web\Response $response the response to be formatted.
  */
 public function format($response)
 {
     $response->getHeaders()->set('Content-Type', 'text');
     //$response->setDownloadHeaders('error.pdf', 'application/pdf');
     //$response->setStatusCode(200);
     if ($response->data === null) {
         return;
     }
     echo '<pre>';
     var_export($response->data);
     /*
     $renderer = new \mPDF(
         'pl-x', // mode
         'A4', // format
         0, // font-size
         '', // font
         12, // margin-left
         12, // margin-right
         5, // margin-top
         5, // margin-bottom
         2, // margin-header
         2, // margin-footer
         'P' // orientation
     );
     $renderer->useSubstitutions = true;
     $renderer->simpleTables = false;
     if ($response->data !== null) {
         @$renderer->WriteHTML(\yii\helpers\Html::encode(var_export($response->data, true)));
     }
     $response->content = $renderer->Output('print', 'S');
     */
 }
 /**
  * Formats the specified response.
  * @param Response $response the response to be formatted.
  */
 public function format($response)
 {
     $charset = $this->encoding === null ? $response->charset : $this->encoding;
     if ($this->gzip) {
         $this->contentType = $this->gzipContentType;
     } elseif (stripos($this->contentType, 'charset') === false) {
         $this->contentType .= '; charset=' . $charset;
     }
     $response->getHeaders()->set('Content-Type', $this->contentType);
     $dom = new DOMDocument($this->version, $charset);
     $dom->formatOutput = true;
     $urlsetElement = $dom->createElement($this->rootTag);
     //urlset
     $dom->appendChild($urlsetElement);
     foreach ($this->xmlns as $xmlnsAttributeName => $xmlnsAttributeValue) {
         $urlsetElement->setAttributeNS('http://www.w3.org/2000/xmlns/', $xmlnsAttributeName, $xmlnsAttributeValue);
     }
     $this->buildXml($urlsetElement, $response->data, $dom);
     $xmlData = $dom->saveXML();
     //output
     if ($this->gzip) {
         $response->content = gzencode($xmlData);
         $response->getHeaders()->set('Content-Disposition', "attachment; filename=\"{$this->gzipFilename}\"");
     } else {
         $response->content = $xmlData;
     }
 }
Ejemplo n.º 5
0
 /**
  * @dataProvider wrongRanges
  */
 public function testSendFileWrongRanges($rangeHeader)
 {
     $this->setExpectedException('yii\\web\\HttpException');
     $dataFile = \Yii::getAlias('@yiiunit/data/web/data.txt');
     $_SERVER['HTTP_RANGE'] = 'bytes=' . $rangeHeader;
     $this->response->sendFile($dataFile);
 }
Ejemplo n.º 6
0
 /**
  * Formats the specified response.
  * @param Response $response the response to be formatted.
  */
 public function format($response)
 {
     if (stripos($this->contentType, 'charset') === false) {
         $this->contentType .= '; charset=' . $response->charset;
     }
     $response->getHeaders()->set('Content-Type', $this->contentType);
     $response->content = $response->data;
 }
 /**
  * Formats the specified response.
  * @param Response $response the response to be formatted.
  */
 public function format($response)
 {
     $response->getHeaders()->set('Content-Type', $this->contentType);
     if ($this->filename !== null) {
         $response->getHeaders()->set('Content-Disposition', "attachment; filename=\"{$this->filename}\"");
     }
     $response->content = Yii::$app->{$this->converter}->convert($response->data, $this->options);
 }
 /**
  * Formats the specified response.
  * @param Response $response the response to be formatted.
  */
 public function format($response)
 {
     $response->getHeaders()->set('Content-Type', $this->contentType);
     $dom = new DOMDocument($this->version, $this->encoding === null ? $response->charset : $this->encoding);
     $root = new DOMElement($this->rootTag);
     $dom->appendChild($root);
     $this->buildXml($root, $response->data);
     $response->content = $dom->saveXML();
 }
Ejemplo n.º 9
0
 /**
  * Formats response data in JSONP format.
  * @param Response $response
  */
 protected function formatJsonp($response)
 {
     $response->getHeaders()->set('Content-Type', 'application/javascript; charset=UTF-8');
     if (is_array($response->data) && isset($response->data['data'], $response->data['callback'])) {
         $response->content = sprintf('%s(%s);', $response->data['callback'], Json::encode($response->data['data']));
     } else {
         $response->content = '';
         Yii::warning("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.", __METHOD__);
     }
 }
 /**
  * Formats response data in JSON format.
  * @param Response $response
  */
 protected function formatJson($response)
 {
     $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
     if ($response->data !== null) {
         $options = $this->encodeOptions;
         if ($this->prettyPrint) {
             $options |= JSON_PRETTY_PRINT;
         }
         $response->content = Json::encode($response->data, $options);
     }
 }
Ejemplo n.º 11
0
 /** @inheritdoc */
 protected function renderException($exception)
 {
     $event = new ExceptionEvent($exception);
     $this->trigger(self::EVENT_BEFORE_EXCEPTION, $event);
     if (\Yii::$app->has('response')) {
         $response = \Yii::$app->getResponse();
     } else {
         $response = new Response();
     }
     $response->data = $this->convertExceptionToArray($exception);
     $response->setStatusCode(property_exists($exception, 'statusCode') ? $exception->statusCode : 500);
     $response->send();
 }
Ejemplo n.º 12
0
 /**
  * Renders the exception.
  * @param \Exception $exception the exception to be rendered.
  */
 protected function renderException($exception)
 {
     if (!$exception instanceof JqException) {
         parent::renderException($exception);
         return;
     }
     if (\Yii::$app->has('response')) {
         $response = \Yii::$app->getResponse();
     } else {
         $response = new Response();
     }
     $response->setStatusCode(500);
     $response->data['message'] = $exception->getMessage();
     $response->send();
 }
Ejemplo n.º 13
0
 /**
  * Formats the specified response.
  * @param Response $response the response to be formatted.
  */
 public function format($response)
 {
     $charset = $this->encoding === null ? $response->charset : $this->encoding;
     if (stripos($this->contentType, 'charset') === false) {
         $this->contentType .= '; charset=' . $charset;
     }
     $response->getHeaders()->set('Content-Type', $this->contentType);
     if ($response->data !== null) {
         $dom = new DOMDocument($this->version, $charset);
         $root = new DOMElement($this->rootTag);
         $dom->appendChild($root);
         $this->buildXml($root, $response->data);
         $response->content = $dom->saveXML();
     }
 }
Ejemplo n.º 14
0
 public function sendContent()
 {
     if ($this->stream === null) {
         $this->content = Yii::$app->getI18n()->removeLegacyLangTags($this->content);
     }
     parent::sendContent();
 }
Ejemplo n.º 15
0
 /**
  * Formats the specified response.
  * @param \yii\web\Response $response the response to be formatted.
  */
 public function format($response)
 {
     //$response->getHeaders()->set('Content-Type', 'application/vnd.ms-excel');
     $response->setDownloadHeaders(basename(\Yii::$app->request->pathInfo) . '.xls', 'application/vnd.ms-excel');
     if ($response->data === null) {
         return;
     }
     \PHPExcel_Settings::setCacheStorageMethod(\PHPExcel_CachedObjectStorageFactory::cache_to_sqlite3);
     $styles = $this->getStyles();
     $objPHPExcel = new \PHPExcel();
     $sheet = $objPHPExcel->getActiveSheet();
     $offset = 1;
     /*
      * serialize filter
     $sheet->setCellValue('A1', $opcje['nazwaAnaliza']);
     $sheet->duplicateStyle($styles['default'], 'A1:C4');
     $sheet->getRowDimension(1)->setRowHeight(18);
     $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(15);
     $sheet->getStyle('C3:C4')->getFont()->setBold(true);
     $offset = 6;
     */
     $data = $response->data;
     if (!isset($data['items'])) {
         // single model
         $this->addLine($sheet, $offset, array_keys($data));
         $this->addLine($sheet, $offset + 1, array_values($data));
         for ($i = 1, $lastColumn = 'A'; $i < count($data); $i++, $lastColumn++) {
         }
         $sheet->duplicateStyle($styles['header'], 'A' . $offset . ':' . $lastColumn . $offset);
     } else {
         // a collection of models
         if (($firstRow = reset($data['items'])) !== false) {
             $this->addLine($sheet, $offset, array_keys($firstRow));
         }
         $startOffset = ++$offset;
         $item = [];
         foreach ($data['items'] as $item) {
             $this->addLine($sheet, $offset++, $item);
         }
         $this->addSummaryRow($sheet, $startOffset, $offset, $item);
     }
     $filename = tempnam(\Yii::getAlias('@runtime'), 'xls');
     $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
     $objWriter->save($filename);
     $response->content = file_get_contents($filename);
     unlink($filename);
 }
 public function afterAction($action, $result)
 {
     $result = parent::afterAction($action, $result);
     if ($this->response->getStatusCode() == 200) {
         return $this->respondByFormat();
     }
     return $result;
 }
Ejemplo n.º 17
0
 /**
  * Send the result.
  */
 public function send()
 {
     //PS: I think this is a bit wrong. But this works, for now.
     $this->_transport->open();
     $this->_processor->process($this->_protocol, $this->_protocol);
     $this->_transport->close();
     parent::send();
 }
Ejemplo n.º 18
0
 public function getHeaders()
 {
     $data = parent::getHeaders();
     foreach ($this->newheaders as $k => $v) {
         $data->set($k, $v);
     }
     return $data;
 }
Ejemplo n.º 19
0
 /**
  * Renders the exception.
  * @param \Exception $exception the exception to be rendered.
  */
 protected function renderException($exception)
 {
     //如果存在未提交的事务,则对事务进行回滚
     $transaction = Yii::$app->db->getTransaction();
     if ($transaction) {
         $transaction->rollback();
     }
     //对返回内容进行渲染
     if (Yii::$app->has('response')) {
         $response = Yii::$app->getResponse();
         // reset parameters of response to avoid interference with partially created response data
         // in case the error occurred while sending the response.
         $response->isSent = false;
         $response->stream = null;
         $response->data = null;
         $response->content = null;
     } else {
         $response = new Response();
     }
     $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
     //如果是用户定义的异常,则需要将异常错误信息抛出,如果是接口类型的并且有model类型的错误
     //需要使用用户定制的errorView,同时用户在配置文件中指定了errorAction
     if ($useErrorView && $this->errorAction !== null) {
         $result = Yii::$app->runAction($this->errorAction);
         if ($result instanceof Response) {
             $result = $result;
         } else {
             $response->data = $result;
         }
     } elseif ($response->format === Response::FORMAT_HTML) {
         if (YII_ENV_TEST || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
             $response->data = '<pre>' . $this->htmlEncode(static::convertExceptionToString($exception)) . '</pre>';
         } else {
             if (YII_DEBUG) {
                 ini_set('display_errors', 1);
             }
             $file = $useErrorView ? $this->errorView : $this->exceptionView;
             $response->data = $this->renderFile($file, ['exception' => $exception]);
         }
     } elseif ($response->format === Response::FORMAT_RAW) {
         $response->data = static::convertExceptionToString($exception);
     } elseif ($response->format === Response::FORMAT_JSON || $response->format === Response::FORMAT_XML) {
         $response->data = ['code' => $exception->getCode(), 'message' => $exception->getMessage()];
         if ($exception instanceof LBUserException) {
             $response->data['errors'] = $exception->getErrors();
         }
     } else {
         $response->data = $this->convertExceptionToArray($exception);
     }
     //调试状态状态码为500, 非调试状态不抛出异常
     if (!YII_DEBUG || $exception instanceof LBUserException) {
         $response->setStatusCode(200);
     } else {
         $response->setStatusCode(500);
     }
     $response->send();
 }
Ejemplo n.º 20
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if (!Yii::$app instanceof Application) {
         return;
     }
     Event::on(Controller::className(), 'beforeAction', [$this, 'beforeActionAccess']);
     if ($this->removeDeniedLinks) {
         Event::on(Response::className(), 'afterPrepare', [$this, 'responseAfterPrepare']);
     }
 }
Ejemplo n.º 21
0
 public function send()
 {
     if ($this->finishRequestAfterSend && function_exists('fastcgi_finish_request')) {
         $this->on(static::EVENT_AFTER_SEND, 'fastcgi_finish_request', null, false);
     }
     //如果是DEBUG
     if (YII_DEBUG) {
         $this->getHeaders()->add('Request-Duration', (microtime(true) - YII_BEGIN_TIME) * 1000000);
     }
     return parent::send();
 }
 public function afterAction($action, $result)
 {
     $errorHandler = Yii::$app->get('errorHandler');
     if (!empty($errorHandler->exception)) {
         $this->handleException($errorHandler->exception);
     }
     $result = parent::afterAction($action, $result);
     if ($this->response->getStatusCode() == 200) {
         return $this->respondByFormat();
     }
     return $result;
 }
 /**
  * Formats response data in JSON format.
  * @link http://jsonapi.org/format/upcoming/#document-structure
  * @param Response $response
  */
 public function format($response)
 {
     $response->getHeaders()->set('Content-Type', 'application/vnd.api+json; charset=UTF-8');
     if ($response->data !== null) {
         $options = $this->encodeOptions;
         if ($this->prettyPrint) {
             $options |= JSON_PRETTY_PRINT;
         }
         if ($response->isClientError || $response->isServerError) {
             if (ArrayHelper::isAssociative($response->data)) {
                 $response->data = [$response->data];
             }
             $apiDocument = ['errors' => $response->data];
         } elseif (ArrayHelper::keyExists('data', $response->data)) {
             $apiDocument = $response->data;
         } else {
             $apiDocument = ['meta' => $response->data];
         }
         $response->content = Json::encode($apiDocument, $options);
     }
 }
Ejemplo n.º 24
0
 /**
  * Renders the exception.
  * @param \Exception $exception the exception to be rendered.
  */
 protected function renderException($exception)
 {
     //如果存在未提交的事务,则对事务进行回滚
     $transaction = Yii::$app->db->getTransaction();
     if ($transaction) {
         $transaction->rollback();
     }
     //对返回内容进行渲染
     if (Yii::$app->has('response')) {
         $response = Yii::$app->getResponse();
         // reset parameters of response to avoid interference with partially created response data
         // in case the error occurred while sending the response.
         $response->isSent = false;
         $response->stream = null;
         $response->data = null;
         $response->content = null;
     } else {
         $response = new Response();
     }
     $useErrorView = $response->format === Response::FORMAT_HTML && !YII_DEBUG;
     //如果是用户定义的异常,则需要将异常错误信息抛出,如果是接口类型的并且有model类型的错误
     if ($useErrorView) {
         if ($this->errorAction !== null) {
             $result = Yii::$app->runAction($this->errorAction);
             if ($result instanceof Response) {
                 $result = $result;
             } else {
                 $result->data = $result;
             }
         } else {
             //在没有默认异常处理action的情况下,直接渲染文件
             $file = $useErrorView ? $this->errorView : $this->exceptionView;
             $responseData = $this->renderFile($file, ['exception' => $exception]);
         }
     } else {
         if ($response->format === Response::FORMAT_JSON || $response->format === Response::FORMAT_XML) {
             $response->data = ['code' => $exception->getCode(), 'message' => $exception->getMessage()];
             if ($exception instanceof LBUserException) {
                 $response->data['errors'] = $exception->getErrors();
             }
         } else {
             $response->data = $this->convertExceptionToArray($exception);
         }
     }
     //调试状态状态码为500, 非调试状态不抛出异常
     if (!YII_DEBUG || $exception instanceof LBUserException) {
         $response->setStatusCode(200);
     } else {
         $response->setStatusCode(500);
     }
     $response->send();
 }
 /**
  * @param string $seq
  * @param string $tag
  * @param boolean $passthru whether to send response to the browser or render it as plain text
  * @return Response
  * @throws HttpException
  */
 public function run($seq, $tag, $passthru = false)
 {
     $this->controller->loadData($tag);
     $timings = $this->panel->calculateTimings();
     if (!isset($timings[$seq])) {
         throw new HttpException(404, 'Log message not found.');
     }
     $requestInfo = $timings[$seq]['info'];
     $httpRequest = $this->createRequestFromLog($requestInfo);
     $httpResponse = $httpRequest->send();
     $httpResponse->getHeaders()->get('content-type');
     $response = new Response(['format' => Response::FORMAT_RAW]);
     if ($passthru) {
         foreach ($httpResponse->getHeaders() as $name => $value) {
             $response->getHeaders()->set($name, $value);
         }
         $response->content = $httpResponse->content;
         return $response;
     }
     $response->getHeaders()->add('content-type', 'text/plain');
     $response->content = $httpResponse->toString();
     return $response;
 }
Ejemplo n.º 26
0
 protected function response()
 {
     // Setting default format of response is json.
     Yii::$app->response->format = Response::FORMAT_JSON;
     Event::on(Response::className(), Response::EVENT_BEFORE_SEND, function ($event) {
         // Clean output.
         for ($level = ob_get_level(); $level > 0; --$level) {
             if (!@ob_end_clean()) {
                 ob_clean();
             }
         }
         /* @var $response \yii\web\Response */
         /* @var $event \yii\base\Event */
         $response = $event->sender;
     });
 }
Ejemplo n.º 27
0
 public function init()
 {
     parent::init();
     $this->on(Base::EVENT_BEFORE_SEND, function ($event) {
         $this->isBuffering = false;
         if (headers_sent()) {
             return;
         }
         if (ob_start('ob_gzhandler')) {
             $this->isBuffering = true;
         }
     });
     $this->on(Base::EVENT_AFTER_SEND, function ($event) {
         if ($this->isBuffering) {
             ob_end_flush();
             $this->isBuffering = false;
         }
     });
 }
 /**
  * Uploads the file and update database
  */
 public function run()
 {
     $file = UploadedFile::getInstanceByName('attachment[file]');
     $result = $this->insertMedia($file);
     $response = new Response();
     $response->setStatusCode(200);
     $response->format = Response::FORMAT_JSON;
     if ($result['success'] === true) {
         $response->setStatusCode(200);
         $response->data = ['file' => ['url' => '/' . $result['data']['source'], 'media_id' => $result['data']['id']]];
         $response->send();
     } else {
         $response->statusText = $result['message'];
         $response->setStatusCode(500);
         $response->send();
         Yii::$app->end();
     }
 }
Ejemplo n.º 29
0
 /**
  * Restores response properties from the given data
  * @param Response $response the response to be restored
  * @param array $data the response property data
  * @since 2.0.3
  */
 protected function restoreResponse($response, $data)
 {
     if (isset($data['format'])) {
         $response->format = $data['format'];
     }
     if (isset($data['version'])) {
         $response->version = $data['version'];
     }
     if (isset($data['statusCode'])) {
         $response->statusCode = $data['statusCode'];
     }
     if (isset($data['statusText'])) {
         $response->statusText = $data['statusText'];
     }
     if (isset($data['headers']) && is_array($data['headers'])) {
         $headers = $response->getHeaders()->toArray();
         $response->getHeaders()->fromArray(array_merge($data['headers'], $headers));
     }
     if (isset($data['cookies']) && is_array($data['cookies'])) {
         $cookies = $response->getCookies()->toArray();
         $response->getCookies()->fromArray(array_merge($data['cookies'], $cookies));
     }
 }
Ejemplo n.º 30
-1
 /**
  * https://github.com/yiisoft/yii2/issues/7529
  */
 public function testSendContentAsFile()
 {
     ob_start();
     $this->response->sendContentAsFile('test', 'test.txt')->send(['mimeType' => 'text/plain']);
     $content = ob_get_clean();
     static::assertEquals('test', $content);
     static::assertEquals(200, $this->response->statusCode);
     $headers = $this->response->headers;
     static::assertEquals('application/octet-stream', $headers->get('Content-Type'));
     static::assertEquals('attachment; filename="test.txt"', $headers->get('Content-Disposition'));
     static::assertEquals(4, $headers->get('Content-Length'));
 }