-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathUrl.php
43 lines (35 loc) · 1.07 KB
/
Url.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
namespace MiladRahimi\PhpRouter;
use MiladRahimi\PhpRouter\Exceptions\UndefinedRouteException;
use MiladRahimi\PhpRouter\Routing\Repository;
/**
* It generates URLs by name based on the defined routes
*/
class Url
{
private Repository $repository;
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
/**
* Generate (make) URL by name based on the defined routes
*
* @param string $name
* @param string[] $parameters
* @return string
* @throws UndefinedRouteException
*/
public function make(string $name, array $parameters = []): string
{
if (!($route = $this->repository->findByName($name))) {
throw new UndefinedRouteException("There is no route named `$name`.");
}
$uri = $route->getPath();
foreach ($parameters as $key => $value) {
$uri = preg_replace('/\??{' . $key . '\??}/', $value, $uri);
}
$uri = preg_replace('/{[^}]+\?}/', '', $uri);
return str_replace('/?', '', $uri);
}
}