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 sprintf; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Builds the given path using the given attributes |
27
|
|
|
* |
28
|
|
|
* If strict mode is enabled, each attribute value will be validated. |
29
|
|
|
* |
30
|
|
|
* @param string $path |
31
|
|
|
* @param array $attributes |
32
|
|
|
* @param bool $strict |
33
|
|
|
* |
34
|
|
|
* @return string |
35
|
|
|
* |
36
|
|
|
* @throws InvalidArgumentException |
37
|
|
|
*/ |
38
|
|
|
function path_build(string $path, array $attributes = [], bool $strict = false) : string |
39
|
|
|
{ |
40
|
|
|
$matches = path_parse($path); |
41
|
|
|
|
42
|
|
|
foreach ($matches as $match) { |
43
|
|
|
if (!isset($attributes[$match['name']])) { |
44
|
|
|
if (!$match['isOptional']) { |
45
|
|
|
throw new InvalidArgumentException( |
46
|
|
|
sprintf('[%s] missing attribute "%s".', $path, $match['name']) |
47
|
|
|
); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$path = str_replace($match['withParentheses'], '', $path); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$attributes[$match['name']] = (string) $attributes[$match['name']]; |
54
|
|
|
|
55
|
|
|
if ($strict && isset($match['pattern'])) { |
56
|
|
|
if (!preg_match('#' . $match['pattern'] . '#u', $attributes[$match['name']])) { |
57
|
|
|
throw new InvalidArgumentException( |
58
|
|
|
sprintf('[%s] "%s" must match "%s".', $path, $match['name'], $match['pattern']) |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$path = str_replace($match['raw'], $attributes[$match['name']], $path); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$path = str_replace(['(', ')'], '', $path); |
67
|
|
|
|
68
|
|
|
return $path; |
69
|
|
|
} |
70
|
|
|
|