1<?php
2
3namespace MediaWiki\Tests\Rest\PathTemplateMatcher;
4
5use MediaWiki\Rest\PathTemplateMatcher\PathConflict;
6use MediaWiki\Rest\PathTemplateMatcher\PathMatcher;
7
8/**
9 * @covers \MediaWiki\Rest\PathTemplateMatcher\PathMatcher
10 * @covers \MediaWiki\Rest\PathTemplateMatcher\PathConflict
11 */
12class PathMatcherTest extends \MediaWikiUnitTestCase {
13	private static $normalRoutes = [
14		'/a/b',
15		'/b/{x}',
16		'/c/{x}/d',
17		'/c/{x}/e',
18		'/c/{x}/{y}/d',
19	];
20
21	public static function provideConflictingRoutes() {
22		return [
23			[ '/a/b', 0, '/a/b' ],
24			[ '/a/{x}', 0, '/a/b' ],
25			[ '/{x}/c', 1, '/b/{x}' ],
26			[ '/b/a', 1, '/b/{x}' ],
27			[ '/b/{x}', 1, '/b/{x}' ],
28			[ '/{x}/{y}/d', 2, '/c/{x}/d' ],
29		];
30	}
31
32	public static function provideMatch() {
33		return [
34			[ '', false ],
35			[ '/a/b', [ 'params' => [], 'userData' => 0 ] ],
36			[ '/b', false ],
37			[ '/b/1', [ 'params' => [ 'x' => '1' ], 'userData' => 1 ] ],
38			[ '/c/1/d', [ 'params' => [ 'x' => '1' ], 'userData' => 2 ] ],
39			[ '/c/1/e', [ 'params' => [ 'x' => '1' ], 'userData' => 3 ] ],
40			[ '/c/000/e', [ 'params' => [ 'x' => '000' ], 'userData' => 3 ] ],
41			[ '/c/1/f', false ],
42			[ '/c//e', [ 'params' => [ 'x' => '' ], 'userData' => 3 ] ],
43			[ '/c///e', false ],
44		];
45	}
46
47	public function createNormalRouter() {
48		$pm = new PathMatcher;
49		foreach ( self::$normalRoutes as $i => $route ) {
50			$pm->add( $route, $i );
51		}
52		return $pm;
53	}
54
55	/** @dataProvider provideConflictingRoutes */
56	public function testAddConflict( $attempt, $expectedUserData, $expectedTemplate ) {
57		$pm = $this->createNormalRouter();
58		$actualTemplate = null;
59		$actualUserData = null;
60		try {
61			$pm->add( $attempt, 'conflict' );
62		} catch ( PathConflict $pc ) {
63			$actualTemplate = $pc->existingTemplate;
64			$actualUserData = $pc->existingUserData;
65		}
66		$this->assertSame( $expectedUserData, $actualUserData );
67		$this->assertSame( $expectedTemplate, $actualTemplate );
68	}
69
70	/** @dataProvider provideMatch */
71	public function testMatch( $path, $expectedResult ) {
72		$pm = $this->createNormalRouter();
73		$result = $pm->match( $path );
74		$this->assertSame( $expectedResult, $result );
75	}
76}
77