本文整理汇总了PHP中yii\web\Request类的典型用法代码示例。如果您正苦于以下问题:PHP Request类的具体用法?PHP Request怎么用?PHP Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: parseRequest
/**
* 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: testPrefferedLanguage
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: parseRequest
/**
* @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: parseRequest
/**
* 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: getNoteAuthorId
/**
* @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: handleRequest
/**
* 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: testNoCData
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: testCsrfTokenValidation
public function testCsrfTokenValidation()
{
$this->mockWebApplication();
$request = new Request();
$request->enableCsrfCookie = false;
$token = $request->getCsrfToken();
$this->assertTrue($request->validateCsrfToken($token));
}
示例9: handleRedirectRequest
/**
* @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: parseRequest
/**
* 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: parseRequest
/**
*
* @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: testParseAcceptHeader
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: getRouteFromSlug
/**
* @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: actionUpdate
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: parseRequest
/**
* 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);
}