Passed
Branch release/v2.0.0 (caca50)
by Anatoly
02:02
created

path_build()   A

Complexity

Conditions 5
Paths 1

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 23
rs 9.5555
cc 5
nc 1
nop 3
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