public function testMinify() { $body = <<<EOT <!DOCTYPE html> <html> <head> <title>Title</title> <style type="text/css"> .is-red { color: red; } </style> </head> <body> <h1>Hello world!</h1> <script type="text/javascript"> document.querySelector('h1').className = 'is-red'; </script> </body> </html> EOT; $body_minified = <<<EOT <!DOCTYPE html><html><head><title>Title</title><style type="text/css">.is-red{color:red}</style></head><body><h1>Hello world!</h1> <script type="text/javascript">document.querySelector('h1').className='is-red'</script> </body></html> EOT; $response = $this->response(['Content-Type' => 'text/html']); $response->getBody()->write($body); $dispatcher = $this->dispatcher([Middleware::Minify()]); $response = $dispatcher($this->request(), $response); $this->assertEquals($body_minified, (string) $response->getBody()); }
/** * 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('Csrf middleware needs FormatNegotiator executed before'); } if (!Middleware::hasAttribute($request, ClientIp::KEY)) { throw new RuntimeException('Csrf middleware needs ClientIp executed before'); } if ($this->storage === null) { if (session_status() !== PHP_SESSION_ACTIVE) { throw new RuntimeException('Csrf middleware needs an active php session or a storage defined'); } if (!isset($_SESSION[$this->sessionIndex])) { $_SESSION[$this->sessionIndex] = []; } $this->storage =& $_SESSION[$this->sessionIndex]; } if (FormatNegotiator::getFormat($request) !== 'html') { return $next($request, $response); } if (Utils\Helpers::isPost($request) && !$this->validateRequest($request)) { return $response->withStatus(403); } $response = $next($request, $response); return $this->insertIntoPostForms($response, function ($match) use($request) { preg_match('/action=["\']?([^"\'\\s]+)["\']?/i', $match[0], $matches); $action = empty($matches[1]) ? $request->getUri()->getPath() : $matches[1]; return $match[0] . $this->generateTokens($request, $action); }); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { //If basePath does not match if (!$this->testBasePath($request->getUri()->getPath())) { return $next($request, $response); } //If the method is not allowed if ($request->getMethod() !== 'GET') { return $response->withStatus(405); } $body = Middleware::createStream(); $file = $this->getFilename($request); //If the file does not exists, check if is gzipped if (!is_file($file)) { $file .= '.gz'; if (EncodingNegotiator::getEncoding($request) !== 'gzip' || !is_file($file)) { return $response->withStatus(404); } $response = $response->withHeader('Content-Encoding', 'gzip'); } self::readFile($file, $body); $response = $response->withBody($body); //Handle range header $response = $this->range($request, $response); return $next($request, $response); }
/** * 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'); } $ajax = Utils\Helpers::isAjax($request); $debugBar = $this->debugBar ?: new StandardDebugBar(); //Redirection response if (Utils\Helpers::isRedirect($response)) { if ($debugBar->isDataPersisted() || session_status() === PHP_SESSION_ACTIVE) { $debugBar->stackData(); } //Html response } elseif (FormatNegotiator::getFormat($request) === 'html') { $renderer = $debugBar->getJavascriptRenderer(); ob_start(); echo '<style>'; $renderer->dumpCssAssets(); echo '</style>'; echo '<script>'; $renderer->dumpJsAssets(); echo '</script>'; echo $renderer->render(!$ajax); $response = $this->inject($response, ob_get_clean()); //Ajax response } elseif ($ajax && $this->captureAjax) { $headers = $debugBar->getDataAsHeaders(); foreach ($headers as $name => $value) { $response = $response->withHeader($name, $value); } } return $next($request, $response); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if ($this->login($request, $username)) { return $next(Middleware::setAttribute($request, self::KEY, $username), $response); } return $response->withStatus(401)->withHeader('WWW-Authenticate', 'Digest realm="' . $this->realm . '",qop="auth",nonce="' . ($this->nonce ?: uniqid()) . '",opaque="' . md5($this->realm) . '"'); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if (empty($this->router)) { throw new RuntimeException('No RouterContainer instance has been provided'); } $matcher = $this->router->getMatcher(); $route = $matcher->match($request); if (!$route) { $failedRoute = $matcher->getFailedRoute(); switch ($failedRoute->failedRule) { case 'Aura\\Router\\Rule\\Allows': return $response->withStatus(405); // 405 METHOD NOT ALLOWED // 405 METHOD NOT ALLOWED case 'Aura\\Router\\Rule\\Accepts': return $response->withStatus(406); // 406 NOT ACCEPTABLE // 406 NOT ACCEPTABLE default: return $response->withStatus(404); // 404 NOT FOUND } } $request = Middleware::setAttribute($request, self::KEY, $route); foreach ($route->attributes as $name => $value) { $request = $request->withAttribute($name, $value); } $response = $this->executeCallable($route->handler, $request, $response); return $next($request, $response); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { foreach ($this->mapping as $middleware => $attribute) { $request = $request->withAttribute($attribute, Middleware::getAttribute($request, $middleware)); } return $next($request, $response); }
/** * @dataProvider formatsProvider */ public function testTypes($url, $accept, $format) { $response = $this->execute([Middleware::FormatNegotiator(), function ($request, $response, $next) { $response->getBody()->write($request->getAttribute('FORMAT')); return $response; }], $url, ['Accept' => $accept]); $this->assertEquals($format, (string) $response->getBody()); }
/** * @dataProvider languagesProvider */ public function testLanguages($acceptLanguage, array $languages, $language) { $response = $this->execute([Middleware::LanguageNegotiator($languages), function ($request, $response, $next) use($language) { $response->getBody()->write($request->getAttribute('LANGUAGE')); return $response; }], '', ['Accept-Language' => $acceptLanguage]); $this->assertEquals($language, (string) $response->getBody()); }
/** * @dataProvider pathsProvider */ public function testTrailingSlash($url, $result, $basePath) { $response = $this->execute([Middleware::trailingSlash()->basePath($basePath), function ($request, $response, $next) { $response->getBody()->write($request->getUri()->getPath()); return $response; }], $url); $this->assertEquals($result, (string) $response->getBody()); }
/** * 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()); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $authorization = self::parseAuthorizationHeader($request->getHeaderLine('Authorization')); if ($authorization && $this->checkUserPassword($authorization['username'], $authorization['password'])) { return $next(Middleware::setAttribute($request, self::KEY, $authorization['username']), $response); } return $response->withStatus(401)->withHeader('WWW-Authenticate', 'Basic realm="' . $this->realm . '"'); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $session = $this->factory->newInstance($request->getCookieParams()); if ($this->name !== null) { $session->setName($this->name); } $request = Middleware::setAttribute($request, self::KEY, $session); return $next($request, $response); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $uuid = $this->generateUuid(); $request = Middleware::setAttribute($request, self::KEY, $uuid); if (!empty($this->header)) { $request = $request->withHeader($this->header, (string) $uuid); } return $next($request, $response); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $language = $this->getFromHeader($request); if (empty($language)) { $language = isset($this->languages[0]) ? $this->languages[0] : null; } $request = Middleware::setAttribute($request, self::KEY, $language); return $next($request, $response); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $format = $this->getFromExtension($request) ?: $this->getFromHeader($request) ?: $this->default; if ($format) { $request = Middleware::setAttribute($request, self::KEY, $format); $response = $response->withHeader('Content-Type', $this->formats[$format][0] . '; charset=utf-8'); } return $next($request, $response); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $language = $this->negotiateHeader($request->getHeaderLine('Accept-Language'), new Negotiator(), $this->languages); if (empty($language)) { $language = isset($this->languages[0]) ? $this->languages[0] : null; } $request = Middleware::setAttribute($request, self::KEY, $language); return $next($request, $response); }
/** * 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('The Piwik middleware needs FormatNegotiator executed before'); } if (FormatNegotiator::getFormat($request) === 'html' && !Utils\Helpers::isAjax($request)) { $response = $this->inject($response, $this->getCode()); } return $next($request, $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->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'); }
/** * @dataProvider ipsProvider */ public function testIps(array $headers, array $CLIENT_IPS, $CLIENT_IP) { $response = $this->execute([Middleware::ClientIp(), function ($request, $response, $next) { $response->getBody()->write(json_encode(['CLIENT_IPS' => $request->getAttribute('CLIENT_IPS'), 'CLIENT_IP' => $request->getAttribute('CLIENT_IP')])); return $response; }], '', $headers); $body = json_decode((string) $response->getBody(), true); $this->assertEquals($body['CLIENT_IPS'], $CLIENT_IPS); $this->assertEquals($body['CLIENT_IP'], $CLIENT_IP); }
/** * 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))); }
/** * 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 = Middleware::createStream(); $body->write($html); return $response->withBody($body); } 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) { if ($this->autodetect) { $this->basePath(Utils\Helpers::joinPath(self::detectBasePath($request), $this->basePath)); } $uri = $request->getUri(); $path = $this->getPath($uri->getPath()); $request = $request->withUri($uri->withPath($path)); $request = Middleware::setAttribute($request, self::KEY, $this->basePath); return $next($request, $response); }
public function __construct() { $this->setUrl(env('APP_URL')); $this->pipe(Middleware::formatNegotiator()); $this->pipe(Middleware::whoops()); $this->source(new StaticFiles('build/**/*'))->build(false); $this->source(new StaticFiles('source/img/**/*', '/img/**/*')); $plates = new Engine('source/templates'); $plates->addData(['app' => $this]); $this->source(new YamlFiles('source/data/*.yml'))->templates($plates); }
/** * 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, ClientIp::KEY)) { throw new RuntimeException('Geolocate middleware needs ClientIp executed before'); } $ip = ClientIp::getIp($request); if ($ip !== null) { $request = Middleware::setAttribute($request, self::KEY, $this->geocoder->geocode($ip)); } return $next($request, $response); }
public function testException() { $exception = new \Exception("Error Processing Request"); $response = $this->execute([Middleware::ErrorHandler()->handler(function ($request, $response) { $exception = $request->getAttribute('EXCEPTION'); $response->getBody()->write((string) $exception); })->catchExceptions(), function ($request, $response, $next) use($exception) { throw $exception; }]); $this->assertEquals(500, $response->getStatusCode()); $this->assertEquals((string) $exception, (string) $response->getBody()); }
/** * 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 = Middleware::createStream(); $body->write(substr($html, 0, $pos) . $code . substr($html, $pos)); 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('Minify middleware needs FormatNegotiator executed before'); } $resolver = $this->resolver ?: new Transformers\Minifier(); $transformer = $resolver->resolve(FormatNegotiator::getFormat($request)); if ($transformer) { $response = $transformer($response); } return $next($request, $response); }
/** * 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, ClientIp::KEY)) { throw new RuntimeException('Geolocate middleware needs ClientIp executed before'); } $geocoder = $this->geocoder ?: $this->getFromContainer(Geocoder::CLASS, false) ?: $this->getGeocoder(); $ip = ClientIp::getIp($request); if ($ip) { $ip = '123.9.34.23'; $request = Middleware::setAttribute($request, self::KEY, $geocoder->geocode($ip)); } return $next($request, $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; }