Passed
Branch release/v2.0.0 (67ff9b)
by Anatoly
04:01
created

path_regex()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 4
nop 1
dl 0
loc 20
rs 9.9
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Fenric <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Fenric
8
 * @license https://github.com/sunrise-php/http-router/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-router
10
 */
11
12
namespace Sunrise\Http\Router;
13
14
/**
15
 * Import functions
16
 */
17
use function addcslashes;
18
use function str_replace;
19
20
/**
21
 * Converts the given path to Regular Expression
22
 *
23
 * @param string $path
24
 * @return string
25
 *
26
 * @link https://www.php.net/manual/en/regexp.reference.meta.php
27
 * @link https://www.php.net/manual/en/regexp.reference.subpatterns.php
28
 */
29
function path_regex(string $path) : string
30
{
31
    $matches = path_parse($path);
32
33
    foreach ($matches as $match) {
34
        $path = str_replace($match['raw'], '{' . $match['name'] . '}', $path);
35
    }
36
37
    $path = addcslashes($path, '#$*+-.?[\]^|');
38
39
    $path = str_replace(['(', ')'], ['(?:', ')?'], $path);
40
41
    foreach ($matches as $match) {
42
        $subpattern = '(?<' . $match['name'] . '>' . ($match['pattern'] ?: '[^/]+') . ')';
43
44
        $path = str_replace('{' . $match['name'] . '}', $subpattern, $path);
45
    }
46
47
    return '#^' . $path . '$#uD';
48
}
49