/** * Create response. * @param FilesystemInterface $cache Cache file system. * @param string $path Cached file path. * @return Response Response object. */ public function create(FilesystemInterface $cache, $path) { $stream = $this->streamCallback->__invoke($cache->readStream($path)); $contentType = $cache->getMimetype($path); $contentLength = (string) $cache->getSize($path); $cacheControl = 'max-age=31536000, public'; $expires = date_create('+1 years')->format('D, d M Y H:i:s') . ' GMT'; return $this->response->withBody($stream)->withHeader('Content-Type', $contentType)->withHeader('Content-Length', $contentLength)->withHeader('Cache-Control', $cacheControl)->withHeader('Expires', $expires); }
/** * Create response. * @param FilesystemInterface $cache Cache file system. * @param string $path Cached file path. * @return ResponseInterface Response object. */ public function create(FilesystemInterface $cache, $path) { $stream = $this->streamCallback->__invoke($cache->readStream($path)); $contentType = $cache->getMimetype($path); $contentLength = (string) $cache->getSize($path); $cacheControl = 'max-age=31536000, public'; $expires = date_create('+1 years')->format('D, d M Y H:i:s') . ' GMT'; if ($contentType === false) { throw new FilesystemException('Unable to determine the image content type.'); } if ($contentLength === false) { throw new FilesystemException('Unable to determine the image content length.'); } return $this->response->withBody($stream)->withHeader('Content-Type', $contentType)->withHeader('Content-Length', $contentLength)->withHeader('Cache-Control', $cacheControl)->withHeader('Expires', $expires); }
public function render(ResponseInterface $response, $templateName, array $data = []) { $source = $this->fetch($templateName, $data); $body = $response->getBody(); $body->write($source); return $response->withBody($body); }
public function __wakeup() { // We re-create the stream of the response if ($this->response !== null) { $this->response = $this->response->withBody(\GuzzleHttp\Psr7\stream_for($this->responseBody)); } }
/** * Proxy to PsrResponseInterface::withBody() * * {@inheritdoc} */ public function withBody(StreamInterface $body) { if ($this->complete) { return $this; } $new = $this->psrResponse->withBody($body); return new self($new); }
/** * Proxy to PsrResponseInterface::withBody() * * {@inheritdoc} * @throws RuntimeException if response is already completed */ public function withBody(StreamInterface $body) { if ($this->complete) { throw $this->responseIsAlreadyCompleted(__METHOD__); } $new = $this->psrResponse->withBody($body); return new self($new); }
/** * Transform the image. * * @param ResponseInterface $response * @param string $transform * * @return ResponseInterface */ private function transform(ResponseInterface $response, $transform) { $image = Image::createFromString((string) $response->getBody()); $image->transform($transform); $body = Middleware::createStream(); $body->write($image->getString()); return $response->withBody($body)->withHeader('Content-Type', $image->getMimeType()); }
public function marshalResponse(ViewModelInterface $model, ResponseInterface $response) { $template = $model->getTemplate(); $vars = $model->getVariables(); $stream = $response->getBody()->detach(); $this->assign($vars); $this->render($template, $stream); return $response->withBody(new Stream($stream)); }
/** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { if ($request->getUri()->getPath() === '/robots.txt') { $body = Middleware::createStream(); $body->write("User-Agent: *\nDisallow: /"); return $response->withBody($body); } $response = $next($request, $response); return $response->withHeader(self::HEADER, 'noindex, nofollow, noarchive'); }
private function fetchFromCache(string $id, Response $res) { $cachePath = sprintf('%s/%s', $this->cachePath, $id); if (!file_exists($cachePath)) { // Nothing in cache, but should be cached return false; } // Cache hit! return $res->withBody(new Stream(fopen($cachePath, 'r'))); }
/** * Insert content into all POST forms. * * @param ResponseInterface $response * @param callable $replace * * @return ResponseInterface */ private function insertIntoPostForms(ResponseInterface $response, callable $replace) { $html = (string) $response->getBody(); $html = preg_replace_callback('/(<form\\s[^>]*method=["\']?POST["\']?[^>]*>)/i', $replace, $html, -1, $count); if (!empty($count)) { $body = self::createStream(); $body->write($html); return $response->withBody($body); } return $response; }
/** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { if ($request->getMethod() !== 'GET') { return $response->withStatus(405); } $file = $this->getFilename($request); if (!is_file($file)) { return $response->withStatus(404); } return $next($request, $response->withBody(Middleware::createStream($file))); }
/** * Process an incoming error, along with associated request and response. * * Accepts an error, a server-side request, and a response instance, and * does something with them; if further processing can be done, it can * delegate to `$out`. * * @see MiddlewareInterface * @param mixed $error * @param Request $request * @param Response $response * @param null|callable $out * @return null|Response */ public function __invoke($error, Request $request, Response $response, callable $out = null) { //Show error in browser if display_errors is on in php.ini if ($this->displayErrors) { $body = $response->getBody(); $body->write($error); return $response->withBody($body); } $body = $response->getBody(); $body->write('500 Internal Server Error'); return $response->withStatus(500)->withBody($body); }
/** * Inject some code just before any tag. * * @param ResponseInterface $response * @param string $code * @param string $tag * * @return ResponseInterface */ private function inject(ResponseInterface $response, $code, $tag = 'body') { $html = (string) $response->getBody(); $pos = strripos($html, "</{$tag}>"); if ($pos === false) { $response->getBody()->write($code); return $response; } $body = self::createStream(); $body->write(substr($html, 0, $pos) . $code . substr($html, $pos)); return $response->withBody($body); }
public function after(ResponseInterface $response) { if (config('micro_debug.handlers.fire_php')) { $db = \app('db'); if ($db) { $profiler = $db->getProfiler(); if ($profiler->getEnabled()) { $totalTime = $profiler->getTotalElapsedSecs(); $queryCount = $profiler->getTotalNumQueries(); $longestTime = 0; $longestQuery = \null; $total = sprintf('%.6f', microtime(\true) - $_SERVER['REQUEST_TIME_FLOAT']); $label = 'Executed ' . $queryCount . ' queries in ' . sprintf('%.6f', $totalTime) . ' seconds. (' . ($total ? \round($totalTime / $total * 100, 2) : 0) . '%)'; $table = []; $table[] = ['Time', 'Event', 'Parameters']; if ($profiler->getQueryProfiles()) { foreach ($profiler->getQueryProfiles() as $k => $query) { if ($query->getElapsedSecs() > $longestTime) { $longestTime = $query->getElapsedSecs(); $longestQuery = $k; } } foreach ($profiler->getQueryProfiles() as $k => $query) { $table[] = [\sprintf('%.6f', $query->getElapsedSecs()) . ($k == $longestQuery ? ' !!!' : ''), $query->getQuery(), ($params = $query->getQueryParams()) ? $params : \null]; } } FirePHP\FirePHP::getInstance()->table('DB - ' . $label, $table); } } } if (\config('micro_debug.handlers.dev_tools')) { if ($response instanceof HtmlResponse) { $body = $response->getBody(); if ($body->isSeekable()) { $body->rewind(); } $b = $body->getContents(); $b = explode('</body>', $b); $b[0] .= str_replace(array("\n", "\t", "\r"), "", $this->view->render()) . '</body>'; $response->withBody(new TempStream(implode('', $b))); } } if (($fileForCache = \config('micro_debug.handlers.performance')) !== \null) { $forStore = []; foreach (\MicroLoader::getFiles() as $class => $file) { if (\substr($class, 0, 6) === 'Micro\\') { $forStore[$class] = $file; } } \file_put_contents($fileForCache, "<?php\nreturn " . \var_export($forStore, \true) . ";", \LOCK_EX); } return $response; }
/** * Insert content into all POST forms. * * @param ResponseInterface $response * @param string $input * * @return ResponseInterface */ protected function insertIntoPostForms(ResponseInterface $response, $input) { $html = (string) $response->getBody(); $html = preg_replace_callback('/(<form\\s[^>]*method="?POST"?[^>]*>)/i', function ($match) use($input) { return $match[0] . $input; }, $html, -1, $count); if ($count) { $body = Middleware::createStream(); $body->write($html); return $response->withBody($body); } return $response; }
/** * Renders a template with given name to Response object. * * @param string $templateName Name of the template to render. * @param ResponseInterface $response Response object to write a result. * @param array $vars Variables to render in the array in a form of a template. * * @return ResponseInterface Response object with rendered template. */ public function renderTemplate($templateName, ResponseInterface $response, array $vars) { $body = $response->getBody(); if (!$body->isWritable()) { throw new \RuntimeException('Response body must be writeable.'); } ob_start(); extract($vars, EXTR_PREFIX_SAME, "wddx"); require "{$this->templatesDir}/{$templateName}"; $body->write(ob_get_clean()); ob_end_clean(); return $response->withBody($body); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if (!Middleware::hasAttribute($request, FormatNegotiator::KEY)) { throw new RuntimeException('This middleware needs FormatNegotiator executed before'); } $renderer = $this->debugBar->getJavascriptRenderer(); //Is an asset? $path = $request->getUri()->getPath(); $renderPath = $renderer->getBaseUrl(); if (strpos($path, $renderPath) === 0) { $file = $renderer->getBasePath() . substr($path, strlen($renderPath)); if (file_exists($file)) { $body = Middleware::createStream(); $body->write(file_get_contents($file)); return $response->withBody($body); } } $response = $next($request, $response); //Fix the render baseUrl $renderPath = Utils\Helpers::joinPath(BasePath::getBasePath($request), $renderer->getBaseUrl()); $renderer->setBaseUrl($renderPath); $ajax = Utils\Helpers::isAjax($request); //Redirection response if (Utils\Helpers::isRedirect($response)) { if ($this->debugBar->isDataPersisted() || session_status() === PHP_SESSION_ACTIVE) { $this->debugBar->stackData(); } //Html response } elseif (FormatNegotiator::getFormat($request) === 'html') { if (!$ajax) { $response = $this->inject($response, $renderer->renderHead(), 'head'); } $response = $this->inject($response, $renderer->render(!$ajax), 'body'); //Ajax response } elseif ($ajax && $this->captureAjax) { $headers = $this->debugBar->getDataAsHeaders(); foreach ($headers as $name => $value) { $response = $response->withHeader($name, $value); } } return $response; }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $renderer = $this->debugBar->getJavascriptRenderer(); //Is an asset? $path = $request->getUri()->getPath(); $renderPath = $renderer->getBaseUrl(); if (strpos($path, $renderPath) === 0) { $file = $renderer->getBasePath() . substr($path, strlen($renderPath)); if (file_exists($file)) { return $response->withBody(self::createStream($file, 'r')); } } $response = $next($request, $response); //Fix the render baseUrl $generator = BasePath::getGenerator($request); if ($generator) { $renderer->setBaseUrl($generator($renderer->getBaseUrl())); } $ajax = Utils\Helpers::isAjax($request); //Redirection response if (Utils\Helpers::isRedirect($response)) { if ($this->debugBar->isDataPersisted() || session_status() === PHP_SESSION_ACTIVE) { $this->debugBar->stackData(); } //Html response } elseif (Utils\Helpers::getMimeType($response) === 'text/html') { if (!$ajax) { $response = $this->inject($response, $renderer->renderHead(), 'head'); } $response = $this->inject($response, $renderer->render(!$ajax), 'body'); //Ajax response } elseif ($ajax && $this->captureAjax) { $headers = $this->debugBar->getDataAsHeaders(); foreach ($headers as $name => $value) { $response = $response->withHeader($name, $value); } } return $response; }
/** * {@inheritDoc} */ public function withBody(StreamInterface $body) { return new self($this->app, $this->decorated->withBody($body)); }
/** * Return an instance with the specified message body. * * The body MUST be a StreamInterface object. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return a new instance that has the * new body stream. * * @param StreamInterface $body Body. * @return self * @throws \InvalidArgumentException When the body is not valid. */ function withBody(StreamInterface $body) { return $this->response->withBody($body); }
/** * Render content of template and write it to response body. * Does not remove previous body content. * @param ResponseInterface $response * @return ResponseInterface */ public function renderToReponse(ResponseInterface $response) : ResponseInterface { $body = $response->getBody(); $body->write($this->render()); return $response->withBody($body); }
public function withJsonBody($data, string $contentType = 'application/json') : ResponseInterface { return $this->response->withBody(stream_for(json_encode($data)))->withHeader('Content-Type', $contentType); }
/** * {@inheritdoc} */ public function withBody(StreamInterface $body) { return new HttpException($this->response->withBody($body), $this->attributes); }
/** @return Resource */ private function createResourceFromObject(stdClass $object) { $processor = new self(); return $processor->process($this->response->withBody($this->createStream(json_encode($object))), $this->fetcher); }
/** * HTML minifier. * * @param ResponseInterface $response * * @return ResponseInterface */ public function html(ResponseInterface $response) { $stream = Middleware::createStream(); $stream->write(Minify_HTML::minify((string) $response->getBody(), ['jsCleanComments' => true])); return $response->withBody($stream); }
/** * @param ResponseInterface $response * @param string $contents * * @return ResponseInterface */ private function withNewBody(ResponseInterface $response, $contents) { $body = new Body(fopen('php://temp', 'r+')); $body->write($contents); return $response->withBody($body); }
public function attachStream(ResponseInterface $response, Template $template) { $template = $template->withData($this->data->withData($template->getData())); return $response->withBody(new TemplateStream(new TemplateRender($this->getEngineForTemplate($template), $template))); }
/** * Minify js code. * * @param ResponseInterface $response * * @return ResponseInterface */ protected function minifyJs(ResponseInterface $response) { $stream = Middleware::createStream(); $stream->write(JsMinify::minify((string) $response->getBody())); return $response->withBody($stream); }
/** * Sends an asset file to the client * * @param \Psr\Http\Message\ServerRequestInterface $request The request object to use. * @param \Psr\Http\Message\ResponseInterface $response The response object to use. * @param \Cake\Filesystem\File $file The file wrapper for the file. * @return \Psr\Http\Message\ResponseInterface The response with the file & headers. */ protected function deliverAsset(ServerRequestInterface $request, ResponseInterface $response, $file) { $contentType = $this->getType($file); $modified = $file->lastChange(); $expire = strtotime($this->cacheTime); $maxAge = $expire - time(); $stream = new Stream(fopen($file->path, 'rb')); return $response->withBody($stream)->withHeader('Content-Type', $contentType)->withHeader('Cache-Control', 'public,max-age=' . $maxAge)->withHeader('Date', gmdate('D, j M Y G:i:s \\G\\M\\T', time()))->withHeader('Last-Modified', gmdate('D, j M Y G:i:s \\G\\M\\T', $modified))->withHeader('Expires', gmdate('D, j M Y G:i:s \\G\\M\\T', $expire)); }