aboutsummaryrefslogtreecommitdiff
path: root/tests/RouteMatcherTest.php
blob: 5181c50a8c6e34362a2d83815b6595a8522a8cec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

declare(strict_types=1);

namespace BrettParson\MiniRoute\Tests;

use BrettParson\MiniRoute\Routing\RouteDef;
use BrettParson\MiniRoute\Routing\RouteMatcher;
use PHPUnit\Framework\TestCase;

final class RouteMatcherTest extends TestCase
{
    private RouteMatcher $matcher;

    protected function setUp(): void
    {
        $this->matcher = new RouteMatcher();
    }

    private function route(string $method, string $path): RouteDef
    {
        return new RouteDef($method, $path, 'C', 'm');
    }

    public function testMatchesExactPath(): void
    {
        $route = $this->route('GET', '/entries');

        $this->assertTrue($this->matcher->matches($route, 'get', '/entries'));
        $this->assertFalse($this->matcher->matches($route, 'POST', '/entries'));
        $this->assertFalse($this->matcher->matches($route, 'GET', '/entries/1'));
    }

    public function testMatchesParameterizedPath(): void
    {
        $route = $this->route('GET', '/entries/{slug}');

        $this->assertTrue($this->matcher->matches($route, 'GET', '/entries/hello-world'));
        $this->assertFalse($this->matcher->matches($route, 'GET', '/entries/hello/world'));
    }

    public function testExtractsNamedParameters(): void
    {
        $route = $this->route('GET', '/entries/{slug}');

        $this->assertSame(
            ['slug' => 'hello-world'],
            $this->matcher->extractParams($route, '/entries/hello-world'),
        );
    }

    public function testLiteralBeatsParameter(): void
    {
        $literal = $this->route('GET', '/entries/archive');
        $param = $this->route('GET', '/entries/{slug}');

        $this->assertLessThan(0, $this->matcher->compare($literal, $param));
        $this->assertGreaterThan(0, $this->matcher->compare($param, $literal));
    }

    public function testExactBeatsParameterAtSamePosition(): void
    {
        $exact = $this->route('POST', '/admin/entries/preview');
        $param = $this->route('POST', '/admin/entries/{id}');

        $this->assertLessThan(0, $this->matcher->compare($exact, $param));
    }
}