### Setting the content type
type('jpg');
### Returning the current content type
type();
### Storing content type definitions
type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);
### Replacing a content type definition
type(['jpg' => 'text/plain']);
/** * 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; }
/** * testRenderWithView method * * @return void */ public function testRenderWithView() { $Request = new Request(); $Response = new Response(); $Controller = new Controller($Request, $Response); $Controller->name = 'Posts'; $Controller->viewPath = 'Posts'; $data = array(array('User' => array('username' => 'user1')), array('User' => array('username' => 'user2'))); $Controller->set('users', $data); $Controller->viewClass = 'Xml'; $View = $Controller->createView(); $output = $View->render('index'); $expected = array('users' => array('user' => array('user1', 'user2'))); $expected = Xml::build($expected)->asXML(); $this->assertSame($expected, $output); $this->assertSame('application/xml', $Response->type()); $this->assertInstanceOf('Cake\\View\\HelperRegistry', $View->helpers()); }
/** * Test render with a View file specified. * * @return void */ public function testRenderWithView() { $Request = new Request(); $Response = new Response(); $Controller = new Controller($Request, $Response); $Controller->name = 'Posts'; $data = ['User' => ['username' => 'fake'], 'Item' => [['name' => 'item1'], ['name' => 'item2']]]; $Controller->set('user', $data); $Controller->viewClass = 'Json'; $View = $Controller->createView(); $View->viewPath = $Controller->name; $output = $View->render('index'); $expected = json_encode(['user' => 'fake', 'list' => ['item1', 'item2'], 'paging' => null]); $this->assertSame($expected, $output); $this->assertSame('application/json', $Response->type()); }
/** * 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); }
public function testToPsrContentType() { $cake = new CakeResponse(); $cake->type('js'); $result = ResponseTransformer::toPsr($cake); $this->assertSame('application/javascript', $result->getHeaderLine('Content-Type')); }
/** * Asserts content type * * @param string $type The content-type to check for. * @param string $message The failure message that will be appended to the generated message. * @return void */ public function assertContentType($type, $message = '') { if (!$this->_response) { $this->fail('No response set, cannot assert content-type. ' . $message); } $alias = $this->_response->getMimeType($type); if ($alias !== false) { $type = $alias; } $result = $this->_response->type(); $this->assertEquals($type, $result, $message); }
/** * 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 _deliverAsset(Request $request, Response $response, $assetFile, $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($assetFile)); } // $response->cache(filemtime($assetFile), $this->_cacheTime); $response->sendHeaders(); readfile($assetFile); if ($compressionEnabled) { ob_end_flush(); } }
/** * Handle unauthenticated access attempt. In implementation valid return values * can be: * * - Null - No action taken, AuthComponent should return appropriate response. * - Cake\Network\Response - A response object, which will cause AuthComponent to * simply return that response. * * @param \Cake\Network\Request $request A request object. * @param \Cake\Network\Response $response A response object. * @return \Cake\Network\Response|bool */ public function unauthenticated(Request $request, Response $response) { $response->type('json'); $deviceId = $request->header($this->config('headerDeviceId')); $token = $request->header($this->config('headerToken')); if ($deviceId == null || $token == null) { return $this->unauthorizedResponse($response); } $generatedToken = $this->generateToken($deviceId); //Log::debug("CREATED TOKEN: ".$generatedToken); //Log::debug("SENT TOKEN: ".$token); if ($token != $generatedToken) { return $this->unauthorizedResponse($response); } return true; }
/** * RssViewTest::testSerializeWithArrayLinks() * * `'atom:link' => array('@href' => array(...)` becomes * '@rel' => 'self', '@type' => 'application/rss+xml' automatically set for atom:link * * @return void */ public function testSerializeWithArrayLinks() { $Request = new Request(); $Response = new Response(); $data = ['channel' => ['title' => 'Channel title', 'link' => 'http://channel.example.org', 'atom:link' => ['@href' => ['controller' => 'foo', 'action' => 'bar']], 'description' => 'Channel description'], 'items' => [['title' => 'Title One', 'link' => ['controller' => 'foo', 'action' => 'bar'], 'description' => 'Content one'], ['title' => 'Title Two', 'link' => ['controller' => 'foo', 'action' => 'bar'], 'description' => 'Content two']]]; $viewVars = ['channel' => $data, '_serialize' => 'channel']; $View = new RssView($Request, $Response, null, ['viewVars' => $viewVars]); $result = $View->render(false); $expected = <<<RSS <?xml version="1.0" encoding="UTF-8"?> <rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"> <channel> <title>Channel title</title> <link>http://channel.example.org</link> <atom:link href="{$this->baseUrl}/foo/bar" rel="self" type="application/rss+xml"/> <description>Channel description</description> <item> <title>Title One</title> <link>{$this->baseUrl}/foo/bar</link> <description>Content one</description> </item> <item> <title>Title Two</title> <link>{$this->baseUrl}/foo/bar</link> <description>Content two</description> </item> </channel> </rss> RSS; //debug($result); $this->assertSame('application/rss+xml', $Response->type()); $this->assertTextEquals($expected, $result); }
/** * 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); }
/** * Add in the Content-Type header if necessary. * * @param array $headers The headers to update * @param \Cake\Network\Response $response The CakePHP response to convert * @return array The updated headers. */ protected static function setContentType($headers, $response) { if (isset($headers['Content-Type'])) { return $headers; } if (in_array($response->statusCode(), [204, 304])) { return $headers; } $whitelist = ['application/javascript', 'application/json', 'application/xml', 'application/rss+xml']; $type = $response->type(); $charset = $response->charset(); $hasCharset = false; if ($charset && (strpos($type, 'text/') === 0 || in_array($type, $whitelist))) { $hasCharset = true; } $value = $type; if ($hasCharset) { $value = "{$type}; charset={$charset}"; } $headers['Content-Type'] = $value; return $headers; }
public function _testRender() { $Request = new Request(); $Response = new Response(); $Controller = new AjaxComponentTestController($Request, $Response); $Controller->viewBuilder()->className('Ajax.Ajax'); $Controller->viewBuilder()->template('myTest'); $Controller->viewBuilder()->templatePath('AjaxComponentTest'); $Controller->myTest(); //$Controller->subDir = false; $result = $Controller->render(); $this->assertSame('application/json', $Response->type()); $expected = ['error' => null, 'content' => 'My Index Test ctp']; $expected = json_encode($expected); $this->assertTextEquals($expected, $result); }
/** * Returns the current response type (Content-type header), or null if not alias exists * * @return mixed A string content type alias, or raw content type if no alias map exists, * otherwise null */ public function responseType() { return $this->response->mapType($this->response->type()); }
/** * 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); }
/** * 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); }
/** * Tests the type method * * @return void */ public function testType() { $response = new Response(); $this->assertEquals('text/html', $response->type()); $response->type('pdf'); $this->assertEquals('application/pdf', $response->type()); $this->assertEquals('application/crazy-mime', $response->type('application/crazy-mime')); $this->assertEquals('application/json', $response->type('json')); $this->assertEquals('text/vnd.wap.wml', $response->type('wap')); $this->assertEquals('application/vnd.wap.xhtml+xml', $response->type('xhtml-mobile')); $this->assertEquals('text/csv', $response->type('csv')); $response->type(['keynote' => 'application/keynote', 'bat' => 'application/bat']); $this->assertEquals('application/keynote', $response->type('keynote')); $this->assertEquals('application/bat', $response->type('bat')); $this->assertFalse($response->type('wackytype')); }
/** * 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); }