Cleaner way to build ugly URLs

This commit is contained in:
Pierre Rudloff 2020-10-22 01:20:43 +02:00
parent 7d856c61fb
commit d97b824a44
1 changed files with 11 additions and 7 deletions

View File

@ -9,6 +9,7 @@ namespace Alltube;
use InvalidArgumentException; use InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use RuntimeException; use RuntimeException;
use Slim\Http\Uri;
use Slim\Router; use Slim\Router;
/** /**
@ -27,15 +28,17 @@ class UglyRouter extends Router
*/ */
public function dispatch(ServerRequestInterface $request) public function dispatch(ServerRequestInterface $request)
{ {
parse_str($request->getUri()->getQuery(), $args); $params = $request->getQueryParams();
$uri = '/'; $uri = new Uri('', '');
if (isset($args['page'])) {
$uri .= $args['page']; if (isset($params['page'])) {
// Build an URI that the router can understand.
$uri = $uri->withPath($params['page']);
} }
return $this->createDispatcher()->dispatch( return $this->createDispatcher()->dispatch(
$request->getMethod(), $request->getMethod(),
$uri (string) $uri
); );
} }
@ -52,10 +55,11 @@ class UglyRouter extends Router
*/ */
public function pathFor($name, array $data = [], array $queryParams = []) public function pathFor($name, array $data = [], array $queryParams = [])
{ {
$url = str_replace('/', '/?page=', $this->relativePathFor($name, $data, $queryParams)); $queryParams['page'] = $name;
$url = Uri::createFromString($this->relativePathFor($name, $data, $queryParams))->withPath('');
if ($this->basePath) { if ($this->basePath) {
$url = $this->basePath . $url; $url = $url->withBasePath($this->basePath);
} }
return $url; return $url;