Skip to content

Commit

Permalink
Added url generator
Browse files Browse the repository at this point in the history
  • Loading branch information
simba77 committed Feb 4, 2024
1 parent 1082c99 commit 105ee60
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
12 changes: 6 additions & 6 deletions system/helpers.php
Expand Up @@ -15,7 +15,7 @@
use JetBrains\PhpStorm\NoReturn;
use Johncms\Container\ContainerFactory;
use Johncms\Http\ResponseFactory;
use Johncms\Router\RouterFactory;
use Johncms\Router\Router;
use Johncms\View\Render;
use Psr\Http\Message\ResponseInterface;

Expand Down Expand Up @@ -187,17 +187,17 @@ function redirect(string $url)
/**
* Build url by route name
*
* @param string $route_name
* @param string $routeName
* @param array $params
* @param array $queryParams
* @return string
*/
function route(string $route_name, array $params = [], array $queryParams = []): string
function route(string $routeName, array $params = [], array $queryParams = []): string
{
$router = di(RouterFactory::class);
$route = $router->getRouter()->getNamedRoute($route_name)->getPath($params);
$router = di(Router::class);
$url = $router->getUrlGenerator()->generate($routeName, $params);
$queryString = http_build_query($queryParams);
return str_replace('//', '/', $route) . (! empty($queryString) ? '?' . $queryString : '');
return str_replace('//', '/', $url) . (! empty($queryString) ? '?' . $queryString : '');
}

/**
Expand Down
12 changes: 12 additions & 0 deletions system/src/Router/Router.php
Expand Up @@ -7,13 +7,16 @@
use Illuminate\Container\Container;
use Johncms\Http\Request;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection as SymfonyRouteCollection;

final class Router
{
private SymfonyRouteCollection $routeCollection;
private UrlGeneratorInterface $urlGenerator;

public function __construct(
private readonly RouteLoader $loader,
Expand All @@ -34,9 +37,18 @@ public function getUrlMatcher(): UrlMatcherInterface
return new UrlMatcher($this->getRouteCollection(), $this->context);
}

/**
* @throws \Throwable
* @throws \JsonException
*/
public function handleRequest(): ResponseInterface
{
$requestHandler = new RequestHandler($this->getUrlMatcher(), $this->container, $this->parametersInjector);
return $requestHandler->handle($this->request);
}

public function getUrlGenerator(): UrlGenerator
{
return $this->urlGenerator ??= new UrlGenerator($this->getRouteCollection(), $this->context);
}
}

0 comments on commit 105ee60

Please sign in to comment.