コード例 #1
0
 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;
 }