parseRequest() public method

Parses the user request.
public parseRequest ( Request $request ) : array | boolean
$request Request the request component
return array | boolean the route and the associated parameters. The latter is always empty if [[enablePrettyUrl]] is `false`. `false` is returned if the current request cannot be successfully parsed.
 /**
  * Parses the URL and sets the language accordingly
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($request)
 {
     if ($this->enablePrettyUrl) {
         $pathInfo = $request->getPathInfo();
         $language = explode('/', $pathInfo);
         $locale = $this->getLocal($language[0], $request);
         $language = $this->languages[$locale];
         if (in_array($language, $this->languages, true)) {
             $request->setPathInfo(substr_replace($pathInfo, '', 0, strlen($locale) + 1));
             Yii::$app->language = $locale;
         }
     } else {
         $params = $request->getQueryParams();
         $route = isset($params[$this->routeParam]) ? $params[$this->routeParam] : '';
         if (is_array($route)) {
             $route = '';
         }
         $language = explode('/', $route)[0];
         $locale = $this->getLocal($language, $request);
         $language = $this->languages[$locale];
         if (in_array($language, $this->languages, true)) {
             $route = substr_replace($route, '', 0, strlen($locale) + 1);
             $params[$this->routeParam] = $route;
             $request->setQueryParams($params);
             Yii::$app->language = $locale;
         }
     }
     return parent::parseRequest($request);
 }
Example #2
0
 public function parseRequest($request)
 {
     // extra data from request to composition, which changes the pathInfo of the Request-Object.
     $resolver = $this->composition->getResolvedPathInfo($request);
     $request->setPathInfo($resolver['route']);
     $parsedRequest = parent::parseRequest($request);
     if ($this->composition->hidden) {
         return $parsedRequest;
     }
     // temp write variables
     $composition = $this->composition->full;
     $length = strlen($composition);
     $route = $parsedRequest[0];
     // route matches composition exactly, so we have to remove the composition informations
     if ($route === $composition) {
         $parsedRequest[0] = false;
         // now see if the composition (+1 as we add add trailing slash at the end) matches the cutted route request part, if so its composition prefix, remove it.
     } elseif (substr($route, 0, $length + 1) == $composition . '/') {
         $parsedRequest[0] = substr($parsedRequest[0], $length);
     }
     // fix broken request urls
     if ($parsedRequest[0] === false || $parsedRequest[0] == '/') {
         $parsedRequest[0] = '';
     }
     // ltrim all request to fix request routes
     $parsedRequest[0] = ltrim($parsedRequest[0], '/');
     // return new parsted request route
     return $parsedRequest;
 }
Example #3
0
 public function parseRequest($request)
 {
     $route = parent::parseRequest($request);
     //        $route = lcfirst(str_replace(' ', '', ucwords(str_replace('-', ' ', $route))));
     if ($this->_isExcluded($route[0])) {
         $requestLang = Yii::$app->lang->getDefault();
     } else {
         if (isset($route[1][$this->languageVar])) {
             $requestLang = $route[1][$this->languageVar];
         } else {
             if (isset($route[0]) && $route[0] === Yii::$app->defaultRoute) {
                 header('HTTP/1.1 301 Moved Permanently');
                 header('Location: /' . Yii::$app->lang->get());
                 exit;
             } else {
                 throw new HttpException(404, Yii::t('app', 'Page not found'));
             }
         }
     }
     Yii::$app->language = Yii::$app->lang->get();
     if (!Yii::$app->lang->checkLang($requestLang)) {
         throw new HttpException(404, Yii::t('app', 'Page not found'));
     } else {
         if (Yii::$app->language !== $requestLang) {
             Yii::$app->lang->update($requestLang);
         }
     }
     return $route;
 }
 /**
  * Parses the URL and sets the language accordingly
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($request)
 {
     if ($this->enablePrettyUrl) {
         $pathInfo = $request->getPathInfo();
         $language = explode('/', $pathInfo)[0];
         $locale = ArrayHelper::getValue($this->aliases, $language, $language);
         if (in_array($language, $this->languages)) {
             $request->setPathInfo(substr_replace($pathInfo, '', 0, strlen($language) + 1));
             Yii::$app->language = $locale;
             static::$currentLanguage = $language;
         }
     } else {
         $params = $request->getQueryParams();
         $route = isset($params[$this->routeParam]) ? $params[$this->routeParam] : '';
         if (is_array($route)) {
             $route = '';
         }
         $language = explode('/', $route)[0];
         $locale = ArrayHelper::getValue($this->aliases, $language, $language);
         if (in_array($language, $this->languages)) {
             $route = substr_replace($route, '', 0, strlen($language) + 1);
             $params[$this->routeParam] = $route;
             $request->setQueryParams($params);
             Yii::$app->language = $locale;
             static::$currentLanguage = $language;
         }
     }
     return parent::parseRequest($request);
 }
 public function parseRequest($request)
 {
     $hostInfo = $request->getHostInfo();
     $arr = explode('://', $hostInfo);
     $host = $arr[1];
     $arr = explode('.' . $this->baseDomain, $host);
     $subDomain = $arr[0];
     $request->setQueryParams(array_merge($request->getQueryParams(), [$this->subDomainKey => $subDomain]));
     return parent::parseRequest($request);
 }
 /**
  * Parse request and set application language
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($request)
 {
     if (count($this->availableLanguages) > 0) {
         if (preg_match('/\\/(' . implode('|', $this->availableLanguages) . ')(.*)/si', $request->url, $matches)) {
             Yii::$app->language = $matches[1];
         }
     }
     $res = parent::parseRequest($request);
     if (is_array($res)) {
         if (isset($res[1]['language']) && in_array($res[1]['language'], $this->availableLanguages)) {
             Yii::$app->language = $res[1]['language'];
         }
     }
     return $res;
 }
Example #7
0
 public function parseRequest($request)
 {
     $route = parent::parseRequest($request);
     /**
      * @todo previous `!is_object(\yii::$app->composition)`can remove?`how to handle?
      */
     if (!Yii::$app->has('composition')) {
         return $route;
     }
     $composition = Yii::$app->composition->getFull();
     $length = strlen($composition);
     if (substr($route[0], 0, $length) == $composition) {
         $route[0] = substr($route[0], $length);
     }
     return $route;
 }
Example #8
0
 /** @inheritdoc */
 public function parseRequest($request)
 {
     $redirect = false;
     $result = parent::parseRequest($request);
     $params = $request->getQueryParams();
     $activeLanguage = $request->getQueryParam($this->languageParam);
     Language::set(Language::fromAlias($activeLanguage));
     if (($activeLanguage xor $this->showDefaultLanguage) && Language::isDefault()) {
         unset($params[$this->languageParam]);
         if (!$activeLanguage && $this->showDefaultLanguage) {
             $params[$this->languageParam] = Language::get()->alias;
         }
         \Yii::$app->getResponse()->redirect([$result[0]] + $params, 301);
         $redirect = true;
     }
     return $redirect ? \Yii::$app->end() : $result;
 }
Example #9
0
 public function parseRequest($request)
 {
     // extra data from request to composition, which changes the pathInfo of the Request-Object.
     $resolver = Yii::$app->composition->getResolvedPathInfo($request);
     $request->setPathInfo($resolver['route']);
     $route = parent::parseRequest($request);
     if ($this->composition->hidden) {
         return $route;
     }
     $composition = $this->composition->full;
     $length = strlen($composition);
     if (substr($route[0], 0, $length) == $composition) {
         $route[0] = substr($route[0], $length);
     }
     if ($route[0] === false || $route[0] == '/') {
         $route[0] = '';
     }
     return $route;
 }
Example #10
0
 /**
  * Parses the user request.
  *
  */
 public function parseRequest($request)
 {
     $session = \Yii::$app->session;
     if ($this->enablePrettyUrl) {
         $urlInfo = $request->getUrl();
         $urlComponents = explode('/', $urlInfo);
         if (isset($urlComponents[1]) && in_array($urlComponents[1], array_keys($this->langs))) {
             $this->currLang = $urlComponents[1];
             $request->setUrl(substr($urlInfo, strlen($urlComponents[1]) + 1));
         }
     }
     if (!$this->currLang) {
         $session_lang = $session->get('lang');
         $this->currLang = isset($session_lang) ? $session_lang : substr(\Yii::$app->language, 0, 2);
     }
     if ($session->get('lang') != $this->currLang) {
         $session->set('lang', $this->currLang);
     }
     \Yii::$app->language = $this->langs[$this->currLang];
     return parent::parseRequest($request);
 }
 /**
  * @inheritdoc
  */
 public function parseRequest($request)
 {
     $url = $this->checkRedirectToLanguage($request);
     if ($url !== false) {
         Yii::$app->response->redirect($url);
         return [$url, []];
     }
     $request = parent::parseRequest($request);
     if (!$request) {
         return $request;
     }
     if (isset($request[1][$this->languageParam])) {
         $this->setCurrent($request[1][$this->languageParam]);
         if (!$this->showDefault && $this->isCurrentDefault()) {
             throw new NotFoundHttpException(\Yii::t('app', 'You select default language. Remove it from URL.'));
         }
     }
     \Yii::$app->language = $this->getCurrentLocale();
     return $request;
 }
 /**
  * Redirect to the current URL with given language code applied
  * @param string $language the language code to add. Can also be empty to not add any language code.
  */
 protected function redirectToLanguage($language)
 {
     $result = parent::parseRequest($this->_request);
     if ($result === false) {
         throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
     }
     list($route, $params) = $result;
     if ($language) {
         $params[$this->languageParam] = $language;
     }
     $params = $params + $this->_request->getQueryParams();
     array_unshift($params, $route);
     $url = $this->createUrl($params);
     if ($this->suffix === '/' && $route === '') {
         $url = rtrim($url, '/') . '/';
     }
     Yii::$app->getResponse()->redirect($url);
     if (YII_ENV_TEST) {
         throw new Exception(Url::to($url));
     } else {
         Yii::$app->end();
     }
 }
 /**
  * @inheritdoc
  */
 public function parseRequest($request)
 {
     /** @var \DevGroup\Multilingual\Multilingual $multilingual */
     $multilingual = Yii::$app->multilingual;
     $languages = $multilingual->getAllLanguages();
     foreach ($multilingual->requestedLanguageEvents as $filter) {
         if (is_subclass_of($filter, GettingLanguage::class)) {
             $this->on(self::GET_LANGUAGE, [$filter, 'gettingLanguage']);
         }
         if (is_subclass_of($filter, AfterGettingLanguage::class)) {
             $this->on(self::AFTER_GET_LANGUAGE, [$filter, 'afterGettingLanguage']);
         }
     }
     foreach ($multilingual->preferredLanguageEvents as $filter) {
         if (is_subclass_of($filter, GettingLanguage::class)) {
             $this->on(self::GET_PREFERRED_LANGUAGE, [$filter, 'gettingLanguage']);
         }
     }
     $eventRequestedLanguage = new LanguageEvent();
     $eventRequestedLanguage->multilingual = $multilingual;
     $eventRequestedLanguage->domain = $this->requestedDomain();
     $eventRequestedLanguage->request = $request;
     $eventRequestedLanguage->languages = $languages;
     $this->trigger(self::GET_LANGUAGE, $eventRequestedLanguage);
     $multilingual->language_id = $eventRequestedLanguage->currentLanguageId ? $eventRequestedLanguage->currentLanguageId : $multilingual->default_language_id;
     /** @var bool|Language $languageMatched */
     $languageMatched = $languages[$multilingual->language_id];
     Yii::$app->language = $languageMatched->yii_language;
     $path = explode('/', $request->pathInfo);
     $folder = array_shift($path);
     if (is_array($this->excludeRoutes)) {
         $resolved = parent::parseRequest($request);
         if (is_array($resolved)) {
             $route = reset($resolved);
             if (in_array($route, $this->excludeRoutes)) {
                 $multilingual->language_id = $multilingual->cookie_language_id;
                 /** @var Language $lang */
                 $lang = call_user_func([$multilingual->modelsMap['Language'], 'getById'], $multilingual->cookie_language_id);
                 Yii::$app->language = $lang->yii_language;
                 return $resolved;
             }
         }
     }
     $eventPreferredLanguage = new LanguageEvent();
     $eventPreferredLanguage->multilingual = $multilingual;
     $eventPreferredLanguage->domain = $this->requestedDomain();
     $eventPreferredLanguage->request = $request;
     $eventPreferredLanguage->languages = $languages;
     $this->trigger(self::GET_PREFERRED_LANGUAGE, $eventPreferredLanguage);
     $multilingual->preferred_language_id = $eventPreferredLanguage->currentLanguageId ? $eventPreferredLanguage->currentLanguageId : $eventRequestedLanguage->currentLanguageId;
     $this->trigger(self::AFTER_GET_LANGUAGE, $eventRequestedLanguage);
     if (in_array($eventRequestedLanguage->resultClass, $multilingual->needConfirmationEvents) || $eventRequestedLanguage->resultClass === null || Yii::$app->session->getFlash('needsConfirmation', false)) {
         $multilingual->needsConfirmation = true;
     }
     if ($eventRequestedLanguage->redirectUrl !== false && $eventRequestedLanguage->redirectCode !== false) {
         if ($multilingual->needsConfirmation) {
             Yii::$app->session->setFlash('needsConfirmation', true);
         }
         Yii::$app->response->redirect($eventRequestedLanguage->redirectUrl, $eventRequestedLanguage->redirectCode, false);
         Yii::$app->end();
     }
     if (!empty($languageMatched->folder)) {
         $request->setPathInfo(implode('/', $path));
     }
     return parent::parseRequest($request);
 }
Example #14
0
 public function parseRequest($request)
 {
     /** @var LanguageProviderInterface $languagePovider */
     $languagePovider = $this->conteiner->get('languageProvider');
     $languages = $languagePovider->getLanguages();
     $language =& \Yii::$app->language;
     if (empty($languages)) {
         throw new InvalidValueException('languages not set');
     }
     $languagePattern = implode('|', ArrayHelper::merge(array_keys($languages), array_filter(array_values($languages))));
     $receive = new ReceiveContainer();
     if ($this->detectInSession) {
         $receive->addReceiver(new SessionLanguageReceive($this->sessionLanguageKey));
     }
     if ($this->detectInCookie) {
         $receive->addReceiver(new CookieLanguageReceive($this->cookieLanguageKey));
     }
     $languageFromStorage = $receive->getLanguage();
     //todo: fix mathes
     $mathed = preg_match("~^(?<language>(?:{$languagePattern})?)/?(?<url>.*)~i", $request->getPathInfo(), $mathes);
     $request->setPathInfo(isset($mathes['language']) ? $mathes['url'] : $request->getPathInfo());
     $language = !empty($mathes['language']) ? $mathes['language'] : \Yii::$app->sourceLanguage;
     //        && !$this->showDefault
     //            ? $mathes['language']
     //            :
     //            (is_null($languageFromStorage)
     //                ? $language
     //                : $languageFromStorage);
     if (!$this->showDefault && strtolower($mathes['language']) == strtolower(\Yii::$app->sourceLanguage)) {
         throw new NotFoundHttpException(\Yii::t('yii', 'Page not found.'));
     }
     $saver = new SaveConteiner();
     if ($this->detectInSession) {
         $saver->add(new SessionLanguageSave($this->sessionLanguageKey));
     }
     if ($this->detectInCookie) {
         $saver->add(new CookieLanguageSave($this->cookieLanguageKey));
     }
     $saver->save($language);
     return parent::parseRequest($request);
 }
Example #15
0
 /**
  * @inheritdoc
  */
 public function parseRequest($request)
 {
     if ($this->enableLocaleUrls && $this->languages) {
         $process = true;
         if ($this->ignoreLanguageUrlPatterns) {
             $pathInfo = $request->getPathInfo();
             foreach ($this->ignoreLanguageUrlPatterns as $k => $pattern) {
                 if (preg_match($pattern, $pathInfo)) {
                     $process = false;
                 }
             }
         }
         if ($process) {
             $this->processLocaleUrl($request);
         }
     }
     return parent::parseRequest($request);
 }
Example #16
0
 /**
  * Redirect to the current URL with given language code applied
  *
  * @param string $language the language code to add. Can also be empty to not add any language code.
  * @throws \yii\base\Exception
  */
 protected function redirectToLanguage($language)
 {
     $result = parent::parseRequest($this->_request);
     if ($result === false) {
         throw new \yii\web\NotFoundHttpException(Yii::t('yii', 'Page not found.'));
     }
     list($route, $params) = $result;
     if ($language) {
         $params[$this->languageParam] = $language;
     }
     // See Yii Issues #8291 and #9161:
     $params = $params + $this->_request->getQueryParams();
     array_unshift($params, $route);
     $url = $this->createUrl($params);
     Yii::trace("Redirecting to {$url}.", __METHOD__);
     Yii::$app->getResponse()->redirect($url);
     if (YII_ENV_TEST) {
         // Response::redirect($url) above will call `Url::to()` internally. So to really
         // test for the same final redirect URL here, we need to call Url::to(), too.
         throw new \yii\base\Exception(\yii\helpers\Url::to($url));
     } else {
         Yii::$app->end();
     }
 }
 /**
  * @inheritdoc
  */
 public function parseRequest($request)
 {
     if ($this->enableLocaleUrls && $this->languages) {
         $this->processLocaleUrl($request);
     }
     return parent::parseRequest($request);
 }
Example #18
-1
 public function testParseRESTRequest()
 {
     $request = new Request();
     // pretty URL rules
     $manager = new UrlManager(['enablePrettyUrl' => true, 'showScriptName' => false, 'cache' => null, 'rules' => ['PUT,POST post/<id>/<title>' => 'post/create', 'DELETE post/<id>' => 'post/delete', 'post/<id>/<title>' => 'post/view', 'POST/GET' => 'post/get']]);
     // matching pathinfo GET request
     $_SERVER['REQUEST_METHOD'] = 'GET';
     $request->pathInfo = 'post/123/this+is+sample';
     $result = $manager->parseRequest($request);
     $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result);
     // matching pathinfo PUT/POST request
     $_SERVER['REQUEST_METHOD'] = 'PUT';
     $request->pathInfo = 'post/123/this+is+sample';
     $result = $manager->parseRequest($request);
     $this->assertEquals(['post/create', ['id' => '123', 'title' => 'this+is+sample']], $result);
     $_SERVER['REQUEST_METHOD'] = 'POST';
     $request->pathInfo = 'post/123/this+is+sample';
     $result = $manager->parseRequest($request);
     $this->assertEquals(['post/create', ['id' => '123', 'title' => 'this+is+sample']], $result);
     // no wrong matching
     $_SERVER['REQUEST_METHOD'] = 'POST';
     $request->pathInfo = 'POST/GET';
     $result = $manager->parseRequest($request);
     $this->assertEquals(['post/get', []], $result);
     // createUrl should ignore REST rules
     $this->mockApplication(['components' => ['request' => ['hostInfo' => 'http://localhost/', 'baseUrl' => '/app']]], \yii\web\Application::className());
     $this->assertEquals('/app/post/delete?id=123', $manager->createUrl(['post/delete', 'id' => 123]));
     $this->destroyApplication();
     unset($_SERVER['REQUEST_METHOD']);
 }