It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers. Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST parameters sent via other HTTP methods like PUT or DELETE. Request is configured as an application component in Application by default. You can access that instance via Yii::$app->request.
С версии: 2.0
Автор: Qiang Xue (qiang.xue@gmail.com)
Наследование: extends yii\base\Request
Пример #1
0
 /**
  * Parses the given request and returns the corresponding route and parameters.
  * @param UrlManager $manager the URL manager
  * @param Request $request the request component
  * @return array|boolean the parsing result. The route and the parameters are returned as an array.
  * If false, it means this rule cannot be used to parse this path info.
  */
 public function parseRequest($manager, $request)
 {
     foreach ($this->skip as $item) {
         if (strpos($request->getPathInfo(), $item) !== false) {
             return false;
         }
     }
     /** @var UrlRoute $model */
     $model = $this->modelClass;
     $model = $model::find()->andWhere(['path' => $request->getPathInfo()])->one();
     if ($model == null) {
         return false;
     }
     if ($model->checkAction($model::ACTION_INDEX)) {
         return [$model->getRoute()];
     } elseif ($model->checkAction($model::ACTION_VIEW)) {
         return [$model->getRoute(), ['id' => $model->object_id]];
     } elseif ($model->checkAction($model::ACTION_REDIRECT)) {
         $url = $model->url_to;
         if (strpos($url, 'http://') === false) {
             $url = [$url];
         }
         Yii::$app->response->redirect($url, $model->http_code);
         Yii::$app->end();
     }
     return false;
 }
Пример #2
0
 public function testPrefferedLanguage()
 {
     $this->mockApplication(['language' => 'en']);
     $request = new Request();
     $request->acceptableLanguages = [];
     $this->assertEquals('en', $request->getPreferredLanguage());
     $request = new Request();
     $request->acceptableLanguages = ['de'];
     $this->assertEquals('en', $request->getPreferredLanguage());
     $request = new Request();
     $request->acceptableLanguages = ['en-us', 'de', 'ru-RU'];
     $this->assertEquals('en', $request->getPreferredLanguage(['en']));
     $request = new Request();
     $request->acceptableLanguages = ['en-us', 'de', 'ru-RU'];
     $this->assertEquals('de', $request->getPreferredLanguage(['ru', 'de']));
     $this->assertEquals('de-DE', $request->getPreferredLanguage(['ru', 'de-DE']));
     $request = new Request();
     $request->acceptableLanguages = ['en-us', 'de', 'ru-RU'];
     $this->assertEquals('de', $request->getPreferredLanguage(['de', 'ru']));
     $request = new Request();
     $request->acceptableLanguages = ['en-us', 'de', 'ru-RU'];
     $this->assertEquals('ru-ru', $request->getPreferredLanguage(['ru-ru']));
     $request = new Request();
     $request->acceptableLanguages = ['en-us', 'de'];
     $this->assertEquals('ru-ru', $request->getPreferredLanguage(['ru-ru', 'pl']));
     $this->assertEquals('ru-RU', $request->getPreferredLanguage(['ru-RU', 'pl']));
     $request = new Request();
     $request->acceptableLanguages = ['en-us', 'de'];
     $this->assertEquals('pl', $request->getPreferredLanguage(['pl', 'ru-ru']));
 }
Пример #3
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     if ($this->mode === self::CREATION_ONLY) {
         return false;
     }
     if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
         return false;
     }
     $pathInfo = $request->getPathInfo();
     if ($this->host !== null) {
         $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
     }
     $params = $request->getQueryParams();
     $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix);
     $treeNode = null;
     $originalDir = $pathInfo;
     if ($suffix) {
         $originalDir = substr($pathInfo, 0, strlen($pathInfo) - strlen($suffix));
     }
     $dependency = new TagDependency(['tags' => [(new Tree())->getTableCacheTag()]]);
     if (!$pathInfo) {
         $treeNode = Tree::getDb()->cache(function ($db) {
             return Tree::find()->where(["site_code" => \Yii::$app->cms->site->code, "level" => 0])->one();
         }, null, $dependency);
     } else {
         $treeNode = Tree::find()->where(["dir" => $originalDir, "site_code" => \Yii::$app->cms->site->code])->one();
     }
     if ($treeNode) {
         \Yii::$app->cms->setCurrentTree($treeNode);
         $params['id'] = $treeNode->id;
         return ['cms/tree/view', $params];
     } else {
         return false;
     }
 }
Пример #4
0
 /**
  * Parses the given request and returns the corresponding route and parameters.
  * @param UrlManager $manager the URL manager
  * @param Request $request the request component
  * @return array|boolean the parsing result. The route and the parameters are returned as an array.
  * If false, it means this rule cannot be used to parse this path info.
  */
 public function parseRequest($manager, $request)
 {
     foreach ($this->skip as $item) {
         if (strpos($request->getPathInfo(), $item) !== false) {
             return false;
         }
     }
     $path = $request->getPathInfo();
     $redirect = false;
     // Слэш в конце
     if (substr($path, -1) == '/') {
         $redirect = true;
         $path = trim($path, '/');
     }
     // Двойной слэш
     if (strpos($path, '//') !== false) {
         $redirect = true;
         $path = str_replace('//', '/', $path);
     }
     // Символы в верхнем регистре
     if (($tmpUrl = strtolower($path)) !== $path) {
         $redirect = true;
         $path = $tmpUrl;
     }
     if ($redirect) {
         Yii::$app->response->redirect([$path], 301);
         Yii::$app->end();
     }
     return false;
 }
Пример #5
0
 /**
  * @param \yii\web\Request $request
  * @return integer|null
  */
 private function getNoteAuthorId($request)
 {
     $noteId = $request->get('id');
     /** @var $note Note|null */
     $note = Note::findOne($noteId);
     return isset($note) ? $note->author_id : null;
 }
Пример #6
0
 /**
  * Handles the specified request.
  * @param Request $request the request to be handled
  * @return Response the resulting response
  * @throws NotFoundHttpException if the requested route is invalid
  */
 public function handleRequest($request)
 {
     if (empty($this->catchAll)) {
         list($route, $params) = $request->resolve();
     } else {
         $route = $this->catchAll[0];
         $params = $this->catchAll;
         unset($params[0]);
     }
     try {
         Yii::trace("Route requested: '{$route}'", __METHOD__);
         $this->requestedRoute = $route;
         $result = $this->runAction($route, $params);
         if ($result instanceof Response) {
             return $result;
         } else {
             $response = $this->getResponse();
             if ($result !== null) {
                 $response->data = $result;
             }
             return $response;
         }
     } catch (InvalidRouteException $e) {
         throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'), $e->getCode(), $e);
     }
 }
Пример #7
0
 public function testNoCData()
 {
     $request = new Request(['parsers' => ['application/xml' => XmlParser::className()]]);
     $xml_body = '<xml><ToUserName>test</ToUserName></xml>';
     $request->setRawBody($xml_body);
     $result = $request->post();
     $this->assertArrayHasKey('ToUserName', $result);
 }
Пример #8
0
 public function testCsrfTokenValidation()
 {
     $this->mockWebApplication();
     $request = new Request();
     $request->enableCsrfCookie = false;
     $token = $request->getCsrfToken();
     $this->assertTrue($request->validateCsrfToken($token));
 }
Пример #9
0
 /**
  * @param \yii\web\Request $request
  * @return \yii\web\Response|null
  */
 protected function handleRedirectRequest($request)
 {
     $key = ltrim(str_replace($request->getBaseUrl(), '', $request->getUrl()), '/');
     if (array_key_exists($key, $this->redirectRoutes)) {
         return $this->getResponse()->redirect(Url::to($this->redirectRoutes[$key]));
     } else {
         return null;
     }
 }
Пример #10
0
 /**
  * Parses the given request and returns the corresponding route and parameters.
  *
  * @param UrlManager $manager the URL manager
  * @param Request    $request the request component
  *
  * @return array|boolean the parsing result. The route and the parameters are returned as an array.
  * If false, it means this rule cannot be used to parse this path info.
  */
 public function parseRequest($manager, $request)
 {
     echo '<pre>==== BeeUrlRule ===<br>';
     print_r('PathInfo = ' . $request->getPathInfo());
     echo '<br>';
     print_r('Url = ' . $request->getUrl());
     echo '<br>======================</pre>';
     $items = Yii::$app->getSiteMenu()->getMenu();
     // Parse SEF URL
     if (Yii::$app->urlManager->enablePrettyUrl == TRUE) {
         $route = $request->getPathInfo();
         /*
          *  Пошаговый парсинг меню
          *  Последне найденный записывается в переменную $found
          */
         $found = null;
         foreach ($items as $item) {
             if ($item->path && BeeString::strpos($route, $item->path) === 0) {
                 // Exact route match. We can break iteration because exact item was found.
                 if ($item->path == $route) {
                     $found = $item;
                     break;
                 }
                 // Partial route match. Item with highest level takes priority.
                 if (!$found || $found->level < $item->level) {
                     $found = $item;
                 }
             }
         }
         /*
          * Если мы нашли конечный пункт меню и его адрес полностью собпадает,
          * то формируем и возвращаем ссылку на этот пункт меню
          * иначе берем компонент в @found и продолжаем поиск уже по этому компоненту.
          */
         if (BeeString::strpos($route, $found->path) === 0) {
             $extAction = $found->query[0];
             // site/index
             $url = ['path' => $found->query['path'], 'id' => $found->query['id']];
             return [$extAction, $url];
         } else {
             echo '<pre>';
             print_r('------------------- Еще не все распарсил -------------------');
             echo '</pre>';
         }
         //echo '<br><br><br><pre>';
         //print_r($found);
         //echo '</pre><br><br><br>';
         echo '<br><pre>Сделать парсинг для страниц, отсутствующих в меню';
         echo '<br>======================</pre>';
     } else {
         // Parse RAW URL
         return FALSE;
     }
     echo '<pre><<< Стандартный парсино Yii >>></pre>';
     return FALSE;
     //return ['site/about', []];
 }
Пример #11
0
 /**
  *
  * @param \yii\web\UrlManager $manager            
  * @param \yii\web\Request $request            
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     $rule = $this->getRuleByPattern($request->getPathInfo(), null);
     if ($rule) {
         $params = [];
         parse_str($rule->defaults, $params);
         return [$rule->route, $params];
     }
     return false;
 }
Пример #12
0
 public function testParseAcceptHeader()
 {
     $request = new Request();
     $this->assertEquals([], $request->parseAcceptHeader(' '));
     $this->assertEquals(['audio/basic' => ['q' => 1], 'audio/*' => ['q' => 0.2]], $request->parseAcceptHeader('audio/*; q=0.2, audio/basic'));
     $this->assertEquals(['application/json' => ['q' => 1, 'version' => '1.0'], 'application/xml' => ['q' => 1, 'version' => '2.0', 'x'], 'text/x-c' => ['q' => 1], 'text/x-dvi' => ['q' => 0.8], 'text/plain' => ['q' => 0.5]], $request->parseAcceptHeader('text/plain; q=0.5,
         application/json; version=1.0,
         application/xml; version=2.0; x,
         text/x-dvi; q=0.8, text/x-c'));
 }
Пример #13
0
 /**
  * @param \yii\web\Request $request
  * @return string
  */
 public function getRouteFromSlug($request)
 {
     $_route = $request->getPathInfo();
     $_params = $request->get();
     $dbRoute = $this->getRouteFromCacheOrWriteCacheThenRead($_route, $_params);
     if (is_object($dbRoute) && $dbRoute->hasAttribute('redirect')) {
         if ($dbRoute->getAttribute('redirect')) {
             Yii::$app->response->redirect([$dbRoute->slug], $dbRoute->getAttribute('redirect_code'));
         }
     }
     return $_route;
 }
Пример #14
0
 public function actionUpdate($id = 0)
 {
     //      $out = ['status' => 'err', 'error' => 'Unknown error'];
     if (\Yii::$app->user->isGuest) {
         throw new NotFoundHttpException();
     }
     $r = new Request();
     if (isset($r->post('Project')['id']) && $r->post('Project')['id']) {
         $id = $r->post('Project')['id'];
     }
     //      vd($r->post('Company'));
     $userID = \Yii::$app->user->getId();
     if ($id) {
         $project = Project::findOne(['id' => $id, 'user_id' => $userID]);
     } else {
         $project = new Project();
         //        \Yii::$app->session->setFlash('error', 'Company ID is required.');
         //        $this->redirect(array('view','id'=>$company));
         //        $this->redirect(array('index'));
         //        return;
     }
     //        vd($company);
     if ($project) {
         if ($project->load($r->post())) {
             $project->user_id = $userID;
             if ($project->validate() && $project->save()) {
                 //vd([$r->post(),$order->attributes]);
                 //          $out = [
                 //            'status' => 'ok',
                 //            'order' => $order->id,
                 //            'user' => $order->user_id,
                 //            'sum' => $order->price / 100,
                 //          ];
                 //          $this->redirect(array('view','id'=>$company));
             } else {
                 //          vd($company->errors);
                 \Yii::$app->session->setFlash('error', array_values($project->errors)[0][0]);
                 //          $out['error'] = array_values($order->errors)[0][0];
                 //vd($order->errors);
             }
         }
     } else {
         \Yii::$app->session->setFlash('error', 'Такой проект не существует');
         $this->redirect(array('my'));
         return;
     }
     return $this->render('update', ['project' => $project]);
     //      \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     //      return $out;
     /*vd(['get' => $r->getQueryParams() ,
       'post' => $r->post(),
       'order' => $order],1); //*/
 }
Пример #15
0
 /**
  * Parse request
  *
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  *
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     $pathInfo = $request->getPathInfo();
     $url = preg_replace('#/$#', '', $pathInfo);
     $page = (new CmsModel())->findPage($url);
     if (!empty($page)) {
         $params['pageAlias'] = $url;
         $params['pageId'] = $page->id;
         return [$this->route, $params];
     }
     return parent::parseRequest($manager, $request);
 }
Пример #16
0
 /**
  * Parses the given request and returns the corresponding route and parameters.
  * @param \yii\web\UrlManager $manager the URL manager
  * @param \yii\web\Request $request the request component
  * @return array|boolean the parsing result. The route and the parameters are returned as an array.
  * If false, it means this rule cannot be used to parse this path info.
  */
 public function parseRequest($manager, $request)
 {
     $this->initPatrones();
     $pathInfo = $request->getPathInfo();
     //vendedor
     if ($this->verificaRuta($this->patrones[self::P_VENDEDOR], $pathInfo)) {
         $parametros = $this->obtenerParametros($this->patrones[self::P_VENDEDOR], $pathInfo);
         return [$this->ruta[self::P_VENDEDOR], $parametros];
     }
     //profesional
     if ($this->verificaRuta($this->patrones[self::P_PROFESIONAL], $pathInfo)) {
         $parametros = $this->obtenerParametros($this->patrones[self::P_PROFESIONAL], $pathInfo);
         return [$this->ruta[self::P_PROFESIONAL], $parametros];
     }
     //categoria
     if ($this->verificaRuta($this->patrones[self::P_CATEGORIAS], $pathInfo)) {
         $parametros = $this->obtenerParametros($this->patrones[self::P_CATEGORIAS], $pathInfo);
         //            echo '<pre>';print_r([__LINE__, __METHOD__,$pathInfo,$this->patrones[self::P_CATEGORIAS]]);die();
         //registrar click
         //            if(Yii::$app->request->getBodyParam('hc') == 7 ){
         //                Yii::$app->visitas->registrarClick($parametros['categoria'], 'C');
         //            }
         //registro de impresion de la categoria
         //            Yii::$app->visitas->registrarImpresion($parametros['categoria'], 'C');
         return [$this->ruta[self::P_CATEGORIAS], $parametros];
     }
     //categoria-provincia
     if ($this->verificaRuta($this->patrones[self::P_CATEGORIA_PROVINCIA], $pathInfo)) {
         $parametros = $this->obtenerParametros($this->patrones[self::P_CATEGORIA_PROVINCIA], $pathInfo);
         //registro de impresion de la categoria
         return [$this->ruta[self::P_CATEGORIA_PROVINCIA], $parametros];
     }
     //detalle articulo
     //municipio/articulo
     if ($this->verificaRuta($this->patrones[self::P_MUNICIPIO_DESCUENTO], $pathInfo)) {
         $parametros = $this->obtenerParametros($this->patrones[self::P_MUNICIPIO_DESCUENTO], $pathInfo);
         //registrar click
         //            if(Yii::$app->request->getBodyParam('hc') == 7 ){
         //                Yii::$app->visitas->registrarClick($parametros['articulo'], 'A');
         //            }
         //registro de impresion de la categoria
         //            Yii::$app->visitas->registrarImpresion($parametros['articulo'], 'A');
         return [$this->ruta[self::P_MUNICIPIO_DESCUENTO], $parametros];
     }
     //provincia
     if ($this->verificaRuta($this->patrones[self::P_PROVINCIA], $pathInfo)) {
         $parametros = $this->obtenerParametros($this->patrones[self::P_PROVINCIA], $pathInfo);
         return [$this->ruta[self::P_PROVINCIA], $parametros];
     }
     return false;
 }
Пример #17
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     $pathInfo = $request->getPathInfo();
     $params = $request->getQueryParams();
     $sourceOriginalFile = File::object($pathInfo);
     $extension = $sourceOriginalFile->getExtension();
     if (!$extension) {
         return false;
     }
     if (!in_array(StringHelper::strtolower($extension), (array) \Yii::$app->imaging->extensions)) {
         return false;
     }
     return ['cms/imaging/process', $params];
 }
Пример #18
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     $pathInfo = $request->getPathInfo();
     $params = $request->getQueryParams();
     $sourceOriginalFile = File::object($pathInfo);
     $extension = $sourceOriginalFile->getExtension();
     if (!$extension) {
         return false;
     }
     if (Validate::validate(new AllowExtension(), $extension)->isInvalid()) {
         return false;
     }
     return ['cms/imaging/process', $params];
 }
 /**
  * Parse request
  *
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  *
  * @return boolean
  */
 public function parseRequest($manager, $request)
 {
     $pathInfo = $request->getPathInfo();
     // get path without '/' in end
     $url = preg_replace("#/\$#", "", $pathInfo);
     // find page by url in db
     $page = (new CmsModel())->findPage($url);
     // redirect to page
     if (!is_null($page)) {
         $params['pageAlias'] = $url;
         $params['pageId'] = $page->id;
         return [$this->route, $params];
     }
     return parent::parseRequest($manager, $request);
 }
 /**
  * Displays product category page.
  *
  * @param string $path
  * @param Request $request
  * @return string
  * @throws NotFoundHttpException
  */
 public function actionView($path, Request $request)
 {
     $model = $this->findModel($path);
     $this->setModel($model);
     $categorySearchComponent = $this->getCategorySearchComponent();
     $searchableType = 'product';
     $searchQuery = $request->get('query', null);
     $params['categoriesFacetValueRouteParams'] = function (CategoriesFacetValue $value) {
         return ['path' => $value->getEntity()->slug];
     };
     $dataProvider = $categorySearchComponent->getSearchDataProvider($searchableType, $model, $searchQuery, $params);
     $dataProvider->prepare();
     $this->_searchResult = $dataProvider->query->result();
     return $this->render('view', ['model' => $model, 'productsDataProvider' => $dataProvider]);
 }
Пример #21
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     $pathInfo = $request->getPathInfo();
     $params = $request->getQueryParams();
     $treeNode = null;
     if (!$pathInfo) {
         return $this->_go();
     }
     //Если урл преобразован, редирректим по новой
     $pathInfoNormal = $this->_normalizeDir($pathInfo);
     if ($pathInfo != $pathInfoNormal) {
         //\Yii::$app->response->redirect(DIRECTORY_SEPARATOR . $pathInfoNormal . ($params ? '?' . http_build_query($params) : '') );
     }
     return $this->_go($pathInfoNormal);
 }
Пример #22
0
 /**
  * Parses the given request and returns the corresponding route and parameters.
  * @param UrlManager $manager the URL manager
  * @param Request $request the request component
  * @return array|bool the parsing result. The route and the parameters are returned as an array.
  * If false, it means this rule cannot be used to parse this path info.
  * @throws NotFoundHttpException
  */
 public function parseRequest($manager, $request)
 {
     $this->currentLanguage = Language::getCurrent();
     $this->pathInfo = $request->getPathInfo();
     if ($this->pathInfo == $this->albumsRoute) {
         if ($this->disableDefault) {
             throw new NotFoundHttpException();
         }
         if (!empty($request->getQueryParams()['id'])) {
             $id = $request->getQueryParams()['id'];
             $album = GalleryAlbum::findOne($id);
             if (!$album) {
                 return false;
             }
             $translation = $album->getTranslation($this->currentLanguage->id);
             if ($translation) {
                 if (!empty($translation->seoUrl)) {
                     throw new NotFoundHttpException();
                 }
             }
         }
     }
     if (!empty($this->prefix)) {
         if (strpos($this->pathInfo, $this->prefix) === 0) {
             $this->pathInfo = substr($this->pathInfo, strlen($this->prefix));
         } else {
             return false;
         }
     }
     $this->initRoutes($this->pathInfo);
     if (!empty($this->prefix) && $this->routesCount == 1) {
         return [$this->albumsRoute, []];
     } else {
         if ($this->routesCount == 2) {
             $seoUrl = $this->routes[1];
             /* @var SeoData $seoData */
             $seoData = SeoData::find()->where(['entity_name' => GalleryAlbumTranslation::className(), 'seo_url' => $seoUrl])->one();
             if ($seoData) {
                 /* @var GalleryAlbum $album */
                 $album = GalleryAlbum::find()->joinWith('translations translation')->where(['translation.id' => $seoData->entity_id, 'translation.language_id' => $this->currentLanguage->id])->one();
                 if ($album) {
                     return [$this->albumsRoute, ['id' => $album->id]];
                 }
             }
         }
     }
     return false;
 }
Пример #23
0
 public function validateCsrfToken()
 {
     if ($this->enableCsrfValidation && in_array(Yii::$app->getUrlManager()->parseRequest($this)[0], $this->noCsrfRoutes)) {
         return true;
     }
     return parent::validateCsrfToken();
 }
Пример #24
0
 public function actionView($path, Request $request)
 {
     $model = $this->findModel($path);
     /** @var \im\search\components\SearchManager $searchManager */
     $searchManager = Yii::$app->get('searchManager');
     $query = $request->get('query', '');
     $searchComponent = $searchManager->getSearchComponent();
     /** @var FacetSet $facetSet */
     $facetSet = FacetSet::findOne(1);
     $facets = $facetSet->facets;
     $query = $searchComponent->getQuery('product', $query, $facets);
     $dataProvider = new SearchDataProvider(['query' => $query]);
     $dataProvider->prepare();
     $this->_searchResult = $dataProvider->query->result();
     return $this->render('view', ['model' => $model, 'dataProvider' => $dataProvider]);
 }
Пример #25
0
 public function __construct($config = array())
 {
     if (empty($this->languages)) {
         $this->languages = ['default' => \yii::$app->language];
     }
     parent::__construct($config);
 }
 /**
  * @param Request $request
  * @return bool
  */
 public function receive(Request $request)
 {
     $this->answer = null;
     $model = new IncomingRequest();
     if ($model->load($request->get(), '') && $model->validate()) {
         $this->sms = $model->toIncomingSms();
         $this->sms->save(false);
         $this->trigger(self::EVENT_RECEIVE_SMS);
         $this->sms->updateAttributes(['answer' => $this->answer]);
         $this->isError = false;
         return $this;
     }
     $this->trigger(self::EVENT_ERROR);
     $this->isError = true;
     return $this;
 }
Пример #27
0
 /**
  * 
  * @return string
  */
 protected function resolveRequestUri()
 {
     if ($this->_requestUri === null) {
         $this->_requestUri = MultiLanguage::processLangInUrl(parent::resolveRequestUri());
     }
     return $this->_requestUri;
 }
Пример #28
0
 /**
  * @throws Exception
  */
 public function init()
 {
     parent::init();
     if (\Yii::$app->user) {
         \Yii::$app->user->enableSession = false;
         \Yii::$app->user->loginUrl = null;
     }
     if (!YII_DEBUG) {
         $this->controllerMap = [];
     }
     Yii::setAlias('@api', __DIR__ . DIRECTORY_SEPARATOR);
     /** @noinspection PhpUndefinedFieldInspection */
     if (YII_DEBUG || Yii::$app->has('api') && Yii::$app->api->enableDocs) {
         $this->controllerMap['doc'] = 'vr\\api\\controllers\\DocController';
     }
     $this->set('harvester', new Harvester());
     Yii::$app->set('request', ['enableCookieValidation' => false, 'enableCsrfValidation' => false, 'class' => Request::className(), 'parsers' => ['application/json' => 'yii\\web\\JsonParser']]);
     Yii::$app->set('response', ['class' => '\\yii\\web\\Response', 'on beforeSend' => function ($event) {
         $response = $event->sender;
         if ($response->format == Response::FORMAT_JSON) {
             if (!$response->data) {
                 $response->data = [];
             }
             if ($response->isSuccessful) {
                 $response->data = ['success' => $response->isSuccessful] + $response->data;
             } else {
                 $response->data = ['success' => $response->isSuccessful, 'exception' => $response->data];
             }
         }
     }, 'formatters' => [Response::FORMAT_JSON => ['class' => '\\vr\\api\\components\\JsonResponseFormatter', 'prettyPrint' => YII_DEBUG, 'encodeOptions' => JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE]]]);
 }
Пример #29
0
 public function getUrl()
 {
     if ($this->langUrl === null) {
         $this->langUrl = parent::getUrl();
         $this->originalUrl = $this->langUrl = parent::getUrl();
         $scriptName = '';
         if (strpos($this->langUrl, $_SERVER['SCRIPT_NAME']) !== false) {
             $scriptName = $_SERVER['SCRIPT_NAME'];
             $this->langUrl = substr($this->langUrl, strlen($scriptName));
         }
         Yii::$app->getModule('radiata')->getActiveLanguageByUrl($this->langUrl);
         if (Yii::$app->getModule('radiata')->activeLanguage->code) {
             Yii::$app->language = Yii::$app->getModule('radiata')->activeLanguage->locale;
             if (Yii::$app->getModule('radiata')->activeLanguage->code != Yii::$app->getModule('radiata')->defaultLanguage->code) {
                 $this->langUrl = substr($this->langUrl, strlen(Yii::$app->getModule('radiata')->activeLanguage->code) + 1);
             }
         }
         if (!$this->langUrl) {
             $this->langUrl = $scriptName . '/';
         }
     } else {
         $this->langUrl = parent::getUrl();
     }
     return $this->langUrl;
 }
Пример #30
0
 /**
  * Parses the given request and returns the corresponding route and parameters.
  * @param UrlManager $manager the URL manager
  * @param Request $request the request component
  * @return array|boolean the parsing result. The route and the parameters are returned as an array.
  * If false, it means this rule cannot be used to parse this path info.
  */
 public function parseRequest($manager, $request)
 {
     /* @var $modelClass ActiveRecordInterface */
     if (empty($this->route)) {
         return false;
     }
     if (empty($this->modelClass) || !class_exists($this->modelClass)) {
         return false;
     } else {
         $modelClass = $this->modelClass;
     }
     $pathInfo = $request->getPathInfo();
     if (!empty($this->prefix)) {
         if (strpos($pathInfo, $this->prefix) === 0) {
             $pathInfo = substr($pathInfo, strlen($this->prefix));
         } else {
             return false;
         }
     }
     $routes = explode('/', $pathInfo);
     if (count($routes) == 1) {
         $seoData = SeoData::find()->where(['entity_name' => $modelClass, 'seo_url' => $routes[0]])->one();
         if (!empty($seoData)) {
             $condition = [];
             $condition[$modelClass::primaryKey()[0]] = $seoData->entity_id;
             if (!empty($this->condition)) {
                 foreach ($this->condition as $key => $value) {
                     if (is_callable($value)) {
                         $value = $value();
                     }
                     $condition[$key] = $value;
                 }
             }
             $model = $modelClass::find()->where($condition)->one();
             if (!empty($model)) {
                 $params = [];
                 if (!empty($this->params)) {
                     foreach ($this->params as $key => $param) {
                         $params[$key] = $model->{$param};
                     }
                 }
                 return [$this->route, $params];
             }
         }
     }
     return false;
 }