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 classes |
16
|
|
|
*/ |
17
|
|
|
use InvalidArgumentException; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Import functions |
21
|
|
|
*/ |
22
|
|
|
use function preg_match; |
23
|
|
|
use function preg_replace_callback; |
24
|
|
|
use function sprintf; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Builds the given path with the given attributes |
28
|
|
|
* |
29
|
|
|
* @param string $path |
30
|
|
|
* @param array $attributes |
31
|
|
|
* @param bool $strict |
32
|
|
|
* |
33
|
|
|
* @return string |
34
|
|
|
* |
35
|
|
|
* @throws InvalidArgumentException |
36
|
|
|
*/ |
37
|
|
|
function path_build(string $path, array $attributes = [], bool $strict = false) : string |
38
|
|
|
{ |
39
|
|
|
$regex = '/{([0-9A-Za-z_]+)(?:<([^<#>]+)>)?}/'; |
40
|
|
|
|
41
|
|
|
return preg_replace_callback($regex, function ($match) use ($path, $attributes, $strict) { |
42
|
|
|
if (!isset($attributes[$match[1]])) { |
43
|
|
|
throw new InvalidArgumentException( |
44
|
|
|
sprintf('[%s] missing attribute "%s".', $path, $match[1]) |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$attributes[$match[1]] = (string) $attributes[$match[1]]; |
49
|
|
|
|
50
|
|
|
if ($strict && isset($match[2])) { |
51
|
|
|
if (!preg_match('#' . $match[2] . '#u', $attributes[$match[1]])) { |
52
|
|
|
throw new InvalidArgumentException( |
53
|
|
|
sprintf('[%s] "%s" must match "%s".', $path, $match[1], $match[2]) |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $attributes[$match[1]]; |
59
|
|
|
}, $path); |
60
|
|
|
} |
61
|
|
|
|