diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 78881e2..dcbeead 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -28,6 +28,7 @@ Yii Framework 2 Change Log - Enh #6467: `ActiveForm` will scroll to the nearest visible element when the first error input is hidden (newartix) - Enh #6488: Support changing `yii\base\Theme::basePath` during runtime (qiangxue) - Enh #6618: Added Model::addErrors() (slavcodev, pana1990) +- Enh #6697: Added `yii\helpers\Url::current()` method that allows adding or removing parameters from current URL (samdark, callmez) - Enh #6739: Log `Target` now works also when there is no `Yii::$app` instance available, no message prefix will be added in this case (schmunk42) - Enh #6748: Improved HTML to Text converter in BaseMailer to generate more readable and correct text version of emails (cebe) - Chg #5690: adjusted paths in message config generated by `yii message/config` to reflect directory structure better (mikehaertl, samdark) diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 667e75e..4f79505 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -342,4 +342,27 @@ class BaseUrl { return strncmp($url, '//', 2) && strpos($url, '://') === false; } + + /** + * Creates URL from the current one by adding parameters specified. + * + * @param array $params associative array of parameters. If value is null, parameter will be removed. + * @param boolean|string $scheme the URI scheme to use in the generated URL: + * + * - `false` (default): generating a relative URL. + * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]]. + * - string: generating an absolute URL with the specified scheme (either `http` or `https`). + * + * @return string the generated URL + * + * @since 2.0.2 + */ + public static function current(array $params = [], $scheme = false) + { + $currentParms = Yii::$app->controller->actionParams; + $currentParms[0] = Yii::$app->controller->getRoute(); + $route = ArrayHelper::merge($currentParms, $params); + + return static::toRoute($route, $scheme); + } } diff --git a/tests/unit/framework/helpers/UrlTest.php b/tests/unit/framework/helpers/UrlTest.php index ae053e3..875dc29 100644 --- a/tests/unit/framework/helpers/UrlTest.php +++ b/tests/unit/framework/helpers/UrlTest.php @@ -94,6 +94,17 @@ class UrlTest extends TestCase Url::toRoute('site/view'); } + public function testCurrent() + { + $this->mockAction('page', 'view', null, ['id' => 10, 'name' => 'test']); + + $this->assertEquals('/base/index.php?r=page%2Fview&id=10&name=test', Url::current()); + + $this->assertEquals('/base/index.php?r=page%2Fview&id=20&name=test', Url::current(['id' => 20])); + + $this->assertEquals('/base/index.php?r=page%2Fview&name=test', Url::current(['id' => null])); + } + public function testTo() { // is an array: the first array element is considered a route, while the rest of the name-value