UrlManager rules with hyphen as a delimiter

Hi All,
I’m trying to minimaize the number of UrlManager rules to make the application work faster. There are couple of very similar rules and I’m wondering whether it’s possible to combine them into one.

I’d like to handle creation of these cases:

news-1
news-1-foo-bar
news-1-foo-bar/3
news-1/3

So in general the url should be in a form similar to this:
news-<id:\d+>-<name:\w+>/<page:\d+>

id is mandatory, name and page optionals. As you can see the main difference between this case and “standard” one is that for some part of the url I need to use hyphens as a delimiter.

I’ve tried different regexps with “defaults” values - no luck, so I’m just thinking if it’s possible to handle such scenario using default UrlManager and UrlRule implementation?

Cheers

I’d leave that as two rules:

news-<id:\d+>-<name:\w+>/<page:\d+>
news-<id:\d+>-<name:\w+>

Thanks for the comment, seems that I can use one rule to handle all cases:

[
    'pattern' => 'news-<id:\d+>-<name:.+>/<page:\d+>',
    'route' => 'news/view',
    'defaults' => ['name' => '', 'page' => ''],
]

The only problem is that the created urls have hyphens at the end:

ID: /news-1-
ID, NAME: /news-1-foobar
ID, PAGE: /news-1-/7
ID, NAME, PAGE: /news-1-foobar/7

But this can be solved with custom UrlRule class:

[
    'class' => 'app\components\UrlRule',
    'pattern' => 'news-<id:\d+>-<name:.+>/<page:\d+>',
    'route' => 'news/view',
    'defaults' => ['name' => '', 'page' => ''],
]
namespace app\components;

class UrlRule extends \yii\web\UrlRule
{
    public function createUrl($manager, $route, $params)
    {
        $url = parent::createUrl($manager, $route, $params);
        if ($this->createStatus === self::CREATE_STATUS_SUCCESS) {
            $url = str_replace('-/', '/', rtrim($url, '-'));
        }
        return $url;
    }
}

Should be fine.

Cheers