Skip to content

Commit

Permalink
Merge pull request #967 from spiral/hotfix/route-prefix
Browse files Browse the repository at this point in the history
Fixes incorrect Concatenation of Route Pattern with Prefix in Route Group
  • Loading branch information
butschster authored Aug 16, 2023
2 parents d7c8048 + ce47614 commit 5e483c4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Router/src/UriHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,11 @@ private function compile(): void

$options = [];
$replaces = [];
$pattern = \rtrim(\ltrim($this->getPrefix() . '/' . $this->pattern, ':/'), '/');

$prefix = \rtrim($this->getPrefix(), '/ ');
$pattern = \ltrim($this->pattern, '/ ');
$pattern = $prefix . '/' . $pattern;
$pattern = \rtrim(\ltrim($pattern, ':/'), '/');

// correct [/ first occurrence]
if (\str_starts_with($pattern, '[/')) {
Expand Down
32 changes: 32 additions & 0 deletions src/Router/tests/RouteGroupTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Spiral\Tests\Router;

use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7\ServerRequest;
use PHPUnit\Framework\Attributes\DataProvider;
use Psr\Http\Message\UriFactoryInterface;
use Spiral\Core\Container;
Expand All @@ -19,6 +20,7 @@

final class RouteGroupTest extends BaseTestCase
{

protected function setUp(): void
{
parent::setUp();
Expand Down Expand Up @@ -134,6 +136,36 @@ public function testWithNamePrefix(): void
$this->assertFalse($group->hasRoute('name'));
}

#[DataProvider('routePrefixDataProvider')]
public function testWithPrefix(string $prefix, string $pattern): void
{
$route = new Route($pattern, new Action('controller', 'method'));
$group = new RouteGroup();
$group->setPrefix($prefix);
$group->addRoute('name', $route->withVerbs('GET'));
$group->register($this->router, $this->container);

$route = $this->router->getRoute('name');
$this->assertNotNull(
$route->match(new ServerRequest('GET', '/api/blog'))
);

$this->assertSame('/api/blog', (string) $route->uri());
}

public static function routePrefixDataProvider(): iterable
{
yield ['/api/', '/blog'];
yield ['/api', '/blog'];
yield ['/api', 'blog'];
yield ['api/', '/blog'];
yield ['api', '/blog'];
yield ['api', 'blog'];
yield ['api/', '/blog/'];
yield ['api', '/blog/'];
yield ['api', 'blog/'];
}

/**
* @throws \ReflectionException
*/
Expand Down

0 comments on commit 5e483c4

Please sign in to comment.