BKF
BKF

Reputation: 1366

Laravel 9: How to extend UrlGenerator core class

I'm trying to extend the UrlGenerator class in order to add a custom temporaryTenantSignedRoute and then use it like this :

Url::temporaryTenantSignedRoute(...)

So, I've created a class CustomUrlGenerator :

<?php

namespace Domain\Shared\Support;

use Illuminate\Support\Arr;
use Illuminate\Routing\UrlGenerator;

class CustomUrlGenerator extends UrlGenerator
{ 
    public function temporaryTenantSignedRoute($name, $expiration, $parameters = [], $absolute = true)
    {
         return $this->tenantSignedRoute($name, $parameters, $expiration, $absolute);
    }   

    public function tenantSignedRoute($name, $parameters = [], $expiration = null, $absolute = true)
    {
        $this->ensureSignedRouteParametersAreNotReserved(
            $parameters = Arr::wrap($parameters)
        );

        if ($expiration) {
            $parameters = $parameters + ['expires' => $this->availableAt($expiration)];
        }

        ksort($parameters);

        $key = call_user_func($this->keyResolver);

        return tenant_route(tenant()->domain, $name, $parameters + [
            'signature' => hash_hmac('sha256', tenant_route(tenant()->domain, $name, $parameters, $absolute), $key),
        ], $absolute);
    }
}

And I've registered it in AppServiceProvider like this :

 $this->app->bind(UrlGenerator::class, CustomUrlGenerator::class);

But it does not work ! Any help please? thanks

Upvotes: 2

Views: 546

Answers (1)

Norman Huth
Norman Huth

Reputation: 570

Works for me

$this->app->extend('url', function (\Illuminate\Routing\UrlGenerator $urlGenerator) {
    return new \App\Helpers\UrlGenerator(
        $this->app->make('router')->getRoutes(),
        $urlGenerator->getRequest(),
        $this->app->make('config')->get('app.asset_url')
    );
});

Upvotes: 2

Related Questions