예제 #1
0
 /**
  * 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);
 }
예제 #2
0
 /**
  * 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);
 }
예제 #3
0
 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));
     }
 }
예제 #5
0
 /**
  * Proxy to PsrResponseInterface::withBody()
  *
  * {@inheritdoc}
  */
 public function withBody(StreamInterface $body)
 {
     if ($this->complete) {
         return $this;
     }
     $new = $this->psrResponse->withBody($body);
     return new self($new);
 }
예제 #6
0
 /**
  * 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);
 }
예제 #7
0
 /**
  * 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());
 }
예제 #8
0
 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));
 }
예제 #9
0
 /**
  * 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');
 }
예제 #10
0
 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')));
 }
예제 #11
0
 /**
  * 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;
 }
예제 #12
0
 /**
  * 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)));
 }
예제 #13
0
 /**
  * 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);
 }
예제 #15
0
 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;
 }
예제 #16
0
 /**
  * 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;
 }
예제 #17
0
 /**
  * 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);
 }
예제 #18
0
 /**
  * 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;
 }
예제 #19
0
 /**
  * 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;
 }
예제 #20
0
파일: Response.php 프로젝트: ezimuel/tonis
 /**
  * {@inheritDoc}
  */
 public function withBody(StreamInterface $body)
 {
     return new self($this->app, $this->decorated->withBody($body));
 }
예제 #21
0
 /**
  * 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);
 }
예제 #23
0
 public function withJsonBody($data, string $contentType = 'application/json') : ResponseInterface
 {
     return $this->response->withBody(stream_for(json_encode($data)))->withHeader('Content-Type', $contentType);
 }
예제 #24
0
 /**
  * {@inheritdoc}
  */
 public function withBody(StreamInterface $body)
 {
     return new HttpException($this->response->withBody($body), $this->attributes);
 }
예제 #25
0
 /** @return Resource */
 private function createResourceFromObject(stdClass $object)
 {
     $processor = new self();
     return $processor->process($this->response->withBody($this->createStream(json_encode($object))), $this->fetcher);
 }
예제 #26
0
 /**
  * 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);
 }
예제 #27
0
 /**
  * @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);
 }
예제 #28
0
 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)));
 }
예제 #29
0
 /**
  * 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);
 }
예제 #30
0
 /**
  * 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));
 }