Url::make()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 14
rs 10
1
<?php
2
3
namespace MiladRahimi\PhpRouter;
4
5
use MiladRahimi\PhpRouter\Exceptions\UndefinedRouteException;
6
use MiladRahimi\PhpRouter\Routing\Repository;
7
8
/**
9
 * It generates URLs by name based on the defined routes
10
 */
11
class Url
12
{
13
    private Repository $repository;
14
15
    public function __construct(Repository $repository)
16
    {
17
        $this->repository = $repository;
18
    }
19
20
    /**
21
     * Generate (make) URL by name based on the defined routes
22
     *
23
     * @param string $name
24
     * @param string[] $parameters
25
     * @return string
26
     * @throws UndefinedRouteException
27
     */
28
    public function make(string $name, array $parameters = []): string
29
    {
30
        if (!($route = $this->repository->findByName($name))) {
31
            throw new UndefinedRouteException("There is no route named `$name`.");
32
        }
33
34
        $uri = $route->getPath();
35
36
        foreach ($parameters as $key => $value) {
37
            $uri = preg_replace('/\??{' . $key . '\??}/', $value, $uri);
38
        }
39
40
        $uri = preg_replace('/{[^}]+\?}/', '', $uri);
41
        return str_replace('/?', '', $uri);
42
    }
43
}
44