body() public method

Buffers the response message to be sent if $content is null the current buffer is returned
public body ( string | callable | null $content = null ) : string
$content string | callable | null the string or callable message to be sent
return string Current message buffer if $content param is passed as null
Example #1
7
 /**
  * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  *
  * @param string $view View to use for rendering
  * @param string $layout Layout to use
  * @return \Cake\Network\Response A response object containing the rendered view.
  * @link http://book.cakephp.org/3.0/en/controllers.html#rendering-a-view
  */
 public function render($view = null, $layout = null)
 {
     $builder = $this->viewBuilder();
     if (!$builder->templatePath()) {
         $builder->templatePath($this->_viewPath());
     }
     if (!empty($this->request->params['bare'])) {
         $builder->autoLayout(false);
     }
     $builder->className($this->viewClass);
     $this->autoRender = false;
     $event = $this->dispatchEvent('Controller.beforeRender');
     if ($event->result instanceof Response) {
         return $event->result;
     }
     if ($event->isStopped()) {
         return $this->response;
     }
     if ($builder->template() === null && isset($this->request->params['action'])) {
         $builder->template($this->request->params['action']);
     }
     $this->View = $this->createView();
     $this->response->body($this->View->render($view, $layout));
     return $this->response;
 }
Example #2
3
 public function afterDispatch(Event $event, Request $request, Response $response)
 {
     if (Configure::read('debug') || !isset($request->params['cache']) || $request->params['cache'] !== true) {
         return;
     }
     unset($request->params['cache']);
     $cacheKey = $this->_getCacheKey($request);
     if ($cacheKey !== false) {
         $content = $response->body();
         Cache::write($cacheKey, $content, 'wasabi/cms/pages');
     }
 }
 /**
  * Create the response.
  *
  * @param \League\Flysystem\FilesystemInterface $cache The cache file system.
  * @param string $path The cached file path.
  *
  * @return \Cake\Network\Response The response object.
  */
 public function create(FilesystemInterface $cache, $path)
 {
     $stream = $cache->readStream($path);
     $contentType = $cache->getMimetype($path);
     $contentLength = (string) $cache->getSize($path);
     $response = new Response();
     $response->type($contentType);
     $response->header('Content-Length', $contentLength);
     $response->body(function () use($stream) {
         rewind($stream);
         fpassthru($stream);
         fclose($stream);
     });
     return $response;
 }
 /**
  * Convert a CakePHP response into a PSR7 one.
  *
  * @param CakeResponse $response The CakePHP response to convert
  * @return PsrResponse $response The equivalent PSR7 response.
  */
 public static function toPsr(CakeResponse $response)
 {
     $status = $response->statusCode();
     $headers = $response->header();
     if (!isset($headers['Content-Type'])) {
         $headers['Content-Type'] = $response->type();
     }
     $body = $response->body();
     $stream = 'php://memory';
     if (is_string($body)) {
         $stream = new Stream('php://memory', 'wb');
         $stream->write($response->body());
     }
     if (is_callable($body)) {
         $stream = new CallbackStream($body);
     }
     // This is horrible, but CakePHP doesn't have a getFile() method just yet.
     $fileProp = new \ReflectionProperty($response, '_file');
     $fileProp->setAccessible(true);
     $file = $fileProp->getValue($response);
     if ($file) {
         $stream = new Stream($file->path, 'rb');
     }
     return new DiactorosResponse($stream, $status, $headers);
 }
 /**
  * @author Gaetan SENELLE
  * @return Response
  */
 public function render()
 {
     $response = new Response();
     $exception = $this->error;
     $code = $this->_code($exception);
     $message = $this->_message($exception, $code);
     $url = $this->controller->request->here();
     $isDebug = Configure::read('debug');
     $response->statusCode($code);
     if (method_exists($exception, 'responseHeader')) {
         $this->controller->response->header($exception->responseHeader());
     }
     $classname = get_class($exception);
     if (preg_match('@\\\\([\\w]+)$@', $classname, $matches)) {
         $classname = $matches[1];
     } else {
         $classname = null;
     }
     if (!$isDebug && !$exception instanceof ApiException && !$exception instanceof HttpException) {
         $classname = null;
     }
     $data = ['exception' => ['type' => $classname, 'message' => $message, 'url' => h($url), 'code' => $code], 'success' => false];
     $response->body(json_encode($data));
     $response->type('json');
     return $response;
 }
Example #6
1
 /**
  * Filters the cake response to the BrowserKit one.
  *
  * @param \Cake\Network\Response $response Cake response.
  * @return \Symfony\Component\BrowserKit\Response BrowserKit response.
  */
 protected function filterResponse($response)
 {
     $this->cake['response'] = $response;
     foreach ($response->cookie() as $cookie) {
         $this->getCookieJar()->set(new Cookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httpOnly']));
     }
     $response->sendHeaders();
     return new BrowserKitResponse($response->body(), $response->statusCode(), $response->header());
 }
 /**
  * @param \Cake\Network\Request $request Request to get authentication information from.
  * @param \Cake\Network\Response $response A response object that can have headers added.
  * @return bool|\Cake\Network\Response
  */
 public function unauthenticated(Request $request, Response $response)
 {
     if ($this->_config['continue']) {
         return false;
     }
     if (isset($this->_exception)) {
         $response->statusCode($this->_exception->httpStatusCode);
         $response->header($this->_exception->getHttpHeaders());
         $response->body(json_encode(['error' => $this->_exception->errorType, 'message' => $this->_exception->getMessage()]));
         return $response;
     }
     $message = __d('authenticate', 'You are not authenticated.');
     throw new BadRequestException($message);
 }
 /**
  * Main functionality to trigger maintenance mode.
  * Will automatically set the appropriate headers.
  *
  * Tip: Check for non CLI first
  *
  *  if (php_sapi_name() !== 'cli') {
  *    App::uses('MaintenanceLib', 'Setup.Lib');
  *    $Maintenance = new MaintenanceLib();
  *    $Maintenance->checkMaintenance();
  *  }
  *
  * @param string|null $ipAddress
  * @param bool $exit If Response should be sent and exited.
  * @return void
  * @deprecated Use Maintenance DispatcherFilter
  */
 public function checkMaintenance($ipAddress = null, $exit = true)
 {
     if ($ipAddress === null) {
         $ipAddress = env('REMOTE_ADDRESS');
     }
     if (!$this->isMaintenanceMode($ipAddress)) {
         return;
     }
     $Response = new Response();
     $Response->statusCode(503);
     $Response->header('Retry-After', DAY);
     $body = __d('setup', 'Maintenance work');
     $template = APP . 'Template' . DS . 'Error' . DS . $this->template;
     if (file_exists($template)) {
         $body = file_get_contents($template);
     }
     $Response->body($body);
     if ($exit) {
         $Response->send();
         exit;
     }
 }
Example #9
0
 /**
  * Tests the body method
  *
  * @return void
  */
 public function testBody()
 {
     $response = new Response();
     $this->assertNull($response->body());
     $response->body('Response body');
     $this->assertEquals('Response body', $response->body());
     $this->assertEquals('Changed Body', $response->body('Changed Body'));
 }
Example #10
0
 /**
  * test setting parameters in beforeDispatch method
  *
  * @return void
  */
 public function testQueryStringAndCustomTime()
 {
     $folder = CACHE . 'views' . DS;
     $file = $folder . 'posts-home-coffee-life-sleep-sissies-coffee-life-sleep-sissies.html';
     $content = '<!--cachetime:' . (time() + WEEK) . ';ext:html-->Foo bar';
     file_put_contents($file, $content);
     Router::reload();
     Router::connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
     Router::connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
     Router::connect('/:controller/:action/*');
     $_GET = ['coffee' => 'life', 'sleep' => 'sissies'];
     $filter = new CacheFilter();
     $request = new Request('posts/home/?coffee=life&sleep=sissies');
     $response = new Response();
     $event = new Event(__CLASS__, $this, compact('request', 'response'));
     $filter->beforeDispatch($event);
     $result = $response->body();
     $expected = '<!--created:';
     $this->assertTextStartsWith($expected, $result);
     $expected = '-->Foo bar';
     $this->assertTextEndsWith($expected, $result);
     $result = $response->type();
     $expected = 'text/html';
     $this->assertEquals($expected, $result);
     $result = $response->header();
     $this->assertNotEmpty($result['Expires']);
     // + 1 week
     unlink($file);
 }
 /**
  * Assert content exists in the response body.
  *
  * @param string $content The content to check for.
  * @param string $message The failure message that will be appended to the generated message.
  * @return void
  */
 public function assertResponseContains($content, $message = '')
 {
     if (!$this->_response) {
         $this->fail('No response set, cannot assert content. ' . $message);
     }
     $this->assertContains($content, $this->_response->body(), $message);
 }
 /**
  * Assert response content is empty.
  *
  * @param string $message The failure message that will be appended to the generated message.
  * @return void
  */
 public function assertResponseEmpty($message = '')
 {
     if (!$this->_response) {
         $this->fail('No response set, cannot assert content. ' . $message);
     }
     $this->assertEmpty((string) $this->_response->body(), $message);
 }
 /**
  * @param \Cake\Network\Request $request Request to get authentication information from.
  * @param \Cake\Network\Response $response A response object that can have headers added.
  * @return bool|\Cake\Network\Response
  */
 public function unauthenticated(Request $request, Response $response)
 {
     if ($this->_config['continue']) {
         return false;
     }
     if (isset($this->_exception)) {
         $response->statusCode($this->_exception->httpStatusCode);
         //add : to http code for cakephp (header method in Network/Response expects header separated with colon notation)
         $headers = $this->_exception->getHttpHeaders();
         $code = (string) $this->_exception->httpStatusCode;
         $headers = array_map(function ($header) use($code) {
             $pos = strpos($header, $code);
             if ($pos !== false) {
                 return substr($header, 0, $pos + strlen($code)) . ':' . substr($header, $pos + strlen($code) + 1);
             }
             return $header;
         }, $headers);
         $response->header($headers);
         $response->body(json_encode(['error' => $this->_exception->errorType, 'message' => $this->_exception->getMessage()]));
         return $response;
     }
     $message = __d('authenticate', 'You are not authenticated.');
     throw new BadRequestException($message);
 }
 /**
  * Handles (fakes) redirects for AJAX requests using requestAction()
  *
  * @param Event $event The Controller.beforeRedirect event.
  * @param string|array $url A string or array containing the redirect location
  * @param \Cake\Network\Response $response The response object.
  * @return void|\Cake\Network\Response The response object if the redirect is caught.
  */
 public function beforeRedirect(Event $event, $url, Response $response)
 {
     $request = $this->request;
     if (!$request->is('ajax')) {
         return;
     }
     if (empty($url)) {
         return;
     }
     if (is_array($url)) {
         $url = Router::url($url + ['_base' => false]);
     }
     $controller = $event->subject();
     $response->body($controller->requestAction($url, ['return', 'bare' => false, 'environment' => ['REQUEST_METHOD' => 'GET']]));
     $response->statusCode(200);
     return $response;
 }
Example #15
0
 /**
  * Sends an asset file to the client
  *
  * @param \Cake\Network\Request $request The request object to use.
  * @param \Cake\Network\Response $response The response object to use.
  * @param string $assetFile Path to the asset file in the file system
  * @param string $ext The extension of the file to determine its mime type
  * @return void
  */
 protected function _deliverCacheFile(Request $request, Response $response, $file, $ext)
 {
     $compressionEnabled = $response->compress();
     if ($response->type($ext) === $ext) {
         $contentType = 'application/octet-stream';
         $agent = $request->env('HTTP_USER_AGENT');
         if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
             $contentType = 'application/octetstream';
         }
         $response->type($contentType);
     }
     if (!$compressionEnabled) {
         $response->header('Content-Length', filesize($file));
     }
     $content = file_get_contents($file);
     $cacheInfo = $this->extractCacheInfo($content);
     $modifiedTime = filemtime($file);
     $cacheTime = $cacheInfo['time'];
     if (!$cacheTime) {
         $cacheTime = $this->_cacheTime;
     }
     $response->cache($modifiedTime, $cacheTime);
     $response->type($cacheInfo['ext']);
     if (Configure::read('debug') || $this->config('debug')) {
         if ($cacheInfo['ext'] === 'html') {
             $content = '<!--created:' . $modifiedTime . '-->' . $content;
         }
     }
     $response->body($content);
 }
Example #16
0
 /**
  * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  *
  * @param string $view View to use for rendering
  * @param string $layout Layout to use
  * @return \Cake\Network\Response A response object containing the rendered view.
  * @link http://book.cakephp.org/3.0/en/controllers.html#rendering-a-view
  */
 public function render($view = null, $layout = null)
 {
     if (!empty($this->request->params['bare'])) {
         $this->getView()->autoLayout = false;
     }
     $event = $this->dispatchEvent('Controller.beforeRender');
     if ($event->result instanceof Response) {
         $this->autoRender = false;
         return $event->result;
     }
     if ($event->isStopped()) {
         $this->autoRender = false;
         return $this->response;
     }
     $this->autoRender = false;
     $this->response->body($this->getView()->render($view, $layout));
     return $this->response;
 }
Example #17
0
 /**
  * Get the stream for the new response.
  *
  * @param \Cake\Network\Response $response The cake response to extract the body from.
  * @return \Psr\Http\Message\StreamInterface|string The stream.
  */
 protected static function getStream($response)
 {
     $stream = 'php://memory';
     $body = $response->body();
     if (is_string($body) && strlen($body)) {
         $stream = new Stream('php://memory', 'wb');
         $stream->write($body);
         return $stream;
     }
     if (is_callable($body)) {
         $stream = new CallbackStream($body);
         return $stream;
     }
     $file = $response->getFile();
     if ($file) {
         $stream = new Stream($file->path, 'rb');
         return $stream;
     }
     return $stream;
 }
 /**
  * Handles (fakes) redirects for AJAX requests using requestAction()
  *
  * @param Event $event The Controller.beforeRedirect event.
  * @param string|array $url A string or array containing the redirect location
  * @param \Cake\Network\Response $response The response object.
  * @return \Cake\Network\Response|null The response object if the redirect is caught.
  */
 public function beforeRedirect(Event $event, $url, Response $response)
 {
     $request = $this->request;
     if (!$request->is('ajax')) {
         return null;
     }
     if (empty($url)) {
         return null;
     }
     if (is_array($url)) {
         $url = Router::url($url + ['_base' => false]);
     }
     $query = [];
     if (strpos($url, '?') !== false) {
         list($url, $querystr) = explode('?', $url, 2);
         parse_str($querystr, $query);
     }
     $controller = $event->subject();
     $response->body($controller->requestAction($url, ['return', 'bare' => false, 'environment' => ['REQUEST_METHOD' => 'GET'], 'query' => $query]));
     $response->statusCode(200);
     return $response;
 }
Example #19
0
 /**
  * Injects the JS to build the toolbar.
  *
  * The toolbar will only be injected if the response's content type
  * contains HTML and there is a </body> tag.
  *
  * @param string $id ID to fetch data from.
  * @param \Cake\Network\Response $response The response to augment.
  * @return void
  */
 protected function _injectScripts($id, $response)
 {
     if (strpos($response->type(), 'html') === false) {
         return;
     }
     $body = $response->body();
     $pos = strrpos($body, '</body>');
     if ($pos === false) {
         return;
     }
     $url = Router::url('/', true);
     $script = "<script id=\"__debug_kit\" data-id=\"{$id}\" data-url=\"{$url}\" src=\"" . Router::url('/debug_kit/js/toolbar.js') . '"></script>';
     $body = substr($body, 0, $pos) . $script . substr($body, $pos);
     $response->body($body);
 }
Example #20
0
 /**
  * Injects the JS to build the toolbar.
  *
  * The toolbar will only be injected if the response's content type
  * contains HTML and there is a </body> tag.
  *
  * @param string $id ID to fetch data from.
  * @param \Cake\Network\Response $response The response to augment.
  * @return void
  */
 protected function _injectScripts($id, $response)
 {
     if (strpos($response->type(), 'html') === false) {
         return;
     }
     $body = $response->body();
     $pos = strrpos($body, '</body>');
     if ($pos === false) {
         return;
     }
     $url = Router::url('/', true);
     $script = "<script>var __debug_kit_id = '{$id}', __debug_kit_base_url = '{$url}';</script>";
     $script .= '<script src="' . Router::url('/debug_kit/js/toolbar.js') . '"></script>';
     $body = substr($body, 0, $pos) . $script . substr($body, $pos);
     $response->body($body);
 }
 /**
  * Test that afterDispatch does not modify response
  *
  * @return void
  */
 public function testAfterDispatchNoModifyResponse()
 {
     $request = new Request(['url' => '/articles']);
     $response = new Response(['statusCode' => 200, 'type' => 'application/json', 'body' => '{"some":"json"}']);
     $bar = new DebugBarFilter($this->events, []);
     $bar->setup();
     $event = new Event('Dispatcher.afterDispatch', $bar, compact('request', 'response'));
     $bar->afterDispatch($event);
     $this->assertTextEquals('{"some":"json"}', $response->body());
 }
 /**
  * Handles (fakes) redirects for Ajax requests using requestAction()
  * Modifies the $_POST and $_SERVER['REQUEST_METHOD'] to simulate a new GET request.
  *
  * @param Event $event The Controller.beforeRedirect event.
  * @param string|array $url A string or array containing the redirect location
  * @param \Cake\Network\Response $response The response object.
  * @return void
  */
 public function beforeRedirect(Event $event, $url, $response)
 {
     if (!$this->request->is('ajax')) {
         return;
     }
     if (empty($url)) {
         return;
     }
     $_SERVER['REQUEST_METHOD'] = 'GET';
     foreach ($_POST as $key => $val) {
         unset($_POST[$key]);
     }
     if (is_array($url)) {
         $url = Router::url($url + array('base' => false));
     }
     $controller = $event->subject();
     $response->body($controller->requestAction($url, array('return', 'bare' => false)));
     $response->send();
     $response->stop();
 }
Example #23
0
 /**
  * Injects the JS to build the toolbar.
  *
  * The toolbar will only be injected if the response's content type
  * contains HTML and there is a </body> tag.
  *
  * @param \Cake\Network\Response $response The response to augment.
  *
  * @return void
  */
 protected function _injectScriptsAndStyles($response)
 {
     if (strpos($response->type(), 'html') === false) {
         return;
     }
     $body = $response->body();
     //add scripts
     $pos = strrpos($body, '</body>');
     if ($pos !== false) {
         $script = '<script src="' . Router::url('/debug_http/js/highlight.min.js') . '"></script>';
         $script .= '<script src="' . Router::url('/debug_http/js/clipboard.min.js') . '"></script>';
         $body = substr($body, 0, $pos) . $script . substr($body, $pos);
     }
     //add styles
     $pos = strrpos($body, '</head>');
     if ($pos !== false) {
         $style = '<link rel="stylesheet" type="text/css" href="' . Router::url('/debug_http/css/requests.css') . '">';
         $style .= '<link rel="stylesheet" type="text/css" href="' . Router::url('/debug_http/css/highlight.min.css') . '">';
         $body = substr($body, 0, $pos) . $style . substr($body, $pos);
     }
     $response->body($body);
 }
 /**
  * Generates the unauthorized response
  * @param \Cake\Network\Response $response A response object.
  * @return \Cake\Network\Response
  */
 private function unauthorizedResponse($response)
 {
     $response->statusCode(403);
     $response->body(json_encode((object) ['message' => 'Error al verificar el token de autorizaciĆ³n, no tiene permiso para acceder a la aplicaciĆ³n', 'code' => 403]));
     return $response;
 }
 public function testToPsrBodyCallable()
 {
     $cake = new CakeResponse(['status' => 200]);
     $cake->body(function () {
         return 'callback response';
     });
     $result = ResponseTransformer::toPsr($cake);
     $this->assertSame('callback response', '' . $result->getBody());
 }
Example #26
-2
 /**
  * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  *
  * @param string $view View to use for rendering
  * @param string $layout Layout to use
  * @return \Cake\Network\Response A response object containing the rendered view.
  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
  */
 public function render($view = null, $layout = null)
 {
     $event = new Event('Controller.beforeRender', $this);
     $event = $this->getEventManager()->dispatch($event);
     if ($event->result instanceof Response) {
         $this->autoRender = false;
         return $event->result;
     }
     if ($event->isStopped()) {
         $this->autoRender = false;
         return $this->response;
     }
     $this->View = $this->createView();
     $this->autoRender = false;
     $this->response->body($this->View->render($view, $layout));
     return $this->response;
 }