From 3400eb521596116df16a598772b009681b455e5b Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 16:41:55 +0400 Subject: [PATCH 01/21] #2630: `yii\heplers\Html::url` moved to new `yii\helpers\Url::create` --- .../templates/bootstrap/SideNavWidget.php | 3 +- extensions/authclient/widgets/Choice.php | 3 +- extensions/debug/views/default/toolbar.php | 4 +- extensions/debug/views/default/view.php | 3 +- extensions/elasticsearch/DebugPanel.php | 3 +- extensions/jui/Tabs.php | 3 +- extensions/smarty/ViewRenderer.php | 3 +- extensions/twig/ViewRenderer.php | 3 +- framework/CHANGELOG.md | 1 + framework/captcha/Captcha.php | 3 +- framework/grid/GridView.php | 3 +- framework/helpers/BaseHtml.php | 52 ++------------- framework/helpers/BaseUrl.php | 65 +++++++++++++++++++ framework/helpers/Url.php | 19 ++++++ framework/web/Controller.php | 4 +- framework/web/Response.php | 4 +- framework/widgets/ActiveForm.php | 3 +- framework/widgets/Menu.php | 3 +- 18 files changed, 116 insertions(+), 66 deletions(-) create mode 100644 framework/helpers/BaseUrl.php create mode 100644 framework/helpers/Url.php diff --git a/extensions/apidoc/templates/bootstrap/SideNavWidget.php b/extensions/apidoc/templates/bootstrap/SideNavWidget.php index 0904285f23..6013ee455c 100644 --- a/extensions/apidoc/templates/bootstrap/SideNavWidget.php +++ b/extensions/apidoc/templates/bootstrap/SideNavWidget.php @@ -11,6 +11,7 @@ use Yii; use yii\base\InvalidConfigException; use yii\bootstrap\BootstrapAsset; use yii\helpers\ArrayHelper; +use yii\helpers\Url; use yii\helpers\Html; /** @@ -135,7 +136,7 @@ class SideNavWidget extends \yii\bootstrap\Widget $label = $this->encodeLabels ? Html::encode($item['label']) : $item['label']; // $options = ArrayHelper::getValue($item, 'options', []); $items = ArrayHelper::getValue($item, 'items'); - $url = Html::url(ArrayHelper::getValue($item, 'url', '#')); + $url = Url::create(ArrayHelper::getValue($item, 'url', '#')); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []); Html::addCssClass($linkOptions, 'list-group-item'); diff --git a/extensions/authclient/widgets/Choice.php b/extensions/authclient/widgets/Choice.php index f05e3fd83d..0ecda6fd17 100644 --- a/extensions/authclient/widgets/Choice.php +++ b/extensions/authclient/widgets/Choice.php @@ -9,6 +9,7 @@ namespace yii\authclient\widgets; use yii\base\Widget; use Yii; +use yii\helpers\Url; use yii\helpers\Html; use yii\authclient\ClientInterface; @@ -195,7 +196,7 @@ class Choice extends Widget $this->autoRender = false; $url = $this->getBaseAuthUrl(); $url[$this->clientIdGetParamName] = $provider->getId(); - return Html::url($url); + return Url::create($url); } /** diff --git a/extensions/debug/views/default/toolbar.php b/extensions/debug/views/default/toolbar.php index bb87a78a49..166d216c57 100644 --- a/extensions/debug/views/default/toolbar.php +++ b/extensions/debug/views/default/toolbar.php @@ -5,7 +5,7 @@ * @var string $tag * @var string $position */ -use yii\helpers\Html; +use yii\helpers\Url; $minJs = <<getUrl(); ?>
- + Yii Debugger diff --git a/extensions/debug/views/default/view.php b/extensions/debug/views/default/view.php index f3784a1929..ea98d42a62 100644 --- a/extensions/debug/views/default/view.php +++ b/extensions/debug/views/default/view.php @@ -2,6 +2,7 @@ use yii\bootstrap\ButtonDropdown; use yii\bootstrap\ButtonGroup; +use yii\helpers\Url; use yii\helpers\Html; /** @@ -19,7 +20,7 @@ $this->title = 'Yii Debugger';
- + Yii Debugger diff --git a/extensions/elasticsearch/DebugPanel.php b/extensions/elasticsearch/DebugPanel.php index 1782b8de95..80f9245bc4 100644 --- a/extensions/elasticsearch/DebugPanel.php +++ b/extensions/elasticsearch/DebugPanel.php @@ -9,6 +9,7 @@ namespace yii\elasticsearch; use yii\debug\Panel; use yii\helpers\ArrayHelper; +use yii\helpers\Url; use yii\log\Logger; use yii\helpers\Html; use yii\web\View; @@ -83,7 +84,7 @@ EOD; }, ]); } - $ajaxUrl = Html::url(['elasticsearch-query', 'logId' => $logId, 'tag' => $this->tag]); + $ajaxUrl = Url::create(['elasticsearch-query', 'logId' => $logId, 'tag' => $this->tag]); \Yii::$app->view->registerJs(<<twig->addFunction('path', new \Twig_Function_Function(function ($path, $args = []) { - return Html::url(array_merge([$path], $args)); + return BaseViewRenderer::url(array_merge([$path], $args)); })); $this->twig->addGlobal('app', \Yii::$app); diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 9446f0a07a..c85c9f31c3 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -191,6 +191,7 @@ Yii Framework 2 Change Log - Chg #2544: Changed `DetailView`'s `name:format:label` to `attribute:format:label` to match `GridView` (samdark) - Chg #2603: `yii\base\ErrorException` now extends `\ErrorException` (samdark) - Chg #2629: `Module::controllerPath` is now read only, and all controller classes must be namespaced under `Module::controllerNamespace`. (qiangxue) +- Chg #2630: `yii\heplers\Html::url` moved to new `yii\helpers\Url::create` (samdark) - Chg: Renamed `yii\jui\Widget::clientEventsMap` to `clientEventMap` (qiangxue) - Chg: Renamed `ActiveRecord::getPopulatedRelations()` to `getRelatedRecords()` (qiangxue) - Chg: Renamed `attributeName` and `className` to `targetAttribute` and `targetClass` for `UniqueValidator` and `ExistValidator` (qiangxue) diff --git a/framework/captcha/Captcha.php b/framework/captcha/Captcha.php index 25361c5cb5..146123fd17 100644 --- a/framework/captcha/Captcha.php +++ b/framework/captcha/Captcha.php @@ -9,6 +9,7 @@ namespace yii\captcha; use Yii; use yii\base\InvalidConfigException; +use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; use yii\widgets\InputWidget; @@ -106,7 +107,7 @@ class Captcha extends InputWidget protected function getClientOptions() { $options = [ - 'refreshUrl' => Html::url(['/' . $this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1]), + 'refreshUrl' => Url::create(['/' . $this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1]), 'hashKey' => "yiiCaptcha/{$this->captchaAction}", ]; return $options; diff --git a/framework/grid/GridView.php b/framework/grid/GridView.php index 6924d4a3cf..37b5ad5508 100644 --- a/framework/grid/GridView.php +++ b/framework/grid/GridView.php @@ -11,6 +11,7 @@ use Yii; use Closure; use yii\base\Formatter; use yii\base\InvalidConfigException; +use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; use yii\widgets\BaseListView; @@ -218,7 +219,7 @@ class GridView extends BaseListView } return [ - 'filterUrl' => Html::url($filterUrl), + 'filterUrl' => Url::create($filterUrl), 'filterSelector' => $filterSelector, ]; } diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index f0fe5b43c8..968848fd84 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -205,7 +205,7 @@ class BaseHtml if (!isset($options['rel'])) { $options['rel'] = 'stylesheet'; } - $options['href'] = static::url($url); + $options['href'] = Url::create($url); return static::tag('link', '', $options); } @@ -221,7 +221,7 @@ class BaseHtml */ public static function jsFile($url, $options = []) { - $options['src'] = static::url($url); + $options['src'] = Url::create($url); return static::tag('script', '', $options); } @@ -241,7 +241,7 @@ class BaseHtml */ public static function beginForm($action = '', $method = 'post', $options = []) { - $action = static::url($action); + $action = Url::create($action); $hiddenInputs = []; @@ -311,7 +311,7 @@ class BaseHtml public static function a($text, $url = null, $options = []) { if ($url !== null) { - $options['href'] = static::url($url); + $options['href'] = Url::create($url); } return static::tag('a', $text, $options); } @@ -346,7 +346,7 @@ class BaseHtml */ public static function img($src, $options = []) { - $options['src'] = static::url($src); + $options['src'] = Url::create($src); if (!isset($options['alt'])) { $options['alt'] = ''; } @@ -1527,48 +1527,6 @@ class BaseHtml return $html; } - /** - * Normalizes the input parameter to be a valid URL. - * - * If the input parameter - * - * - is an empty string: the currently requested URL will be returned; - * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result - * is an absolute URL, it will be returned without any change further; Otherwise, the result - * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. - * - is an array: the first array element is considered a route, while the rest of the name-value - * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. - * For example: `['post/index', 'page' => 2]`, `['index']`. - * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. - * - * @param array|string $url the parameter to be used to generate a valid URL - * @return string the normalized URL - * @throws InvalidParamException if the parameter is invalid. - */ - public static function url($url) - { - if (is_array($url)) { - if (isset($url[0])) { - if (Yii::$app->controller instanceof \yii\web\Controller) { - return Yii::$app->controller->createUrl($url); - } else { - return Yii::$app->getUrlManager()->createUrl($url); - } - } else { - throw new InvalidParamException('The array specifying a URL must contain at least one element.'); - } - } elseif ($url === '') { - return Yii::$app->getRequest()->getUrl(); - } else { - $url = Yii::getAlias($url); - if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { - return $url; - } else { - return Yii::$app->getRequest()->getBaseUrl() . '/' . $url; - } - } - } - /** * Adds a CSS class to the specified options. * If the CSS class is already in the options, it will not be added again. diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php new file mode 100644 index 0000000000..3444a227bf --- /dev/null +++ b/framework/helpers/BaseUrl.php @@ -0,0 +1,65 @@ + + * @since 2.0 + */ +class BaseUrl +{ + /** + * Normalizes the input parameter to be a valid URL. + * + * If the input parameter + * + * - is an empty string: the currently requested URL will be returned; + * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result + * is an absolute URL, it will be returned without any change further; Otherwise, the result + * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + * - is an array: the first array element is considered a route, while the rest of the name-value + * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. + * For example: `['post/index', 'page' => 2]`, `['index']`. + * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. + * + * @param array|string $url the parameter to be used to generate a valid URL + * @return string the normalized URL + * @throws InvalidParamException if the parameter is invalid. + */ + public static function create($url) + { + if (is_array($url)) { + if (isset($url[0])) { + if (Yii::$app->controller instanceof \yii\web\Controller) { + return Yii::$app->controller->createUrl($url); + } else { + return Yii::$app->getUrlManager()->createUrl($url); + } + } else { + throw new InvalidParamException('The array specifying a URL must contain at least one element.'); + } + } elseif ($url === '') { + return Yii::$app->getRequest()->getUrl(); + } else { + $url = Yii::getAlias($url); + if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { + return $url; + } else { + return Yii::$app->getRequest()->getBaseUrl() . '/' . $url; + } + } + } +} + \ No newline at end of file diff --git a/framework/helpers/Url.php b/framework/helpers/Url.php new file mode 100644 index 0000000000..87e29c4833 --- /dev/null +++ b/framework/helpers/Url.php @@ -0,0 +1,19 @@ + + * @since 2.0 + */ +class Url extends BaseUrl +{ +} + \ No newline at end of file diff --git a/framework/web/Controller.php b/framework/web/Controller.php index 85a96c630d..0a474536ec 100644 --- a/framework/web/Controller.php +++ b/framework/web/Controller.php @@ -9,7 +9,7 @@ namespace yii\web; use Yii; use yii\base\InlineAction; -use yii\helpers\Html; +use yii\helpers\Url; /** * Controller is the base class of web controllers. @@ -241,7 +241,7 @@ class Controller extends \yii\base\Controller */ public function redirect($url, $statusCode = 302) { - return Yii::$app->getResponse()->redirect(Html::url($url), $statusCode); + return Yii::$app->getResponse()->redirect(Url::create($url), $statusCode); } /** diff --git a/framework/web/Response.php b/framework/web/Response.php index b3f75483f2..70c72c8a8b 100644 --- a/framework/web/Response.php +++ b/framework/web/Response.php @@ -10,8 +10,8 @@ namespace yii\web; use Yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; +use yii\helpers\Url; use yii\helpers\FileHelper; -use yii\helpers\Html; use yii\helpers\Json; use yii\helpers\Security; use yii\helpers\StringHelper; @@ -673,7 +673,7 @@ class Response extends \yii\base\Response // ensure the route is absolute $url[0] = '/' . ltrim($url[0], '/'); } - $url = Html::url($url); + $url = Url::create($url); if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) { $url = Yii::$app->getRequest()->getHostInfo() . $url; } diff --git a/framework/widgets/ActiveForm.php b/framework/widgets/ActiveForm.php index fdb52edb8c..c7000e7513 100644 --- a/framework/widgets/ActiveForm.php +++ b/framework/widgets/ActiveForm.php @@ -10,6 +10,7 @@ namespace yii\widgets; use Yii; use yii\base\Widget; use yii\base\Model; +use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; use yii\web\JsExpression; @@ -194,7 +195,7 @@ class ActiveForm extends Widget 'ajaxDataType' => $this->ajaxDataType, ]; if ($this->validationUrl !== null) { - $options['validationUrl'] = Html::url($this->validationUrl); + $options['validationUrl'] = Url::create($this->validationUrl); } foreach (['beforeSubmit', 'beforeValidate', 'afterValidate'] as $name) { if (($value = $this->$name) !== null) { diff --git a/framework/widgets/Menu.php b/framework/widgets/Menu.php index ae1ced7e06..7cea1afbe4 100644 --- a/framework/widgets/Menu.php +++ b/framework/widgets/Menu.php @@ -10,6 +10,7 @@ namespace yii\widgets; use Yii; use yii\base\Widget; use yii\helpers\ArrayHelper; +use yii\helpers\Url; use yii\helpers\Html; /** @@ -218,7 +219,7 @@ class Menu extends Widget if (isset($item['url'])) { $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate); return strtr($template, [ - '{url}' => Html::url($item['url']), + '{url}' => Url::create($item['url']), '{label}' => $item['label'], ]); } else { From e758608a5a563ffff07c5b6b98a31dd41d7e7e3c Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 18:02:24 +0400 Subject: [PATCH 02/21] Added Url::asset --- framework/helpers/BaseUrl.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 3444a227bf..a6cb619eb6 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -57,9 +57,20 @@ class BaseUrl if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { return $url; } else { - return Yii::$app->getRequest()->getBaseUrl() . '/' . $url; + return static::asset($url); } } } + + /** + * Prefixes relative URL with base URL + * + * @param string $url relative URL + * @return string absolute URL + */ + public function asset($url) + { + return Yii::$app->getRequest()->getBaseUrl() . '/' . $url; + } } \ No newline at end of file From 5420517e21e6b3e797fc1db27ceb0fa877f0b492 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 18:07:54 +0400 Subject: [PATCH 03/21] Added Url::rememberReturnUrl --- framework/helpers/BaseUrl.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index a6cb619eb6..96275fa54e 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -72,5 +72,13 @@ class BaseUrl { return Yii::$app->getRequest()->getBaseUrl() . '/' . $url; } + + /** + * Sets current URL as return URL + */ + public function rememberReturnUrl() + { + Yii::$app->user->setReturnUrl(Yii::$app->getRequest()->getUrl()); + } } \ No newline at end of file From 14fc5bd1deb282d57c7d46945063d91424772a15 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 18:10:36 +0400 Subject: [PATCH 04/21] Added Url::canonical --- framework/helpers/BaseUrl.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 96275fa54e..6887677645 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -80,5 +80,15 @@ class BaseUrl { Yii::$app->user->setReturnUrl(Yii::$app->getRequest()->getUrl()); } + + /** + * Returns canonical URL for the current page + * + * @return string canonical URL + */ + public function canonical() + { + return Yii::$app->controller->getCanonicalUrl(); + } } \ No newline at end of file From 2cd5f982feb85ce3923bdf9ed29ea37127a795b4 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 18:15:37 +0400 Subject: [PATCH 05/21] Renamed methods, added Url::getHome --- framework/helpers/BaseUrl.php | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 6887677645..5a603541b6 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -57,7 +57,7 @@ class BaseUrl if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { return $url; } else { - return static::asset($url); + return static::base($url); } } } @@ -68,7 +68,7 @@ class BaseUrl * @param string $url relative URL * @return string absolute URL */ - public function asset($url) + public function base($url) { return Yii::$app->getRequest()->getBaseUrl() . '/' . $url; } @@ -76,7 +76,7 @@ class BaseUrl /** * Sets current URL as return URL */ - public function rememberReturnUrl() + public function rememberReturn() { Yii::$app->user->setReturnUrl(Yii::$app->getRequest()->getUrl()); } @@ -86,9 +86,19 @@ class BaseUrl * * @return string canonical URL */ - public function canonical() + public function getCanonical() { return Yii::$app->controller->getCanonicalUrl(); } + + /** + * Returns home URL + * + * @return string home URL + */ + public function getHome() + { + return Yii::$app->getHomeUrl(); + } } \ No newline at end of file From 8df9dddd70681631ab27ff465b67e0b94e2e813a Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 18:24:27 +0400 Subject: [PATCH 06/21] Added Url::createAbsolute, adjusted signiatures --- framework/helpers/BaseUrl.php | 48 ++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 5a603541b6..267a6e68ce 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -34,34 +34,58 @@ class BaseUrl * For example: `['post/index', 'page' => 2]`, `['index']`. * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * - * @param array|string $url the parameter to be used to generate a valid URL + * @param array|string $params the parameter to be used to generate a valid URL + * @param boolean $absolute if absolute URL should be created * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function create($url) + public static function create($params, $absolute = false) { - if (is_array($url)) { - if (isset($url[0])) { + if (is_array($params)) { + if (isset($params[0])) { if (Yii::$app->controller instanceof \yii\web\Controller) { - return Yii::$app->controller->createUrl($url); + return $absolute ? Yii::$app->controller->createAbsoluteUrl($params) : Yii::$app->controller->createUrl($params); } else { - return Yii::$app->getUrlManager()->createUrl($url); + return $absolute ? Yii::$app->getUrlManager()->createAbsoluteUrl($params) : Yii::$app->getUrlManager()->createUrl($params); } } else { throw new InvalidParamException('The array specifying a URL must contain at least one element.'); } - } elseif ($url === '') { - return Yii::$app->getRequest()->getUrl(); + } elseif ($params === '') { + return $absolute ? Yii::$app->getRequest()->getAbsoluteUrl() : Yii::$app->getRequest()->getUrl(); } else { - $url = Yii::getAlias($url); - if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { - return $url; + $params = Yii::getAlias($params); + if ($params !== '' && ($params[0] === '/' || $params[0] === '#' || strpos($params, '://') || !strncmp($params, './', 2))) { + return $params; } else { - return static::base($url); + return static::base($params); } } } + /** + * Normalizes the input parameter to be a valid absolute URL. + * + * If the input parameter + * + * - is an empty string: the currently requested URL will be returned; + * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result + * is an absolute URL, it will be returned without any change further; Otherwise, the result + * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + * - is an array: the first array element is considered a route, while the rest of the name-value + * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. + * For example: `['post/index', 'page' => 2]`, `['index']`. + * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. + * + * @param array|string $params the parameter to be used to generate a valid URL + * @return string the normalized URL + * @throws InvalidParamException if the parameter is invalid. + */ + public static function createAbsolute($params) + { + return static::create($params, true); + } + /** * Prefixes relative URL with base URL * From 2dacc4fb0ab5075832d14b99c8a85c2bec5367b0 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 18:30:20 +0400 Subject: [PATCH 07/21] Adjusted changelog --- framework/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index c85c9f31c3..69812a2eb5 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -231,6 +231,7 @@ Yii Framework 2 Change Log - New #1956: Implemented test fixture framework (qiangxue) - New #2149: Added `yii\base\DynamicModel` to support ad-hoc data validation (qiangxue) - New #2360: Added `AttributeBehavior` and `BlameableBehavior`, and renamed `AutoTimestamp` to `TimestampBehavior` (lucianobaraglia, qiangxue) +- New #2630: Added `yii\helpers\Url` (samdark) - New: Yii framework now comes with core messages in multiple languages - New: Added yii\codeception\DbTestCase (qiangxue) From 73b7e03ec3ea4b48539f47da1674ef254298017b Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 9 Mar 2014 19:09:03 +0400 Subject: [PATCH 08/21] Argument for Url::base is now optional --- framework/helpers/BaseUrl.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 267a6e68ce..37bce4bf49 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -92,9 +92,13 @@ class BaseUrl * @param string $url relative URL * @return string absolute URL */ - public function base($url) + public function base($url = null) { - return Yii::$app->getRequest()->getBaseUrl() . '/' . $url; + $result = Yii::$app->getRequest()->getBaseUrl(); + if ($url !== null) { + $result .= '/' . $url; + } + return $result; } /** From 92b381795b579e71d5de91eec967f55d6051b5f2 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 01:34:05 +0400 Subject: [PATCH 09/21] Adjusted Url helper methods --- .../templates/bootstrap/SideNavWidget.php | 2 +- extensions/authclient/widgets/Choice.php | 2 +- extensions/debug/views/default/toolbar.php | 2 +- extensions/debug/views/default/view.php | 2 +- extensions/elasticsearch/DebugPanel.php | 2 +- extensions/jui/Tabs.php | 2 +- framework/CHANGELOG.md | 2 +- framework/captcha/Captcha.php | 2 +- framework/grid/GridView.php | 2 +- framework/helpers/BaseHtml.php | 10 +- framework/helpers/BaseUrl.php | 124 +++++++++--------- framework/web/Controller.php | 2 +- framework/web/Response.php | 2 +- framework/widgets/ActiveForm.php | 2 +- framework/widgets/Menu.php | 2 +- 15 files changed, 80 insertions(+), 80 deletions(-) diff --git a/extensions/apidoc/templates/bootstrap/SideNavWidget.php b/extensions/apidoc/templates/bootstrap/SideNavWidget.php index 6013ee455c..f39064f4b6 100644 --- a/extensions/apidoc/templates/bootstrap/SideNavWidget.php +++ b/extensions/apidoc/templates/bootstrap/SideNavWidget.php @@ -136,7 +136,7 @@ class SideNavWidget extends \yii\bootstrap\Widget $label = $this->encodeLabels ? Html::encode($item['label']) : $item['label']; // $options = ArrayHelper::getValue($item, 'options', []); $items = ArrayHelper::getValue($item, 'items'); - $url = Url::create(ArrayHelper::getValue($item, 'url', '#')); + $url = Url::toRoute(ArrayHelper::getValue($item, 'url', '#')); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []); Html::addCssClass($linkOptions, 'list-group-item'); diff --git a/extensions/authclient/widgets/Choice.php b/extensions/authclient/widgets/Choice.php index 0ecda6fd17..ee993e4cc0 100644 --- a/extensions/authclient/widgets/Choice.php +++ b/extensions/authclient/widgets/Choice.php @@ -196,7 +196,7 @@ class Choice extends Widget $this->autoRender = false; $url = $this->getBaseAuthUrl(); $url[$this->clientIdGetParamName] = $provider->getId(); - return Url::create($url); + return Url::toRoute($url); } /** diff --git a/extensions/debug/views/default/toolbar.php b/extensions/debug/views/default/toolbar.php index 166d216c57..cee9b1d02b 100644 --- a/extensions/debug/views/default/toolbar.php +++ b/extensions/debug/views/default/toolbar.php @@ -28,7 +28,7 @@ $url = $firstPanel->getUrl(); ?>
- + Yii Debugger diff --git a/extensions/debug/views/default/view.php b/extensions/debug/views/default/view.php index ea98d42a62..6dcfaff17d 100644 --- a/extensions/debug/views/default/view.php +++ b/extensions/debug/views/default/view.php @@ -20,7 +20,7 @@ $this->title = 'Yii Debugger';
- + Yii Debugger diff --git a/extensions/elasticsearch/DebugPanel.php b/extensions/elasticsearch/DebugPanel.php index 80f9245bc4..12f6fdf3ab 100644 --- a/extensions/elasticsearch/DebugPanel.php +++ b/extensions/elasticsearch/DebugPanel.php @@ -84,7 +84,7 @@ EOD; }, ]); } - $ajaxUrl = Url::create(['elasticsearch-query', 'logId' => $logId, 'tag' => $this->tag]); + $ajaxUrl = Url::toRoute(['elasticsearch-query', 'logId' => $logId, 'tag' => $this->tag]); \Yii::$app->view->registerJs(<< Url::create(['/' . $this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1]), + 'refreshUrl' => Url::toRoute(['/' . $this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1]), 'hashKey' => "yiiCaptcha/{$this->captchaAction}", ]; return $options; diff --git a/framework/grid/GridView.php b/framework/grid/GridView.php index 37b5ad5508..c1c7e95bab 100644 --- a/framework/grid/GridView.php +++ b/framework/grid/GridView.php @@ -219,7 +219,7 @@ class GridView extends BaseListView } return [ - 'filterUrl' => Url::create($filterUrl), + 'filterUrl' => Url::toRoute($filterUrl), 'filterSelector' => $filterSelector, ]; } diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index 968848fd84..5e89e6b640 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -205,7 +205,7 @@ class BaseHtml if (!isset($options['rel'])) { $options['rel'] = 'stylesheet'; } - $options['href'] = Url::create($url); + $options['href'] = Url::toRoute($url); return static::tag('link', '', $options); } @@ -221,7 +221,7 @@ class BaseHtml */ public static function jsFile($url, $options = []) { - $options['src'] = Url::create($url); + $options['src'] = Url::toRoute($url); return static::tag('script', '', $options); } @@ -241,7 +241,7 @@ class BaseHtml */ public static function beginForm($action = '', $method = 'post', $options = []) { - $action = Url::create($action); + $action = Url::toRoute($action); $hiddenInputs = []; @@ -311,7 +311,7 @@ class BaseHtml public static function a($text, $url = null, $options = []) { if ($url !== null) { - $options['href'] = Url::create($url); + $options['href'] = Url::toRoute($url); } return static::tag('a', $text, $options); } @@ -346,7 +346,7 @@ class BaseHtml */ public static function img($src, $options = []) { - $options['src'] = Url::create($src); + $options['src'] = Url::toRoute($src); if (!isset($options['alt'])) { $options['alt'] = ''; } diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 37bce4bf49..83bfb4b68e 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -21,92 +21,90 @@ use Yii; class BaseUrl { /** - * Normalizes the input parameter to be a valid URL. + * Returns URL for a route. * - * If the input parameter + * @param array|string $route parametrized route or empty string for current URL: * - * - is an empty string: the currently requested URL will be returned; - * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result - * is an absolute URL, it will be returned without any change further; Otherwise, the result - * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. - * - is an array: the first array element is considered a route, while the rest of the name-value + * - an empty string: the currently requested URL will be returned; + * - an array: the first array element is considered a route, while the rest of the name-value * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. * For example: `['post/index', 'page' => 2]`, `['index']`. * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * - * @param array|string $params the parameter to be used to generate a valid URL * @param boolean $absolute if absolute URL should be created * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function create($params, $absolute = false) + public static function toRoute($route, $absolute = false) { - if (is_array($params)) { - if (isset($params[0])) { - if (Yii::$app->controller instanceof \yii\web\Controller) { - return $absolute ? Yii::$app->controller->createAbsoluteUrl($params) : Yii::$app->controller->createUrl($params); - } else { - return $absolute ? Yii::$app->getUrlManager()->createAbsoluteUrl($params) : Yii::$app->getUrlManager()->createUrl($params); - } - } else { - throw new InvalidParamException('The array specifying a URL must contain at least one element.'); - } - } elseif ($params === '') { + if ($route === '') { return $absolute ? Yii::$app->getRequest()->getAbsoluteUrl() : Yii::$app->getRequest()->getUrl(); + } + if (!is_array($route) || !isset($route[0])) { + throw new InvalidParamException('$route should be either empty string or array containing at least one element.'); + } + if (Yii::$app->controller instanceof \yii\web\Controller) { + return $absolute ? Yii::$app->controller->createAbsoluteUrl($route) : Yii::$app->controller->createUrl($route); } else { - $params = Yii::getAlias($params); - if ($params !== '' && ($params[0] === '/' || $params[0] === '#' || strpos($params, '://') || !strncmp($params, './', 2))) { - return $params; - } else { - return static::base($params); + return $absolute ? Yii::$app->getUrlManager()->createAbsoluteUrl($route) : Yii::$app->getUrlManager()->createUrl($route); + } + } + + /** + * Returns URL to asset located under webroot + * + * @param string $asset will first be processed by [[Yii::getAlias()]]. If the result is an absolute URL, it will be + * returned without any change further; Otherwise, the result will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + * @param boolean $absolute if URL should be absolute + * @return string + */ + public function toAsset($asset = null, $absolute = false) + { + $route = Yii::getAlias($asset); + if ($route !== '' && ($route[0] === '/' || $route[0] === '#' || strpos($route, '://') || !strncmp($route, './', 2))) { + return $route; + } else { + $result = $absolute ? Yii::$app->getRequest()->getHostInfo() : ''; + $result .= Yii::$app->getRequest()->getBaseUrl(); + if ($asset !== null) { + $result .= '/' . $asset; } + return $result; } } /** - * Normalizes the input parameter to be a valid absolute URL. + * Remembers URL passed * - * If the input parameter - * - * - is an empty string: the currently requested URL will be returned; - * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result - * is an absolute URL, it will be returned without any change further; Otherwise, the result - * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. - * - is an array: the first array element is considered a route, while the rest of the name-value - * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. - * For example: `['post/index', 'page' => 2]`, `['index']`. - * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. - * - * @param array|string $params the parameter to be used to generate a valid URL - * @return string the normalized URL - * @throws InvalidParamException if the parameter is invalid. + * @param string $url URL to remember. Default is current URL. + * @param string $name Name to use to remember URL. Defaults to `yii\web\User::returnUrlParam`. */ - public static function createAbsolute($params) + public function remember($url = null, $name = null) { - return static::create($params, true); - } - - /** - * Prefixes relative URL with base URL - * - * @param string $url relative URL - * @return string absolute URL - */ - public function base($url = null) - { - $result = Yii::$app->getRequest()->getBaseUrl(); - if ($url !== null) { - $result .= '/' . $url; + if ($url === null) { + $url = Yii::$app->getRequest()->getUrl(); + } + + if ($name === null) { + Yii::$app->user->setReturnUrl($url); + } else { + Yii::$app->session->set($name, $url); } - return $result; } /** - * Sets current URL as return URL + * Returns URL previously saved with remember method + * + * @param string $name Name used to remember URL. Defaults to `yii\web\User::returnUrlParam`. + * @return string URL */ - public function rememberReturn() + public function previous($name = null) { - Yii::$app->user->setReturnUrl(Yii::$app->getRequest()->getUrl()); + if ($name === null) { + return Yii::$app->user->getReturnUrl(); + } else { + return Yii::$app->session->get($name); + } } /** @@ -114,7 +112,7 @@ class BaseUrl * * @return string canonical URL */ - public function getCanonical() + public function canonical() { return Yii::$app->controller->getCanonicalUrl(); } @@ -122,11 +120,13 @@ class BaseUrl /** * Returns home URL * + * @param boolean $absolute if absolute URL should be returned * @return string home URL */ - public function getHome() + public function home($absolute = false) { - return Yii::$app->getHomeUrl(); + $result = $absolute ? Yii::$app->request->getHostInfo() : ''; + return $result . Yii::$app->getHomeUrl(); } } \ No newline at end of file diff --git a/framework/web/Controller.php b/framework/web/Controller.php index 0a474536ec..94b43d9c86 100644 --- a/framework/web/Controller.php +++ b/framework/web/Controller.php @@ -241,7 +241,7 @@ class Controller extends \yii\base\Controller */ public function redirect($url, $statusCode = 302) { - return Yii::$app->getResponse()->redirect(Url::create($url), $statusCode); + return Yii::$app->getResponse()->redirect(Url::toRoute($url), $statusCode); } /** diff --git a/framework/web/Response.php b/framework/web/Response.php index 70c72c8a8b..e06e7ab553 100644 --- a/framework/web/Response.php +++ b/framework/web/Response.php @@ -673,7 +673,7 @@ class Response extends \yii\base\Response // ensure the route is absolute $url[0] = '/' . ltrim($url[0], '/'); } - $url = Url::create($url); + $url = Url::toRoute($url); if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) { $url = Yii::$app->getRequest()->getHostInfo() . $url; } diff --git a/framework/widgets/ActiveForm.php b/framework/widgets/ActiveForm.php index c7000e7513..800e1be4cd 100644 --- a/framework/widgets/ActiveForm.php +++ b/framework/widgets/ActiveForm.php @@ -195,7 +195,7 @@ class ActiveForm extends Widget 'ajaxDataType' => $this->ajaxDataType, ]; if ($this->validationUrl !== null) { - $options['validationUrl'] = Url::create($this->validationUrl); + $options['validationUrl'] = Url::toRoute($this->validationUrl); } foreach (['beforeSubmit', 'beforeValidate', 'afterValidate'] as $name) { if (($value = $this->$name) !== null) { diff --git a/framework/widgets/Menu.php b/framework/widgets/Menu.php index 7cea1afbe4..8bf70739da 100644 --- a/framework/widgets/Menu.php +++ b/framework/widgets/Menu.php @@ -219,7 +219,7 @@ class Menu extends Widget if (isset($item['url'])) { $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate); return strtr($template, [ - '{url}' => Url::create($item['url']), + '{url}' => Url::toRoute($item['url']), '{label}' => $item['label'], ]); } else { From 5d6c314d4e2ee2d535ac9a08fb39d3fb56ad0daf Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 15:25:15 +0400 Subject: [PATCH 10/21] Adjusted URL helper, fixed usage --- .../templates/bootstrap/SideNavWidget.php | 2 +- extensions/authclient/widgets/Choice.php | 2 +- extensions/debug/views/default/toolbar.php | 2 +- extensions/debug/views/default/view.php | 2 +- extensions/elasticsearch/DebugPanel.php | 2 +- extensions/jui/Tabs.php | 2 +- extensions/smarty/ViewRenderer.php | 3 +- extensions/twig/ViewRenderer.php | 3 +- framework/captcha/Captcha.php | 2 +- framework/grid/GridView.php | 2 +- framework/helpers/BaseHtml.php | 10 ++--- framework/helpers/BaseUrl.php | 41 ++++++++++++------- framework/web/Controller.php | 2 +- framework/web/Response.php | 2 +- framework/widgets/ActiveForm.php | 2 +- framework/widgets/Menu.php | 2 +- 16 files changed, 47 insertions(+), 34 deletions(-) diff --git a/extensions/apidoc/templates/bootstrap/SideNavWidget.php b/extensions/apidoc/templates/bootstrap/SideNavWidget.php index f39064f4b6..3399875c6c 100644 --- a/extensions/apidoc/templates/bootstrap/SideNavWidget.php +++ b/extensions/apidoc/templates/bootstrap/SideNavWidget.php @@ -136,7 +136,7 @@ class SideNavWidget extends \yii\bootstrap\Widget $label = $this->encodeLabels ? Html::encode($item['label']) : $item['label']; // $options = ArrayHelper::getValue($item, 'options', []); $items = ArrayHelper::getValue($item, 'items'); - $url = Url::toRoute(ArrayHelper::getValue($item, 'url', '#')); + $url = Url::to(ArrayHelper::getValue($item, 'url', '#')); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []); Html::addCssClass($linkOptions, 'list-group-item'); diff --git a/extensions/authclient/widgets/Choice.php b/extensions/authclient/widgets/Choice.php index ee993e4cc0..48c3d12186 100644 --- a/extensions/authclient/widgets/Choice.php +++ b/extensions/authclient/widgets/Choice.php @@ -196,7 +196,7 @@ class Choice extends Widget $this->autoRender = false; $url = $this->getBaseAuthUrl(); $url[$this->clientIdGetParamName] = $provider->getId(); - return Url::toRoute($url); + return Url::to($url); } /** diff --git a/extensions/debug/views/default/toolbar.php b/extensions/debug/views/default/toolbar.php index cee9b1d02b..0dd3a7dd67 100644 --- a/extensions/debug/views/default/toolbar.php +++ b/extensions/debug/views/default/toolbar.php @@ -28,7 +28,7 @@ $url = $firstPanel->getUrl(); ?>
- + Yii Debugger diff --git a/extensions/debug/views/default/view.php b/extensions/debug/views/default/view.php index 6dcfaff17d..53dd25bd9b 100644 --- a/extensions/debug/views/default/view.php +++ b/extensions/debug/views/default/view.php @@ -20,7 +20,7 @@ $this->title = 'Yii Debugger';
- + Yii Debugger diff --git a/extensions/elasticsearch/DebugPanel.php b/extensions/elasticsearch/DebugPanel.php index 12f6fdf3ab..b7ac2f3bcd 100644 --- a/extensions/elasticsearch/DebugPanel.php +++ b/extensions/elasticsearch/DebugPanel.php @@ -84,7 +84,7 @@ EOD; }, ]); } - $ajaxUrl = Url::toRoute(['elasticsearch-query', 'logId' => $logId, 'tag' => $this->tag]); + $ajaxUrl = Url::to(['elasticsearch-query', 'logId' => $logId, 'tag' => $this->tag]); \Yii::$app->view->registerJs(<<twig->addFunction('path', new \Twig_Function_Function(function ($path, $args = []) { - return BaseViewRenderer::url(array_merge([$path], $args)); + return Url::to(array_merge([$path], $args)); })); $this->twig->addGlobal('app', \Yii::$app); diff --git a/framework/captcha/Captcha.php b/framework/captcha/Captcha.php index e56fade69c..23a55a257c 100644 --- a/framework/captcha/Captcha.php +++ b/framework/captcha/Captcha.php @@ -107,7 +107,7 @@ class Captcha extends InputWidget protected function getClientOptions() { $options = [ - 'refreshUrl' => Url::toRoute(['/' . $this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1]), + 'refreshUrl' => Url::to(['/' . $this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1]), 'hashKey' => "yiiCaptcha/{$this->captchaAction}", ]; return $options; diff --git a/framework/grid/GridView.php b/framework/grid/GridView.php index c1c7e95bab..a1c183eaac 100644 --- a/framework/grid/GridView.php +++ b/framework/grid/GridView.php @@ -219,7 +219,7 @@ class GridView extends BaseListView } return [ - 'filterUrl' => Url::toRoute($filterUrl), + 'filterUrl' => Url::to($filterUrl), 'filterSelector' => $filterSelector, ]; } diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index 5e89e6b640..99012a0b76 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -205,7 +205,7 @@ class BaseHtml if (!isset($options['rel'])) { $options['rel'] = 'stylesheet'; } - $options['href'] = Url::toRoute($url); + $options['href'] = Url::to($url); return static::tag('link', '', $options); } @@ -221,7 +221,7 @@ class BaseHtml */ public static function jsFile($url, $options = []) { - $options['src'] = Url::toRoute($url); + $options['src'] = Url::to($url); return static::tag('script', '', $options); } @@ -241,7 +241,7 @@ class BaseHtml */ public static function beginForm($action = '', $method = 'post', $options = []) { - $action = Url::toRoute($action); + $action = Url::to($action); $hiddenInputs = []; @@ -311,7 +311,7 @@ class BaseHtml public static function a($text, $url = null, $options = []) { if ($url !== null) { - $options['href'] = Url::toRoute($url); + $options['href'] = Url::to($url); } return static::tag('a', $text, $options); } @@ -346,7 +346,7 @@ class BaseHtml */ public static function img($src, $options = []) { - $options['src'] = Url::toRoute($src); + $options['src'] = Url::to($src); if (!isset($options['alt'])) { $options['alt'] = ''; } diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 83bfb4b68e..c92efc68a3 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -51,25 +51,36 @@ class BaseUrl } /** - * Returns URL to asset located under webroot + * Normalizes the input parameter to be a valid URL. * - * @param string $asset will first be processed by [[Yii::getAlias()]]. If the result is an absolute URL, it will be - * returned without any change further; Otherwise, the result will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + * If the input parameter + * + * - is an empty string: the currently requested URL will be returned; + * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result + * is an absolute URL, it will be returned without any change further; Otherwise, the result + * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + * - is an array: the first array element is considered a route, while the rest of the name-value + * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. + * For example: `['post/index', 'page' => 2]`, `['index']`. + * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. + * + * @param array|string $url the parameter to be used to generate a valid URL * @param boolean $absolute if URL should be absolute - * @return string + * @return string the normalized URL + * @throws InvalidParamException if the parameter is invalid. */ - public function toAsset($asset = null, $absolute = false) + public static function to($url = null, $absolute = false) { - $route = Yii::getAlias($asset); - if ($route !== '' && ($route[0] === '/' || $route[0] === '#' || strpos($route, '://') || !strncmp($route, './', 2))) { - return $route; + if (is_array($url) && isset($url[0]) || $url === '') { + return static::to($url, $absolute); } else { - $result = $absolute ? Yii::$app->getRequest()->getHostInfo() : ''; - $result .= Yii::$app->getRequest()->getBaseUrl(); - if ($asset !== null) { - $result .= '/' . $asset; + $url = Yii::getAlias($url); + if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { + return $url; + } else { + $prefix = $absolute ? Yii::$app->request->getHostInfo() : ''; + return $prefix . Yii::$app->getRequest()->getBaseUrl() . '/' . $url; } - return $result; } } @@ -125,8 +136,8 @@ class BaseUrl */ public function home($absolute = false) { - $result = $absolute ? Yii::$app->request->getHostInfo() : ''; - return $result . Yii::$app->getHomeUrl(); + $prefix = $absolute ? Yii::$app->request->getHostInfo() : ''; + return $prefix . Yii::$app->getHomeUrl(); } } \ No newline at end of file diff --git a/framework/web/Controller.php b/framework/web/Controller.php index 94b43d9c86..b747343c50 100644 --- a/framework/web/Controller.php +++ b/framework/web/Controller.php @@ -241,7 +241,7 @@ class Controller extends \yii\base\Controller */ public function redirect($url, $statusCode = 302) { - return Yii::$app->getResponse()->redirect(Url::toRoute($url), $statusCode); + return Yii::$app->getResponse()->redirect(Url::to($url), $statusCode); } /** diff --git a/framework/web/Response.php b/framework/web/Response.php index e06e7ab553..faa093ed34 100644 --- a/framework/web/Response.php +++ b/framework/web/Response.php @@ -673,7 +673,7 @@ class Response extends \yii\base\Response // ensure the route is absolute $url[0] = '/' . ltrim($url[0], '/'); } - $url = Url::toRoute($url); + $url = Url::to($url); if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) { $url = Yii::$app->getRequest()->getHostInfo() . $url; } diff --git a/framework/widgets/ActiveForm.php b/framework/widgets/ActiveForm.php index 800e1be4cd..50dcec7784 100644 --- a/framework/widgets/ActiveForm.php +++ b/framework/widgets/ActiveForm.php @@ -195,7 +195,7 @@ class ActiveForm extends Widget 'ajaxDataType' => $this->ajaxDataType, ]; if ($this->validationUrl !== null) { - $options['validationUrl'] = Url::toRoute($this->validationUrl); + $options['validationUrl'] = Url::to($this->validationUrl); } foreach (['beforeSubmit', 'beforeValidate', 'afterValidate'] as $name) { if (($value = $this->$name) !== null) { diff --git a/framework/widgets/Menu.php b/framework/widgets/Menu.php index 8bf70739da..0c81a0e8de 100644 --- a/framework/widgets/Menu.php +++ b/framework/widgets/Menu.php @@ -219,7 +219,7 @@ class Menu extends Widget if (isset($item['url'])) { $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate); return strtr($template, [ - '{url}' => Url::toRoute($item['url']), + '{url}' => Url::to($item['url']), '{label}' => $item['label'], ]); } else { From cb5a8896216dfcb18d1a5cd5d2c6c9dd25b8a03a Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 15:39:31 +0400 Subject: [PATCH 11/21] Fixed recursion --- framework/helpers/BaseUrl.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index c92efc68a3..02fab01cb5 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -72,7 +72,7 @@ class BaseUrl public static function to($url = null, $absolute = false) { if (is_array($url) && isset($url[0]) || $url === '') { - return static::to($url, $absolute); + return static::toRoute($url, $absolute); } else { $url = Yii::getAlias($url); if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { From 67af6bc84ac232d9f7634fe58105873ad21c9d40 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 15:50:43 +0400 Subject: [PATCH 12/21] Fixed inconsistent usage of getters --- framework/helpers/BaseUrl.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 02fab01cb5..5dffe84aa9 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -78,7 +78,7 @@ class BaseUrl if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { return $url; } else { - $prefix = $absolute ? Yii::$app->request->getHostInfo() : ''; + $prefix = $absolute ? Yii::$app->getRequest()->getHostInfo() : ''; return $prefix . Yii::$app->getRequest()->getBaseUrl() . '/' . $url; } } @@ -97,9 +97,9 @@ class BaseUrl } if ($name === null) { - Yii::$app->user->setReturnUrl($url); + Yii::$app->getUser()->setReturnUrl($url); } else { - Yii::$app->session->set($name, $url); + Yii::$app->getSession()->set($name, $url); } } @@ -112,9 +112,9 @@ class BaseUrl public function previous($name = null) { if ($name === null) { - return Yii::$app->user->getReturnUrl(); + return Yii::$app->getUser()->getReturnUrl(); } else { - return Yii::$app->session->get($name); + return Yii::$app->getSession()->get($name); } } @@ -136,7 +136,7 @@ class BaseUrl */ public function home($absolute = false) { - $prefix = $absolute ? Yii::$app->request->getHostInfo() : ''; + $prefix = $absolute ? Yii::$app->getRequest()->getHostInfo() : ''; return $prefix . Yii::$app->getHomeUrl(); } } From 338bc86e6d1b88ac939e6c1356f69a3549cb92f5 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 15:54:25 +0400 Subject: [PATCH 13/21] Fixed absolute URLs in Url::to --- framework/helpers/BaseUrl.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 5dffe84aa9..bf520de13d 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -76,7 +76,7 @@ class BaseUrl } else { $url = Yii::getAlias($url); if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { - return $url; + return strpos($url, '://') ? $url : Yii::$app->getRequest()->getHostInfo() . $url; } else { $prefix = $absolute ? Yii::$app->getRequest()->getHostInfo() : ''; return $prefix . Yii::$app->getRequest()->getBaseUrl() . '/' . $url; From bd271d42e41cc8e6342fa1698036bb997c168d1a Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 16:33:17 +0400 Subject: [PATCH 14/21] Removed passing unused parameter --- framework/web/UrlManager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/web/UrlManager.php b/framework/web/UrlManager.php index 85709c98e8..504cfd2993 100644 --- a/framework/web/UrlManager.php +++ b/framework/web/UrlManager.php @@ -292,7 +292,7 @@ class UrlManager extends Component $params = (array)$params; $url = $this->createUrl($params); if (strpos($url, '://') === false) { - $url = $this->getHostInfo($schema) . $url; + $url = $this->getHostInfo() . $url; } if ($schema !== null && ($pos = strpos($url, '://')) !== false) { $url = $schema . substr($url, $pos); From aeb25c39e160975a3212ea7e7718fcffd01436f6 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 17:52:03 +0400 Subject: [PATCH 15/21] Further adjustments for Url helper --- framework/helpers/BaseUrl.php | 89 ++++++++++++++++++++++------------- 1 file changed, 56 insertions(+), 33 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index bf520de13d..0fe8b4c253 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -23,64 +23,82 @@ class BaseUrl /** * Returns URL for a route. * - * @param array|string $route parametrized route or empty string for current URL: + * @param array|string $route route as a string or route and parameters in form of + * ['route', 'param1' => 'value1', 'param2' => 'value2']. * - * - an empty string: the currently requested URL will be returned; - * - an array: the first array element is considered a route, while the rest of the name-value - * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. - * For example: `['post/index', 'page' => 2]`, `['index']`. - * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. + * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * - * @param boolean $absolute if absolute URL should be created + * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function toRoute($route, $absolute = false) + public static function toRoute($route, $schema = null) { - if ($route === '') { - return $absolute ? Yii::$app->getRequest()->getAbsoluteUrl() : Yii::$app->getRequest()->getUrl(); - } - if (!is_array($route) || !isset($route[0])) { - throw new InvalidParamException('$route should be either empty string or array containing at least one element.'); + $route = (array)$route; + if (!isset($route[0])) { + throw new InvalidParamException('$route should contain at least one element.'); } if (Yii::$app->controller instanceof \yii\web\Controller) { - return $absolute ? Yii::$app->controller->createAbsoluteUrl($route) : Yii::$app->controller->createUrl($route); + return $schema === null ? Yii::$app->controller->createUrl($route) : Yii::$app->controller->createAbsoluteUrl($route, $schema); } else { - return $absolute ? Yii::$app->getUrlManager()->createAbsoluteUrl($route) : Yii::$app->getUrlManager()->createUrl($route); + return $schema === null ? Yii::$app->getUrlManager()->createUrl($route) : Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema); } } /** - * Normalizes the input parameter to be a valid URL. + * Creates a link specified by the input parameter. * * If the input parameter * - * - is an empty string: the currently requested URL will be returned; - * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result - * is an absolute URL, it will be returned without any change further; Otherwise, the result - * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. * - is an array: the first array element is considered a route, while the rest of the name-value * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. * For example: `['post/index', 'page' => 2]`, `['index']`. * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. + * - is an empty string: the currently requested URL will be returned; + * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result + * is an absolute URL, it will be returned without any change further; Otherwise, the result + * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + * * @param array|string $url the parameter to be used to generate a valid URL - * @param boolean $absolute if URL should be absolute + * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function to($url = null, $absolute = false) + public static function to($url = '', $schema = null) { - if (is_array($url) && isset($url[0]) || $url === '') { - return static::toRoute($url, $absolute); + if (is_array($url)) { + return static::toRoute($url, $schema); + } elseif ($url === '') { + if ($schema === null) { + return Yii::$app->request->getUrl(); + } else { + $url = Yii::$app->request->getAbsoluteUrl(); + $pos = strpos($url, '://'); + return $schema . substr($url, $pos); + } } else { $url = Yii::getAlias($url); - if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) { - return strpos($url, '://') ? $url : Yii::$app->getRequest()->getHostInfo() . $url; - } else { - $prefix = $absolute ? Yii::$app->getRequest()->getHostInfo() : ''; - return $prefix . Yii::$app->getRequest()->getBaseUrl() . '/' . $url; + $pos = strpos($url, '://'); + if ($pos !== null) { + if ($schema !== null) { + $url = $schema . substr($url, $pos); + } + return $url; } + + if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || !strncmp($url, './', 2))) { + $url = Yii::$app->getRequest()->getHostInfo() . $url; + } else { + $url = Yii::$app->getRequest()->getBaseUrl() . '/' . $url; + } + if ($schema !== null) { + $pos = strpos($url, '://'); + if ($pos !== null) { + $url = $schema . substr($url, $pos); + } + } + return $url; } } @@ -131,13 +149,18 @@ class BaseUrl /** * Returns home URL * - * @param boolean $absolute if absolute URL should be returned + * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. * @return string home URL */ - public function home($absolute = false) + public function home($schema = null) { - $prefix = $absolute ? Yii::$app->getRequest()->getHostInfo() : ''; - return $prefix . Yii::$app->getHomeUrl(); + if ($schema === null) { + return Yii::$app->getHomeUrl(); + } else { + $url = Yii::$app->getRequest()->getHostInfo() . Yii::$app->getHomeUrl(); + $pos = strpos($url, '://'); + return $schema . substr($url, $pos); + } } } \ No newline at end of file From 1276970ce56cf71dbee200e408eaa7e9adb46fe9 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 17:57:24 +0400 Subject: [PATCH 16/21] Made $url default consistent --- framework/helpers/BaseUrl.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 0fe8b4c253..24224e8b1e 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -108,9 +108,9 @@ class BaseUrl * @param string $url URL to remember. Default is current URL. * @param string $name Name to use to remember URL. Defaults to `yii\web\User::returnUrlParam`. */ - public function remember($url = null, $name = null) + public function remember($url = '', $name = null) { - if ($url === null) { + if ($url === '') { $url = Yii::$app->getRequest()->getUrl(); } From 2b842ecc577a39bcce50605c8ebf2a88276d1cf9 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 19:40:32 +0400 Subject: [PATCH 17/21] Moded URL management methods from controller to Url helper, updated docs --- docs/guide/url.md | 46 +++++++++++------ framework/CHANGELOG.md | 7 ++- framework/helpers/BaseUrl.php | 63 +++++++++++++++++++---- framework/web/Controller.php | 97 +---------------------------------- 4 files changed, 89 insertions(+), 124 deletions(-) diff --git a/docs/guide/url.md b/docs/guide/url.md index 2347ae17a5..eb76c6a7d5 100644 --- a/docs/guide/url.md +++ b/docs/guide/url.md @@ -51,20 +51,30 @@ examples may also output: * `http://www.example.com/blog/post/index/` * `http://www.example.com/index.php?r=blog/post/index` -Inside a web application controller, you can use the controller's `createUrl` shortcut method. Unlike the global -`createUrl` method, the controller version is context sensitive: +In order to simplify URL creation there is [[yii\helpers\Url]] helper that is able to do the following: ```php -echo $this->createUrl(''); // currently active route -echo $this->createUrl(['view', 'id' => 'contact']); // same controller, different action -echo $this->createUrl('post/index'); // same module, different controller and action -echo $this->createUrl('/site/index'); // absolute route no matter what controller is making this call -echo $this->createurl('hi-tech'); // url for the case sensitive action `actionHiTech` of the current controller -echo $this->createurl(['/date-time/fast-forward', 'id' => 105]); // url for action the case sensitive controller, `DateTimeController::actionFastForward` +use yii\helpers\Url; + +echo Url::to(''); // currently active URL + +echo Url::toRoute(['view', 'id' => 'contact']); // same controller, different action +echo Url::toRoute('post/index'); // same module, different controller and action +echo Url::toRoute('/site/index'); // absolute route no matter what controller is making this call +echo Url::toRoute('hi-tech'); // url for the case sensitive action `actionHiTech` of the current controller +echo Url::toRoute(['/date-time/fast-forward', 'id' => 105]); // url for action the case sensitive controller, `DateTimeController::actionFastForward` + +echo Url::to('@web'); // get URL from alias + +echo Url::canonical(); // get canonical URL for the curent page +echo Url::home(); // get home URL + +Url::remember(); // save URL to be used later +Url::previous(); // get previously saved URL ``` > **Tip**: In order to generate URL with a hashtag, for example `/index.php?r=site/page&id=100#title`, you need to - specify the parameter named `#` using `$this->createUrl(['post/read', 'id' => 100, '#' => 'title'])`. + specify the parameter named `#` using `Url::to(['post/read', 'id' => 100, '#' => 'title'])`. Customizing URLs ---------------- @@ -114,21 +124,25 @@ Let's use some examples to explain how URL rules work. We assume that our rule s ] ``` -- Calling `$this->createUrl('post/list')` generates `/index.php/posts`. The first rule is applied. -- Calling `$this->createUrl(['post/read', 'id' => 100])` generates `/index.php/post/100`. The second rule is applied. -- Calling `$this->createUrl(['post/read', 'year' => 2008, 'title' => 'a sample post'])` generates +- Calling `Url::toRoute('post/list')` generates `/index.php/posts`. The first rule is applied. +- Calling `Url::toRoute(['post/read', 'id' => 100])` generates `/index.php/post/100`. The second rule is applied. +- Calling `Url::toRoute(['post/read', 'year' => 2008, 'title' => 'a sample post'])` generates `/index.php/post/2008/a%20sample%20post`. The third rule is applied. -- Calling `$this->createUrl('post/read')` generates `/index.php/post/read`. None of the rules is applied, convention is used +- Calling `Url::toRoute('post/read')` generates `/index.php/post/read`. None of the rules is applied, convention is used instead. In summary, when using `createUrl` to generate a URL, the route and the `GET` parameters passed to the method are used to decide which URL rule to be applied. If every parameter associated with a rule can be found in the `GET` parameters passed to `createUrl`, and if the route of the rule also matches the route parameter, the rule will be used to generate the URL. -If the `GET` parameters passed to `createUrl` are more than those required by a rule, the additional parameters will appear in the query string. For example, if we call `$this->createUrl('post/read', ['id' => 100, 'year' => 2008])`, we will obtain `/index.php/post/100?year=2008`. +If the `GET` parameters passed to `Url::toRoute` are more than those required by a rule, the additional parameters will +appear in the query string. For example, if we call `Url::toRoute(['post/read', 'id' => 100, 'year' => 2008])`, we will +obtain `/index.php/post/100?year=2008`. -As we mentioned earlier, the other purpose of URL rules is to parse the requesting URLs. Naturally, this is an inverse process of URL creation. For example, when a user requests for `/index.php/post/100`, the second rule in the above example will apply, which resolves in the route `post/read` and the `GET` parameter `['id' => 100]` (accessible via -`Yii::$app->request->getQueryParam('id')`). +As we mentioned earlier, the other purpose of URL rules is to parse the requesting URLs. Naturally, this is an inverse +process of URL creation. For example, when a user requests for `/index.php/post/100`, the second rule in the above example +will apply, which resolves in the route `post/read` and the `GET` parameter `['id' => 100]` (accessible via +`Yii::$app->request->get('id')`). ### Parameterizing Routes diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index aba1b4ec2b..f42f5e891e 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -191,7 +191,11 @@ Yii Framework 2 Change Log - Chg #2544: Changed `DetailView`'s `name:format:label` to `attribute:format:label` to match `GridView` (samdark) - Chg #2603: `yii\base\ErrorException` now extends `\ErrorException` (samdark) - Chg #2629: `Module::controllerPath` is now read only, and all controller classes must be namespaced under `Module::controllerNamespace`. (qiangxue) -- Chg #2630: `yii\heplers\Html::url` removed (samdark) +- Chg #2630: API changes for URLs generation (samdark, qiangxue, cebe) + - Added `yii\helpers\Url`. + - Removed `yii\heplers\Html::url`, use `yii\helpers\Url::to` instead. + - Removed `yii\web\Controller::createUrl` and `yii\web\Controller::createAbsoluteUrl`, use `yii\helpers::toRoute` instead. + - Removed `yii\web\Controller::getCanonicalUrl`, use `yii\helpers::canonical` instead. - Chg: Renamed `yii\jui\Widget::clientEventsMap` to `clientEventMap` (qiangxue) - Chg: Renamed `ActiveRecord::getPopulatedRelations()` to `getRelatedRecords()` (qiangxue) - Chg: Renamed `attributeName` and `className` to `targetAttribute` and `targetClass` for `UniqueValidator` and `ExistValidator` (qiangxue) @@ -231,7 +235,6 @@ Yii Framework 2 Change Log - New #1956: Implemented test fixture framework (qiangxue) - New #2149: Added `yii\base\DynamicModel` to support ad-hoc data validation (qiangxue) - New #2360: Added `AttributeBehavior` and `BlameableBehavior`, and renamed `AutoTimestamp` to `TimestampBehavior` (lucianobaraglia, qiangxue) -- New #2630: Added `yii\helpers\Url` (samdark) - New: Yii framework now comes with core messages in multiple languages - New: Added yii\codeception\DbTestCase (qiangxue) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 24224e8b1e..f72b5e9705 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -26,6 +26,14 @@ class BaseUrl * @param array|string $route route as a string or route and parameters in form of * ['route', 'param1' => 'value1', 'param2' => 'value2']. * + * If there is a controller running relative routes are recognized: + * + * - If the route is an empty string, the current [[route]] will be used; + * - If the route contains no slashes at all, it is considered to be an action ID + * of the current controller and will be prepended with [[uniqueId]]; + * - If the route has no leading slash, it is considered to be a route relative + * to the current module and will be prepended with the module's uniqueId. + * * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. @@ -39,10 +47,36 @@ class BaseUrl throw new InvalidParamException('$route should contain at least one element.'); } if (Yii::$app->controller instanceof \yii\web\Controller) { - return $schema === null ? Yii::$app->controller->createUrl($route) : Yii::$app->controller->createAbsoluteUrl($route, $schema); - } else { - return $schema === null ? Yii::$app->getUrlManager()->createUrl($route) : Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema); + $route[0] = static::getNormalizedRoute($route[0]); } + return $schema === null ? Yii::$app->getUrlManager()->createUrl($route) : Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema); + } + + /** + * Normalizes route making it suitable for UrlManager. Absolute routes are staying as is + * while relative routes are converted to absolute routes. + * + * A relative route is a route without a leading slash, such as "view", "post/view". + * + * - If the route is an empty string, the current [[route]] will be used; + * - If the route contains no slashes at all, it is considered to be an action ID + * of the current controller and will be prepended with [[uniqueId]]; + * - If the route has no leading slash, it is considered to be a route relative + * to the current module and will be prepended with the module's uniqueId. + * + * @param string $route the route. This can be either an absolute route or a relative route. + * @return string normalized route suitable for UrlManager + */ + private static function getNormalizedRoute($route) + { + if (strpos($route, '/') === false) { + // empty or an action ID + $route = $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route; + } elseif ($route[0] !== '/') { + // relative to module + $route = ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/'); + } + return $route; } /** @@ -108,7 +142,7 @@ class BaseUrl * @param string $url URL to remember. Default is current URL. * @param string $name Name to use to remember URL. Defaults to `yii\web\User::returnUrlParam`. */ - public function remember($url = '', $name = null) + public static function remember($url = '', $name = null) { if ($url === '') { $url = Yii::$app->getRequest()->getUrl(); @@ -127,7 +161,7 @@ class BaseUrl * @param string $name Name used to remember URL. Defaults to `yii\web\User::returnUrlParam`. * @return string URL */ - public function previous($name = null) + public static function previous($name = null) { if ($name === null) { return Yii::$app->getUser()->getReturnUrl(); @@ -137,13 +171,22 @@ class BaseUrl } /** - * Returns canonical URL for the current page + * Returns the canonical URL of the currently requested page. + * The canonical URL is constructed using current controller's [[yii\web\Controller::route]] and + * [[yii\web\Controller::actionParams]]. You may use the following code in the layout view to add a link tag + * about canonical URL: * - * @return string canonical URL + * ```php + * $this->registerLinkTag(['rel' => 'canonical', 'href' => Url::canonical()]); + * ``` + * + * @return string the canonical URL of the currently requested page */ - public function canonical() + public static function canonical() { - return Yii::$app->controller->getCanonicalUrl(); + $params = Yii::$app->controller->actionParams; + $params[0] = Yii::$app->controller->getRoute(); + return Yii::$app->getUrlManager()->createAbsoluteUrl($params); } /** @@ -152,7 +195,7 @@ class BaseUrl * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. * @return string home URL */ - public function home($schema = null) + public static function home($schema = null) { if ($schema === null) { return Yii::$app->getHomeUrl(); diff --git a/framework/web/Controller.php b/framework/web/Controller.php index b747343c50..f74dffe6ac 100644 --- a/framework/web/Controller.php +++ b/framework/web/Controller.php @@ -28,7 +28,7 @@ class Controller extends \yii\base\Controller */ public $enableCsrfValidation = true; /** - * @var array the parameters bound to the current action. This is mainly used by [[getCanonicalUrl()]]. + * @var array the parameters bound to the current action. */ public $actionParams = []; @@ -118,101 +118,6 @@ class Controller extends \yii\base\Controller } } - /** - * Normalizes route making it suitable for UrlManager. Absolute routes are staying as is - * while relative routes are converted to absolute routes. - * - * A relative route is a route without a leading slash, such as "view", "post/view". - * - * - If the route is an empty string, the current [[route]] will be used; - * - If the route contains no slashes at all, it is considered to be an action ID - * of the current controller and will be prepended with [[uniqueId]]; - * - If the route has no leading slash, it is considered to be a route relative - * to the current module and will be prepended with the module's uniqueId. - * - * @param string $route the route. This can be either an absolute route or a relative route. - * @return string normalized route suitable for UrlManager - */ - protected function getNormalizedRoute($route) - { - if (strpos($route, '/') === false) { - // empty or an action ID - $route = $route === '' ? $this->getRoute() : $this->getUniqueId() . '/' . $route; - } elseif ($route[0] !== '/') { - // relative to module - $route = ltrim($this->module->getUniqueId() . '/' . $route, '/'); - } - return $route; - } - - /** - * Creates a relative URL using the given route and parameters. - * - * This method enhances [[UrlManager::createUrl()]] by supporting relative routes. - * A relative route is a route without a leading slash, such as "view", "post/view". - * - * - If the route is an empty string, the current [[route]] will be used; - * - If the route contains no slashes at all, it is considered to be an action ID - * of the current controller and will be prepended with [[uniqueId]]; - * - If the route has no leading slash, it is considered to be a route relative - * to the current module and will be prepended with the module's uniqueId. - * - * After this route conversion, the method calls [[UrlManager::createUrl()]] to create a URL. - * - * @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2'] - * @return string the created relative URL - */ - public function createUrl($params) - { - $params = (array)$params; - $params[0] = $this->getNormalizedRoute($params[0]); - return Yii::$app->getUrlManager()->createUrl($params); - } - - /** - * Creates an absolute URL using the given route and parameters. - * - * This method enhances [[UrlManager::createAbsoluteUrl()]] by supporting relative routes. - * A relative route is a route without a leading slash, such as "view", "post/view". - * - * - If the route is an empty string, the current [[route]] will be used; - * - If the route contains no slashes at all, it is considered to be an action ID - * of the current controller and will be prepended with [[uniqueId]]; - * - If the route has no leading slash, it is considered to be a route relative - * to the current module and will be prepended with the module's uniqueId. - * - * After this route conversion, the method calls [[UrlManager::createUrl()]] to create a URL. - * - * @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2'] - * @param string $schema the schema to use for the url. e.g. 'http' or 'https'. If not specified - * the schema of the current request will be used. - * @return string the created absolute URL - */ - public function createAbsoluteUrl($params, $schema = null) - { - $params = (array)$params; - $params[0] = $this->getNormalizedRoute($params[0]); - return Yii::$app->getUrlManager()->createAbsoluteUrl($params, $schema); - } - - /** - * Returns the canonical URL of the currently requested page. - * The canonical URL is constructed using [[route]] and [[actionParams]]. You may use the following code - * in the layout view to add a link tag about canonical URL: - * - * ~~~ - * $this->registerLinkTag(['rel' => 'canonical', 'href' => Yii::$app->controller->canonicalUrl]); - * ~~~ - * - * @return string the canonical URL of the currently requested page - */ - public function getCanonicalUrl() - { - $params = $this->actionParams; - $params[0] = $this->getRoute(); - return Yii::$app->getUrlManager()->createAbsoluteUrl($params); - } - /** * Redirects the browser to the specified URL. * This method is a shortcut to [[Response::redirect()]]. From 577f8a5c5049eb0c23b54961dce876c139967dbe Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 20:11:06 +0400 Subject: [PATCH 18/21] Added separate schema and absolute parameters --- framework/helpers/BaseUrl.php | 67 ++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 29 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index f72b5e9705..2004ad0333 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -36,11 +36,12 @@ class BaseUrl * * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * - * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. + * @param boolean $absolute if absolute URL should be created. + * @param string $schema URI schema to use. Schema to use for absolute URL. If not specified current schema will be used. * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function toRoute($route, $schema = null) + public static function toRoute($route, $absolute = false, $schema = null) { $route = (array)$route; if (!isset($route[0])) { @@ -49,7 +50,7 @@ class BaseUrl if (Yii::$app->controller instanceof \yii\web\Controller) { $route[0] = static::getNormalizedRoute($route[0]); } - return $schema === null ? Yii::$app->getUrlManager()->createUrl($route) : Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema); + return $absolute ? Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema) : Yii::$app->getUrlManager()->createUrl($route); } /** @@ -95,45 +96,49 @@ class BaseUrl * * @param array|string $url the parameter to be used to generate a valid URL - * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. + * @param boolean $absolute if absolute URL should be created. + * @param string $schema URI schema to use. Schema to use for absolute URL. If not specified current schema will be used. * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function to($url = '', $schema = null) + public static function to($url = '', $absolute = false, $schema = null) { if (is_array($url)) { - return static::toRoute($url, $schema); + return static::toRoute($url, $absolute, $schema); } elseif ($url === '') { - if ($schema === null) { - return Yii::$app->request->getUrl(); - } else { + if ($absolute) { $url = Yii::$app->request->getAbsoluteUrl(); $pos = strpos($url, '://'); - return $schema . substr($url, $pos); + $url = $schema . substr($url, $pos); + } else { + $url = Yii::$app->request->getUrl(); } } else { $url = Yii::getAlias($url); $pos = strpos($url, '://'); if ($pos !== null) { + // URI is already absolute, adjust schema if specified if ($schema !== null) { $url = $schema . substr($url, $pos); } - return $url; - } - - if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || !strncmp($url, './', 2))) { - $url = Yii::$app->getRequest()->getHostInfo() . $url; } else { - $url = Yii::$app->getRequest()->getBaseUrl() . '/' . $url; - } - if ($schema !== null) { - $pos = strpos($url, '://'); - if ($pos !== null) { - $url = $schema . substr($url, $pos); + // URI is relative + if ($url === '' || ($url[0] !== '/' && $url[0] !== '#' && strncmp($url, './', 2))) { + // URL is relative need to adjust it to be absolute + $url = Yii::$app->getRequest()->getBaseUrl() . '/' . $url; + } + if ($absolute) { + $url = Yii::$app->getRequest()->getHostInfo() . $url; + if ($schema !== null) { + $pos = strpos($url, '://'); + if ($pos !== null) { + $url = $schema . substr($url, $pos); + } + } } } - return $url; } + return $url; } /** @@ -192,18 +197,22 @@ class BaseUrl /** * Returns home URL * - * @param string $schema URI schema to use. If specified absolute URL with the schema specified is returned. + * @param boolean $absolute if absolute URL should be created. + * @param string $schema URI schema to use. Schema to use for absolute URL. If not specified current schema will be used. * @return string home URL */ - public static function home($schema = null) + public static function home($absolute = false, $schema = null) { - if ($schema === null) { - return Yii::$app->getHomeUrl(); - } else { + if ($absolute) { $url = Yii::$app->getRequest()->getHostInfo() . Yii::$app->getHomeUrl(); - $pos = strpos($url, '://'); - return $schema . substr($url, $pos); + if ($schema !== null) { + $pos = strpos($url, '://'); + $url = $schema . substr($url, $pos); + } + } else { + $url = Yii::$app->getHomeUrl(); } + return $url; } } \ No newline at end of file From bddad5280c64d50ceeb1e494474669d34bf153d1 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 10 Mar 2014 20:29:24 +0400 Subject: [PATCH 19/21] Combined $schema and $absolute into $schema --- framework/helpers/BaseUrl.php | 62 +++++++++++++++++++++-------------- framework/web/UrlManager.php | 2 +- 2 files changed, 39 insertions(+), 25 deletions(-) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 2004ad0333..8738474a12 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -24,24 +24,28 @@ class BaseUrl * Returns URL for a route. * * @param array|string $route route as a string or route and parameters in form of - * ['route', 'param1' => 'value1', 'param2' => 'value2']. + * `['route', 'param1' => 'value1', 'param2' => 'value2']`. * * If there is a controller running relative routes are recognized: * - * - If the route is an empty string, the current [[route]] will be used; + * - If the route is an empty string, the current [[\yii\web\Controller::route]] will be used; * - If the route contains no slashes at all, it is considered to be an action ID - * of the current controller and will be prepended with [[uniqueId]]; + * of the current controller and will be prepended with [[\yii\web\Controller::uniqueId]]; * - If the route has no leading slash, it is considered to be a route relative * to the current module and will be prepended with the module's uniqueId. * * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * - * @param boolean $absolute if absolute URL should be created. - * @param string $schema URI schema to use. Schema to use for absolute URL. If not specified current schema will be used. + * @param boolean|string $schema URI schema to use: + * + * - `false`: relative URL. Default behavior. + * - `true`: absolute URL with the current scheme. + * - string: absolute URL with string value used as schema. + * * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function toRoute($route, $absolute = false, $schema = null) + public static function toRoute($route, $schema = false) { $route = (array)$route; if (!isset($route[0])) { @@ -50,7 +54,7 @@ class BaseUrl if (Yii::$app->controller instanceof \yii\web\Controller) { $route[0] = static::getNormalizedRoute($route[0]); } - return $absolute ? Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema) : Yii::$app->getUrlManager()->createUrl($route); + return $schema ? Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema) : Yii::$app->getUrlManager()->createUrl($route); } /** @@ -59,9 +63,9 @@ class BaseUrl * * A relative route is a route without a leading slash, such as "view", "post/view". * - * - If the route is an empty string, the current [[route]] will be used; + * - If the route is an empty string, the current [[\yii\web\Controller::route]] will be used; * - If the route contains no slashes at all, it is considered to be an action ID - * of the current controller and will be prepended with [[uniqueId]]; + * of the current controller and will be prepended with [[\yii\web\Controller::uniqueId]]; * - If the route has no leading slash, it is considered to be a route relative * to the current module and will be prepended with the module's uniqueId. * @@ -96,20 +100,26 @@ class BaseUrl * * @param array|string $url the parameter to be used to generate a valid URL - * @param boolean $absolute if absolute URL should be created. - * @param string $schema URI schema to use. Schema to use for absolute URL. If not specified current schema will be used. + * @param boolean|string $schema URI schema to use: + * + * - `false`: relative URL. Default behavior. + * - `true`: absolute URL with the current scheme. + * - string: absolute URL with string value used as schema. + * * @return string the normalized URL * @throws InvalidParamException if the parameter is invalid. */ - public static function to($url = '', $absolute = false, $schema = null) + public static function to($url = '', $schema = false) { if (is_array($url)) { - return static::toRoute($url, $absolute, $schema); + return static::toRoute($url, $schema); } elseif ($url === '') { - if ($absolute) { + if ($schema) { $url = Yii::$app->request->getAbsoluteUrl(); - $pos = strpos($url, '://'); - $url = $schema . substr($url, $pos); + if ($schema !== true) { + $pos = strpos($url, '://'); + $url = $schema . substr($url, $pos); + } } else { $url = Yii::$app->request->getUrl(); } @@ -118,7 +128,7 @@ class BaseUrl $pos = strpos($url, '://'); if ($pos !== null) { // URI is already absolute, adjust schema if specified - if ($schema !== null) { + if ($schema && $schema !== true) { $url = $schema . substr($url, $pos); } } else { @@ -127,9 +137,9 @@ class BaseUrl // URL is relative need to adjust it to be absolute $url = Yii::$app->getRequest()->getBaseUrl() . '/' . $url; } - if ($absolute) { + if ($schema) { $url = Yii::$app->getRequest()->getHostInfo() . $url; - if ($schema !== null) { + if ($schema !== true) { $pos = strpos($url, '://'); if ($pos !== null) { $url = $schema . substr($url, $pos); @@ -197,15 +207,19 @@ class BaseUrl /** * Returns home URL * - * @param boolean $absolute if absolute URL should be created. - * @param string $schema URI schema to use. Schema to use for absolute URL. If not specified current schema will be used. + * @param boolean|string $schema URI schema to use: + * + * - `false`: relative URL. Default behavior. + * - `true`: absolute URL with the current scheme. + * - string: absolute URL with string value used as schema. + * * @return string home URL */ - public static function home($absolute = false, $schema = null) + public static function home($schema = false) { - if ($absolute) { + if ($schema) { $url = Yii::$app->getRequest()->getHostInfo() . Yii::$app->getHomeUrl(); - if ($schema !== null) { + if ($schema !== true) { $pos = strpos($url, '://'); $url = $schema . substr($url, $pos); } diff --git a/framework/web/UrlManager.php b/framework/web/UrlManager.php index 504cfd2993..0094371994 100644 --- a/framework/web/UrlManager.php +++ b/framework/web/UrlManager.php @@ -294,7 +294,7 @@ class UrlManager extends Component if (strpos($url, '://') === false) { $url = $this->getHostInfo() . $url; } - if ($schema !== null && ($pos = strpos($url, '://')) !== false) { + if ($schema && ($pos = strpos($url, '://')) !== false) { $url = $schema . substr($url, $pos); } return $url; From 842e7eb573dbab7d2d31ed08f1d41f8da5381e55 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Tue, 11 Mar 2014 02:12:13 +0400 Subject: [PATCH 20/21] Added tests, final Url helper adjustments --- framework/helpers/BaseUrl.php | 49 +++---- tests/unit/framework/helpers/UrlTest.php | 173 +++++++++++++++++++++++ 2 files changed, 194 insertions(+), 28 deletions(-) create mode 100644 tests/unit/framework/helpers/UrlTest.php diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 8738474a12..9392517408 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -48,13 +48,18 @@ class BaseUrl public static function toRoute($route, $schema = false) { $route = (array)$route; - if (!isset($route[0])) { - throw new InvalidParamException('$route should contain at least one element.'); - } if (Yii::$app->controller instanceof \yii\web\Controller) { $route[0] = static::getNormalizedRoute($route[0]); } - return $schema ? Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema) : Yii::$app->getUrlManager()->createUrl($route); + if ($schema) { + if ($schema === true) { + $schema = null; + } + $url = Yii::$app->getUrlManager()->createAbsoluteUrl($route, $schema); + } else { + $url = Yii::$app->getUrlManager()->createUrl($route); + } + return $url; } /** @@ -90,13 +95,13 @@ class BaseUrl * If the input parameter * * - is an array: the first array element is considered a route, while the rest of the name-value - * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. + * pairs are treated as the parameters to be used for URL creation using [[toRoute]]. * For example: `['post/index', 'page' => 2]`, `['index']`. * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * - is an empty string: the currently requested URL will be returned; * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result - * is an absolute URL, it will be returned without any change further; Otherwise, the result - * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + * is an absolute URL, it will be returned either without any change or, if schema was specified, with schema + * replaced; Otherwise, the result will be prefixed with [[\yii\web\Request::baseUrl]] and returned. * * @param array|string $url the parameter to be used to generate a valid URL @@ -115,39 +120,27 @@ class BaseUrl return static::toRoute($url, $schema); } elseif ($url === '') { if ($schema) { - $url = Yii::$app->request->getAbsoluteUrl(); - if ($schema !== true) { - $pos = strpos($url, '://'); - $url = $schema . substr($url, $pos); - } + $url = Yii::$app->getRequest()->getAbsoluteUrl(); } else { - $url = Yii::$app->request->getUrl(); + $url = Yii::$app->getRequest()->getUrl(); } } else { $url = Yii::getAlias($url); - $pos = strpos($url, '://'); - if ($pos !== null) { - // URI is already absolute, adjust schema if specified - if ($schema && $schema !== true) { - $url = $schema . substr($url, $pos); - } - } else { - // URI is relative + if (strpos($url, '://') === false) { if ($url === '' || ($url[0] !== '/' && $url[0] !== '#' && strncmp($url, './', 2))) { - // URL is relative need to adjust it to be absolute $url = Yii::$app->getRequest()->getBaseUrl() . '/' . $url; } if ($schema) { $url = Yii::$app->getRequest()->getHostInfo() . $url; - if ($schema !== true) { - $pos = strpos($url, '://'); - if ($pos !== null) { - $url = $schema . substr($url, $pos); - } - } } } } + if ($schema && $schema !== true) { + $pos = strpos($url, '://'); + if ($pos !== false) { + $url = $schema . substr($url, $pos); + } + } return $url; } diff --git a/tests/unit/framework/helpers/UrlTest.php b/tests/unit/framework/helpers/UrlTest.php new file mode 100644 index 0000000000..e982eaf5ce --- /dev/null +++ b/tests/unit/framework/helpers/UrlTest.php @@ -0,0 +1,173 @@ +mockApplication([ + 'components' => [ + 'request' => [ + 'class' => 'yii\web\Request', + 'scriptUrl' => '/base/index.php', + 'hostInfo' => 'http://example.com/', + 'url' => '/base/index.php&r=site/current&id=42' + ], + 'user' => [ + 'class' => 'yii\web\User', + 'identityClass' => 'stdObject', + ], + ], + ], '\yii\web\Application'); + } + + /** + * Mocks controller action with parameters + * + * @param string $controllerId + * @param string $actionId + * @param string $moduleID + * @param array $params + */ + protected function mockAction($controllerId, $actionId, $moduleID = null, $params = []) + { + \Yii::$app->controller = $controller = new Controller($controllerId, \Yii::$app); + $controller->actionParams = $params; + $controller->action = new Action($actionId, $controller); + + if ($moduleID !== null) { + $controller->module = new Module($moduleID); + } + } + + protected function removeMockedAction() + { + \Yii::$app->controller = null; + } + + public function testToRoute() + { + $this->mockAction('page', 'view', null, ['id' => 10]); + + // If the route is an empty string, the current route will be used; + $this->assertEquals('/base/index.php?r=page/view', Url::toRoute('')); + $this->assertEquals('http://example.com/base/index.php?r=page/view', Url::toRoute('', true)); + $this->assertEquals('https://example.com/base/index.php?r=page/view', Url::toRoute('', 'https')); + + // If the route contains no slashes at all, it is considered to be an action ID of the current controller and + // will be prepended with uniqueId; + $this->assertEquals('/base/index.php?r=page/edit', Url::toRoute('edit')); + $this->assertEquals('/base/index.php?r=page/edit&id=20', Url::toRoute(['edit', 'id' => 20])); + $this->assertEquals('http://example.com/base/index.php?r=page/edit&id=20', Url::toRoute(['edit', 'id' => 20], true)); + $this->assertEquals('https://example.com/base/index.php?r=page/edit&id=20', Url::toRoute(['edit', 'id' => 20], 'https')); + + // If the route has no leading slash, it is considered to be a route relative + // to the current module and will be prepended with the module's uniqueId. + $this->mockAction('default', 'index', 'stats'); + $this->assertEquals('/base/index.php?r=stats/user/view', Url::toRoute('user/view')); + $this->assertEquals('/base/index.php?r=stats/user/view&id=42', Url::toRoute(['user/view', 'id' => 42])); + $this->assertEquals('http://example.com/base/index.php?r=stats/user/view&id=42', Url::toRoute(['user/view', 'id' => 42], true)); + $this->assertEquals('https://example.com/base/index.php?r=stats/user/view&id=42', Url::toRoute(['user/view', 'id' => 42], 'https')); + + // In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. + $this->removeMockedAction(); + + $this->assertEquals('/base/index.php?r=site/view', Url::toRoute('site/view')); + $this->assertEquals('http://example.com/base/index.php?r=site/view', Url::toRoute('site/view', true)); + $this->assertEquals('https://example.com/base/index.php?r=site/view', Url::toRoute('site/view', 'https')); + $this->assertEquals('/base/index.php?r=site/view&id=37', Url::toRoute(['site/view', 'id' => 37])); + } + + public function testTo() + { + // is an array: the first array element is considered a route, while the rest of the name-value + // pairs are treated as the parameters to be used for URL creation using Url::toRoute. + $this->mockAction('page', 'view', null, ['id' => 10]); + $this->assertEquals('/base/index.php?r=page/edit&id=20', Url::to(['edit', 'id' => 20])); + $this->assertEquals('/base/index.php?r=page/edit', Url::to(['edit'])); + $this->assertEquals('/base/index.php?r=page/view', Url::to([''])); + + $this->assertEquals('http://example.com/base/index.php?r=page/edit&id=20', Url::to(['edit', 'id' => 20], true)); + $this->assertEquals('http://example.com/base/index.php?r=page/edit', Url::to(['edit'], true)); + $this->assertEquals('http://example.com/base/index.php?r=page/view', Url::to([''], true)); + + $this->assertEquals('https://example.com/base/index.php?r=page/edit&id=20', Url::to(['edit', 'id' => 20], 'https')); + $this->assertEquals('https://example.com/base/index.php?r=page/edit', Url::to(['edit'], 'https')); + $this->assertEquals('https://example.com/base/index.php?r=page/view', Url::to([''], 'https')); + + //In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. + $this->removeMockedAction(); + + $this->assertEquals('/base/index.php?r=edit&id=20', Url::to(['edit', 'id' => 20])); + $this->assertEquals('/base/index.php?r=edit', Url::to(['edit'])); + $this->assertEquals('/base/index.php?r=', Url::to([''])); + + $this->assertEquals('http://example.com/base/index.php?r=edit&id=20', Url::to(['edit', 'id' => 20], true)); + $this->assertEquals('http://example.com/base/index.php?r=edit', Url::to(['edit'], true)); + $this->assertEquals('http://example.com/base/index.php?r=', Url::to([''], true)); + + $this->assertEquals('https://example.com/base/index.php?r=edit&id=20', Url::to(['edit', 'id' => 20], 'https')); + $this->assertEquals('https://example.com/base/index.php?r=edit', Url::to(['edit'], 'https')); + $this->assertEquals('https://example.com/base/index.php?r=', Url::to([''], 'https')); + + // is an empty string: the currently requested URL will be returned; + $this->mockAction('page', 'view', null, ['id' => 10]); + $this->assertEquals('/base/index.php&r=site/current&id=42', Url::to('')); + $this->assertEquals('http://example.com/base/index.php&r=site/current&id=42', Url::to('', true)); + $this->assertEquals('https://example.com/base/index.php&r=site/current&id=42', Url::to('', 'https')); + $this->removeMockedAction(); + + // is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result + // is an absolute URL, it will be returned either without any change or, if schema was specified, with schema + // replaced; Otherwise, the result will be prefixed with [[\yii\web\Request::baseUrl]] and returned. + \Yii::setAlias('@web1', 'http://test.example.com/test/me1'); + \Yii::setAlias('@web2', 'test/me2'); + \Yii::setAlias('@web3', ''); + \Yii::setAlias('@web4', '/test'); + \Yii::setAlias('@web5', '#test'); + + $this->assertEquals('http://test.example.com/test/me1', Url::to('@web1')); + $this->assertEquals('http://test.example.com/test/me1', Url::to('@web1', true)); + $this->assertEquals('https://test.example.com/test/me1', Url::to('@web1', 'https')); + + $this->assertEquals('/base/test/me2', Url::to('@web2')); + $this->assertEquals('http://example.com/base/test/me2', Url::to('@web2', true)); + $this->assertEquals('https://example.com/base/test/me2', Url::to('@web2', 'https')); + + $this->assertEquals('/base/', Url::to('@web3')); + $this->assertEquals('http://example.com/base/', Url::to('@web3', true)); + $this->assertEquals('https://example.com/base/', Url::to('@web3', 'https')); + + $this->assertEquals('/test', Url::to('@web4')); + $this->assertEquals('http://example.com/test', Url::to('@web4', true)); + $this->assertEquals('https://example.com/test', Url::to('@web4', 'https')); + + $this->assertEquals('#test', Url::to('@web5')); + $this->assertEquals('http://example.com#test', Url::to('@web5', true)); + $this->assertEquals('https://example.com#test', Url::to('@web5', 'https')); + } + + public function testHome() + { + $this->assertEquals('/base/index.php', Url::home()); + $this->assertEquals('http://example.com/base/index.php', Url::home(true)); + $this->assertEquals('https://example.com/base/index.php', Url::home('https')); + } + + public function testCanonical() + { + $this->mockAction('page', 'view', null, ['id' => 10]); + $this->assertEquals('http://example.com/base/index.php?r=page/view&id=10', Url::canonical()); + $this->removeMockedAction(); + } +} From 2ceab799e2a20f9bb93d3a9b3998ad3d5d98f6f6 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Tue, 11 Mar 2014 02:12:53 +0400 Subject: [PATCH 21/21] Removed unneeded config from tests --- tests/unit/framework/helpers/UrlTest.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/unit/framework/helpers/UrlTest.php b/tests/unit/framework/helpers/UrlTest.php index e982eaf5ce..19b5aea72d 100644 --- a/tests/unit/framework/helpers/UrlTest.php +++ b/tests/unit/framework/helpers/UrlTest.php @@ -23,10 +23,6 @@ class UrlTest extends TestCase 'hostInfo' => 'http://example.com/', 'url' => '/base/index.php&r=site/current&id=42' ], - 'user' => [ - 'class' => 'yii\web\User', - 'identityClass' => 'stdObject', - ], ], ], '\yii\web\Application'); }