Class luya\cms\helpers\Url
Inheritance | luya\cms\helpers\Url » luya\helpers\Url » luya\yii\helpers\Url » yii\helpers\BaseUrl |
---|---|
Available since version | 1.0.0 |
Source Code | https://github.com/luyadev/luya-module-cms/blob/master/src/helpers/Url.php |
CMS Url Helper class extends luya\helpers\Url by CMS routing methods.
In addition to the luya\helpers\Url method which is extend it also allows you to make url rule calls to the cms specific contents. The CMS URL helper can only be used when the CMS module is loaded and used within your project application.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$urlManager | yii\web\UrlManager | URL manager to use for creating URLs | yii\helpers\BaseUrl |
Public Methods
Method | Description | Defined By |
---|---|---|
appendQuery() | Append a query to the current url. | luya\yii\helpers\Url |
appendQueryToUrl() | Append an url part to an url | luya\yii\helpers\Url |
base() | Returns the base URL of the current request. | yii\helpers\BaseUrl |
canonical() | Returns the canonical URL of the currently requested page. | yii\helpers\BaseUrl |
cleanHost() | Removes schema, protocol and www. subdomain from host. | luya\yii\helpers\Url |
current() | Creates a URL by using the current route and the GET parameters. | yii\helpers\BaseUrl |
domain() | Return only the domain of a path. | luya\yii\helpers\Url |
ensureHttp() | Apply the http protcol to an url to make sure valid clickable links. Commonly used when provide link where user could have added urls in an administration area. For Example: | luya\yii\helpers\Url |
ensureScheme() | Normalize the URL by ensuring it uses specified scheme. | yii\helpers\BaseUrl |
home() | Returns the home URL. | yii\helpers\BaseUrl |
isRelative() | Returns a value indicating whether a URL is relative. | yii\helpers\BaseUrl |
previous() | Returns the URL previously remembered. | yii\helpers\BaseUrl |
remember() | Remembers the specified URL so that it can be later fetched back by previous(). | yii\helpers\BaseUrl |
to() | Creates a URL based on the given parameters. | yii\helpers\BaseUrl |
toAjax() | Create a link to use when point to an ajax script. | luya\yii\helpers\Url |
toInternal() | This helper method will not concern any context informations | luya\yii\helpers\Url |
toMenuNav() | Create an url to a cms page based on the nav id. | luya\cms\helpers\Url |
toMenuNavItem() | Create an url to a cms page based on the unique nav item id. | luya\cms\helpers\Url |
toModule() | Link to a registered Module. | luya\cms\helpers\Url |
toModuleRoute() | Link to a registered Module with custom Route and Params. | luya\cms\helpers\Url |
toRoute() | Creates a URL for the given route. | yii\helpers\BaseUrl |
trailing() | Add a trailing slash to an url if there is no trailing slash at the end of the url. | luya\yii\helpers\Url |
Protected Methods
Method | Description | Defined By |
---|---|---|
getUrlManager() | yii\helpers\BaseUrl | |
normalizeRoute() | Normalizes route and makes it suitable for UrlManager. Absolute routes are staying as is while relative routes are converted to absolute ones. | yii\helpers\BaseUrl |
Method Details
Defined in: luya\yii\helpers\Url::appendQuery()
Append a query to the current url.
See {{luya\yii\helpers\Url::appendToUrl()}}
public static string appendQuery ( $append, $scheme = false ) | ||
$append | string|array |
A string with url fragments or an array which will be processed by http_build_query. |
$scheme | boolean |
Add full path schema to the url, by default false. Otherwise absolute paths are used (including domain). |
public static function appendQuery($append, $scheme = false)
{
$url = $scheme ? Yii::$app->request->absoluteUrl : Yii::$app->request->url;
return self::appendQueryToUrl($url, $append);
}
Defined in: luya\yii\helpers\Url::appendQueryToUrl()
Append an url part to an url
public static string appendQueryToUrl ( $url, $append ) | ||
$url | string |
The url where the data should be appended. |
$append | string|array |
The query param to append, if an array is given http_build_query() will taken to build the query string. |
return | string |
Returns the url with appended query string |
---|
public static function appendQueryToUrl($url, $append)
{
if (is_array($append)) {
$append = http_build_query($append);
}
// remove starting & and ? chars
$append = ltrim($append, '&?');
// use &: Do we have already a ? in the url
if (StringHelper::contains('?', $url)) {
// seperator already existing
if (StringHelper::endsWith($url, '&') || StringHelper::endsWith($url, '?')) {
return $url . $append;
}
// add seperator
return $url . '&' . $append;
}
// use ?
return $url . '?' . $append;
}
Defined in: yii\helpers\BaseUrl::base()
Returns the base URL of the current request.
public static string base ( $scheme = false ) | ||
$scheme | boolean|string |
The URI scheme to use in the returned base URL:
|
public static function base($scheme = false)
{
$url = static::getUrlManager()->getBaseUrl();
if ($scheme !== false) {
$url = static::getUrlManager()->getHostInfo() . $url;
$url = static::ensureScheme($url, $scheme);
}
return $url;
}
Defined in: yii\helpers\BaseUrl::canonical()
Returns the canonical URL of the currently requested page.
The canonical URL is constructed using the 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:
$this->registerLinkTag(['rel' => 'canonical', 'href' => Url::canonical()]);
public static string canonical ( ) | ||
return | string |
The canonical URL of the currently requested page |
---|
public static function canonical()
{
$params = Yii::$app->controller->actionParams;
$params[0] = Yii::$app->controller->getRoute();
return static::getUrlManager()->createAbsoluteUrl($params);
}
Defined in: luya\yii\helpers\Url::cleanHost()
Removes schema, protocol and www. subdomain from host.
For example https://luya.io/path
would return luya.io/path
.
public static string cleanHost ( $url ) | ||
$url | string |
The url to extract |
return | string |
Returns the url without protocol or www. subdomain |
---|
public static function cleanHost($url)
{
return str_replace(['www.', 'http://', 'https://'], '', Url::ensureHttp($url));
}
Defined in: yii\helpers\BaseUrl::current()
Creates a URL by using the current route and the GET parameters.
You may modify or remove some of the GET parameters, or add additional query parameters through
the $params
parameter. In particular, if you specify a parameter to be null, then this parameter
will be removed from the existing GET parameters; all other parameters specified in $params
will
be merged with the existing GET parameters. For example,
// assume $_GET = ['id' => 123, 'src' => 'google'], current route is "post/view"
// /index.php?r=post%2Fview&id=123&src=google
echo Url::current();
// /index.php?r=post%2Fview&id=123
echo Url::current(['src' => null]);
// /index.php?r=post%2Fview&id=100&src=google
echo Url::current(['id' => 100]);
Note that if you're replacing array parameters with []
at the end you should specify $params
as nested arrays.
For a PostSearchForm
model where parameter names are PostSearchForm[id]
and PostSearchForm[src]
the syntax
would be the following:
// index.php?r=post%2Findex&PostSearchForm%5Bid%5D=100&PostSearchForm%5Bsrc%5D=google
echo Url::current([
$postSearch->formName() => ['id' => 100, 'src' => 'google'],
]);
public static string current ( array $params = [], $scheme = false ) | ||
$params | array |
An associative array of parameters that will be merged with the current GET parameters. If a parameter value is null, the corresponding GET parameter will be removed. |
$scheme | boolean|string |
The URI scheme to use in the generated URL:
|
return | string |
The generated URL |
---|
public static function current(array $params = [], $scheme = false)
{
$currentParams = Yii::$app->getRequest()->getQueryParams();
$currentParams[0] = '/' . Yii::$app->controller->getRoute();
$route = array_replace_recursive($currentParams, $params);
return static::toRoute($route, $scheme);
}
Defined in: luya\yii\helpers\Url::domain()
Return only the domain of a path.
For example https://luya.io/path
would return luya.io
without path informations.
public static string domain ( $url ) | ||
$url | string |
The url to extract |
return | string |
Returns only the domain from the url. |
---|
public static function domain($url)
{
return self::cleanHost(parse_url(Url::ensureHttp($url), PHP_URL_HOST));
}
Defined in: luya\yii\helpers\Url::ensureHttp()
Apply the http protcol to an url to make sure valid clickable links. Commonly used when provide link where user could have added urls in an administration area. For Example:
Url::ensureHttp('luya.io'); // return http://luya.io
Url::ensureHttp('www.luya.io'); // return https://luya.io
Url::ensureHttp('luya.io', true); // return https://luya.io
public static string ensureHttp ( $url, $https = false ) | ||
$url | string |
The url where the http protcol should be applied to if missing |
$https | boolean |
Whether the ensured url should be returned as https or not. |
public static function ensureHttp($url, $https = false)
{
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = ($https ? "https://" : "http://") . $url;
}
return $url;
}
Defined in: yii\helpers\BaseUrl::ensureScheme()
Normalize the URL by ensuring it uses specified scheme.
If the URL is relative or the scheme is not a string, normalization is skipped.
public static string ensureScheme ( $url, $scheme ) | ||
$url | string |
The URL to process |
$scheme | string |
The URI scheme used in the URL (e.g. |
return | string |
The processed URL |
---|
public static function ensureScheme($url, $scheme)
{
if (static::isRelative($url) || !is_string($scheme)) {
return $url;
}
if (strncmp($url, '//', 2) === 0) {
// e.g. //example.com/path/to/resource
return $scheme === '' ? $url : "$scheme:$url";
}
if (($pos = strpos($url, '://')) !== false) {
if ($scheme === '') {
$url = substr($url, $pos + 1);
} else {
$url = $scheme . substr($url, $pos);
}
}
return $url;
}
Defined in: yii\helpers\BaseUrl::getUrlManager()
protected static yii\web\UrlManager getUrlManager ( ) | ||
return | yii\web\UrlManager |
URL manager used to create URLs |
---|
protected static function getUrlManager()
{
return static::$urlManager ?: Yii::$app->getUrlManager();
}
Defined in: yii\helpers\BaseUrl::home()
Returns the home URL.
public static string home ( $scheme = false ) | ||
$scheme | boolean|string |
The URI scheme to use for the returned URL:
|
return | string |
Home URL |
---|
public static function home($scheme = false)
{
$url = Yii::$app->getHomeUrl();
if ($scheme !== false) {
$url = static::getUrlManager()->getHostInfo() . $url;
$url = static::ensureScheme($url, $scheme);
}
return $url;
}
Defined in: yii\helpers\BaseUrl::isRelative()
Returns a value indicating whether a URL is relative.
A relative URL does not have host info part.
public static boolean isRelative ( $url ) | ||
$url | string |
The URL to be checked |
return | boolean |
Whether the URL is relative |
---|
public static function isRelative($url)
{
return strncmp($url, '//', 2) && strpos($url, '://') === false;
}
Defined in: yii\helpers\BaseUrl::normalizeRoute()
Normalizes route and makes it suitable for UrlManager. Absolute routes are staying as is while relative routes are converted to absolute ones.
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 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.
Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias will be converted into the actual route first before conducting the above transformation steps.
protected static string normalizeRoute ( $route ) | ||
$route | string |
The route. This can be either an absolute route or a relative route. |
return | string |
Normalized route suitable for UrlManager |
---|---|---|
throws | yii\base\InvalidArgumentException |
a relative route is given while there is no active controller |
protected static function normalizeRoute($route)
{
$route = Yii::getAlias((string) $route);
if (strncmp($route, '/', 1) === 0) {
// absolute route
return ltrim($route, '/');
}
// relative route
if (Yii::$app->controller === null) {
throw new InvalidArgumentException("Unable to resolve the relative route: $route. No active controller is available.");
}
if (strpos($route, '/') === false) {
// empty or an action ID
return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
}
// relative to module
return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
}
public static string|null previous ( $name = null ) | ||
$name | string|null |
The named associated with the URL that was remembered previously. If not set, yii\web\User::getReturnUrl() will be used to obtain remembered URL. |
return | string|null |
The URL previously remembered. Null is returned if no URL was remembered with the given name
and |
---|
public static function previous($name = null)
{
if ($name === null) {
return Yii::$app->getUser()->getReturnUrl();
}
return Yii::$app->getSession()->get($name);
}
Defined in: yii\helpers\BaseUrl::remember()
Remembers the specified URL so that it can be later fetched back by previous().
See also:
public static void remember ( $url = '', $name = null ) | ||
$url | string|array |
The URL to remember. Please refer to to() for acceptable formats. If this parameter is not specified, the currently requested URL will be used. |
$name | string|null |
The name associated with the URL to be remembered. This can be used later by previous(). If not set, yii\web\User::setReturnUrl() will be used with passed URL. |
public static function remember($url = '', $name = null)
{
$url = static::to($url);
if ($name === null) {
Yii::$app->getUser()->setReturnUrl($url);
} else {
Yii::$app->getSession()->set($name, $url);
}
}
Defined in: yii\helpers\BaseUrl::to()
Creates a URL based on the given parameters.
This method is very similar to toRoute(). The only difference is that this method
requires a route to be specified as an array only. If a string is given, it will be treated as a URL.
In particular, if $url
is
- an array: toRoute() will be called to generate the URL. For example:
['site/index']
,['post/index', 'page' => 2]
. Please refer to toRoute() for more details on how to specify a route. - a string with a leading
@
: it is treated as an alias, and the corresponding aliased string will be returned. - an empty string: the currently requested URL will be returned;
- a normal string: it will be returned as is.
When $scheme
is specified (either a string or true
), an absolute URL with host info (obtained from
yii\web\UrlManager::$hostInfo) will be returned. If $url
is already an absolute URL, its scheme
will be replaced with the specified one.
Below are some examples of using this method:
// /index.php?r=site%2Findex
echo Url::to(['site/index']);
// /index.php?r=site%2Findex&src=ref1#name
echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
// /index.php?r=post%2Findex assume the alias "@posts" is defined as "/post/index"
echo Url::to(['@posts']);
// the currently requested URL
echo Url::to();
// /images/logo.gif
echo Url::to('@web/images/logo.gif');
// images/logo.gif
echo Url::to('images/logo.gif');
// https://www.example.com/images/logo.gif
echo Url::to('@web/images/logo.gif', true);
// https://www.example.com/images/logo.gif
echo Url::to('@web/images/logo.gif', 'https');
// //www.example.com/images/logo.gif
echo Url::to('@web/images/logo.gif', '');
public static string to ( $url = '', $scheme = false ) | ||
$url | array|string |
The parameter to be used to generate a valid URL |
$scheme | boolean|string |
The URI scheme to use in the generated URL:
|
return | string |
The generated URL |
---|---|---|
throws | yii\base\InvalidArgumentException |
a relative route is given while there is no active controller |
public static function to($url = '', $scheme = false)
{
if (is_array($url)) {
return static::toRoute($url, $scheme);
}
$url = Yii::getAlias($url);
if ($url === '') {
$url = Yii::$app->getRequest()->getUrl();
}
if ($scheme === false) {
return $url;
}
if (static::isRelative($url)) {
// turn relative URL into absolute
$url = static::getUrlManager()->getHostInfo() . '/' . ltrim($url, '/');
}
return static::ensureScheme($url, $scheme);
}
Defined in: luya\yii\helpers\Url::toAjax()
Create a link to use when point to an ajax script.
public static string toAjax ( $route, array $params = [] ) | ||
$route | string |
The base routing path defined in yii. module/controller/action |
$params | array |
Optional array containing get parameters with key value pairing |
return | string |
The ajax url link. |
---|
public static function toAjax($route, array $params = [])
{
$routeParams = ['/'.$route];
foreach ($params as $key => $value) {
$routeParams[$key] = $value;
}
return static::toInternal($routeParams, true);
}
Defined in: luya\yii\helpers\Url::toInternal()
This helper method will not concern any context informations
public static string toInternal ( array $routeParams, $scheme = false ) | ||
$routeParams | array |
Example array to route |
$scheme | boolean |
Whether to return the absolute url or not |
return | string |
The created url. |
---|
public static function toInternal(array $routeParams, $scheme = false)
{
/** @var UrlManager $urlManager */
$urlManager = Yii::$app->getUrlManager();
if ($scheme) {
return $urlManager->internalCreateAbsoluteUrl($routeParams);
}
return $urlManager->internalCreateUrl($routeParams);
}
Link to a registered Module.
Its important to know that the moduleName
must be registered in the modules section in your config and also
that a module page is created for this module, the module-block won't work.
If the module could not be found (not registered in the cms) the method returns the provided module name.
If the module is placed several times, it will take the first pick. So ensure to place a module only once and use the module block for more integration use cases.
Read more about [[app-module-urlrules.md]].
See also toModuleRoute().
public static string toModule ( $moduleName, $absolute = false ) | ||
$moduleName | string |
The name of module you'd like to link to. |
$absolute | boolean |
Whether to return an absolute path or not if link is found |
return | string |
Returns the full url to the module, if no module is found, the input $moduleName is retunred. |
---|
public static function toModule($moduleName, $absolute = false)
{
/** @var Item $item */
$item = Yii::$app->menu->find()->where(['module_name' => $moduleName])->with(['hidden'])->one();
if ($item) {
return $absolute ? $item->absoluteLink : $item->link;
}
return $moduleName;
}
Link to a registered Module with custom Route and Params.
In order to link to a Module with a given route (and params) its recommend to generate an URL rule defintion first.
Ensure that the $moduleName exists in the modules list of your config and a Module Page has been created for the given Name, otherwise the CMS does not know where to link.
Assuming the following url rule defintion defined in {{luya\base\Module::$urlRules}}:
public $urlRules = [
['blog/<year:\d{4}>/<month:\d{2}>' => 'blog/default/index'],
];
Now its possible to generate the link with toModuleRoute:
Url::toModuleRoute('blog', ['/blog/default/index', 'year' => 2016, 'month' => '07]);
This generates the following URL, assuming the blog module is located on the CMS page /my-super-blog:
/my-super-blog/2016/07
Keep in mind that the $urlRule must be prefixed with the module name, read more about [[app-module-urlrules.md]].
See also toModule().
public static string toModuleRoute ( $moduleName, array $route, $scheme = false ) | ||
$moduleName | string |
The ID of the module, which should be found inside the nav items. |
$route | string|array |
The route of the module |
$scheme | string |
An optional scheme configuration like |
throws | luya\cms\Exception |
---|
public static function toModuleRoute($moduleName, array $route, $scheme = false)
{
$item = Yii::$app->menu->find()->where(['module_name' => $moduleName])->with(['hidden'])->one();
if ($item) {
return static::toMenuNavItem($item->id, $route, $scheme);
}
throw new Exception("The module route creation could not find the module '$moduleName'. Have you created a page with this module in this language context?");
}
Defined in: yii\helpers\BaseUrl::toRoute()
Creates a URL for the given route.
This method will use yii\web\UrlManager to create a URL.
You may specify the route as a string, e.g., site/index
. You may also use an array
if you want to specify additional query parameters for the URL being created. The
array format must be:
// generates: /index.php?r=site/index¶m1=value1¶m2=value2
['site/index', 'param1' => 'value1', 'param2' => 'value2']
If you want to create a URL with an anchor, you can use the array format with a #
parameter.
For example,
// generates: /index.php?r=site/index¶m1=value1#name
['site/index', 'param1' => 'value1', '#' => 'name']
A route may be either absolute or relative. An absolute route has a leading slash (e.g. /site/index
),
while a relative route has none (e.g. site/index
or index
). A relative route will be converted
into an absolute one by the following rules:
- If the route is an empty string, the current route will be used;
- If the route contains no slashes at all (e.g.
index
), it is considered to be an action ID of the current controller and will be prepended with yii\web\Controller::$uniqueId; - If the route has no leading slash (e.g.
site/index
), it is considered to be a route relative to the current module and will be prepended with the module's uniqueId.
Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias will be converted into the actual route first before conducting the above transformation steps.
Below are some examples of using this method:
// /index.php?r=site%2Findex
echo Url::toRoute('site/index');
// /index.php?r=site%2Findex&src=ref1#name
echo Url::toRoute(['site/index', 'src' => 'ref1', '#' => 'name']);
// https://www.example.com/index.php?r=site%2Findex
echo Url::toRoute('site/index', true);
// https://www.example.com/index.php?r=site%2Findex
echo Url::toRoute('site/index', 'https');
// /index.php?r=post%2Findex assume the alias "@posts" is defined as "post/index"
echo Url::toRoute('@posts');
public static string toRoute ( $route, $scheme = false ) | ||
$route | string|array |
Use a string to represent a route (e.g. |
$scheme | boolean|string |
The URI scheme to use in the generated URL:
|
return | string |
The generated URL |
---|---|---|
throws | yii\base\InvalidArgumentException |
a relative route is given while there is no active controller |
public static function toRoute($route, $scheme = false)
{
$route = (array) $route;
$route[0] = static::normalizeRoute($route[0]);
if ($scheme !== false) {
return static::getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null);
}
return static::getUrlManager()->createUrl($route);
}
Defined in: luya\yii\helpers\Url::trailing()
Add a trailing slash to an url if there is no trailing slash at the end of the url.
public static string trailing ( $url, $slash = '/' ) | ||
$url | string |
The url which a trailing slash should be appended |
$slash | string |
If you want to trail a file on a windows system it gives you the ability to add forward slashes. |
return | string |
The url with added trailing slash, if requred. |
---|
public static function trailing($url, $slash = '/')
{
return rtrim($url, $slash) . $slash;
}