Inheritance: extends Zend\Diactoros\Response
Example #1
0
    /**
     * @param string $url
     * @return RedirectResponse
     */
    protected function redirectTo($url)
    {
        $url = Core::url() . $url;
        $content = sprintf('
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=%1$s" />

        <title>Redirecting to %1$s</title>
    </head>
    <body>
        Redirecting to <a href="%1$s">%1$s</a>.
    </body>
</html>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8'));
        $response = new RedirectResponse($url);
        $response->getBody()->write($content);
        return $response;
    }
 public function __invoke($request, $response, callable $next = null)
 {
     if (null === $next) {
         return $response;
     }
     $response = $next($request, $response);
     if (isset($this->config['header_handler']['enable']) && $this->config['header_handler']['enable'] === true && !$response instanceof RedirectResponse && !empty($this->config['header_handler']['headers'])) {
         $statusCode = $response->getStatusCode();
         foreach ($this->config['header_handler']['headers'] as $code => $redirect) {
             if (!is_string($redirect)) {
                 throw new \InvalidArgumentException(sprintf('redirect value for %s must be a string', $code));
             }
             if ($code === $statusCode) {
                 $response = new RedirectResponse($redirect);
             }
         }
     }
     if ($response instanceof RedirectResponse) {
         $allow_not_routed_url = isset($this->config['allow_not_routed_url']) ? $this->config['allow_not_routed_url'] : false;
         $exclude_urls = isset($this->config['options']['exclude_urls']) ? $this->config['options']['exclude_urls'] : [];
         $exclude_hosts = isset($this->config['options']['exclude_hosts']) ? $this->config['options']['exclude_hosts'] : [];
         $uriTarget = $response->getHeader('location')[0];
         $uriTargetHost = (new Uri($uriTarget))->getHost();
         if (true === $allow_not_routed_url || in_array($uriTarget, $exclude_urls) || in_array($uriTargetHost, $exclude_hosts)) {
             return $response;
         }
         $default_url = isset($this->config['default_url']) ? $this->config['default_url'] : '/';
         $currentPath = $request->getUri()->getPath();
         $newUri = new Uri($uriTarget);
         $request = $request->withUri($newUri);
         $uriTargetPath = $newUri->getPath();
         $match = $this->router->match($request);
         if ($currentPath === $default_url || $uriTarget === $default_url || $uriTargetPath === $default_url) {
             return;
         }
         if ($match->isFailure() || $match->isSuccess() && $uriTargetPath === $currentPath && $uriTarget !== $default_url && $uriTargetPath !== $default_url) {
             return $response->withHeader('location', $default_url);
         }
     }
     return $response;
 }