Example #1
0
 /**
  * Execute the middleware.
  *
  * @param ExtendedRequest $request
  * @param Response        $response
  * @param callable        $next
  *
  * @return Response
  */
 public function __invoke(ExtendedRequest $request, Response $response, callable $next)
 {
     $router = $this->router;
     $route = $request->getCurrentRoute();
     $locales = $this->locale;
     $locale = $locales->getDefault();
     $lang = $route->getArgument($router->getLanguageIdentifier());
     $lang = ltrim($lang, '/');
     $redirect = false;
     if ($lang) {
         try {
             // Find language in list of available locales and set it as active
             $locale = $locales->findByLanguage($lang);
             $locales->setActive($locale);
             if ($router->isOmitDefaultLanguage() && $locale == $locales->getDefault()) {
                 // Trigger redirect to correct path (as language set in path is default lang and we want to omit it)
                 $redirect = true;
             }
         } catch (Exception $e) {
             // Trigger "notFound" as setActive() throws Exception if $locale is not valid / available
             $next = $this->notFoundHandler;
         }
     } elseif (!$router->isOmitDefaultLanguage()) {
         // Trigger redirect to correct path (as language is not set in path but we don't want to omit default lang)
         $redirect = true;
     }
     // Redirect to route with proper language identifier value set (or omitted)
     if ($redirect) {
         $path = $router->pathFor($route->getName(), $route->getArguments(), $request->getParams(), $locale->getLanguage());
         $uri = $request->getUri()->withPath($path);
         return $response->withRedirect($uri);
     }
     return $next($request, $response);
 }
 /**
  * {@inheritdoc}
  */
 public function register(Container $container)
 {
     /**
      * Add dependency (DI).
      *
      * @param Container $c
      *
      * @return ExtendedRequest
      */
     $container['request'] = function ($c) {
         return ExtendedRequest::createFromEnvironment($c['environment']);
     };
 }