Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| UrlGenerator | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
8 | |
100.00% |
1 / 1 |
| to | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
4 | |||
| isValidUrl | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| generateUrl | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Engelsystem\Http; |
| 6 | |
| 7 | /** |
| 8 | * Provides URLs |
| 9 | * |
| 10 | * The urls have the form <app url>/<path>?<parameters> |
| 11 | */ |
| 12 | class UrlGenerator implements UrlGeneratorInterface |
| 13 | { |
| 14 | /** |
| 15 | * Create a URL for the given path, using the applications base url if configured |
| 16 | * |
| 17 | * @return string url in the form [app url]/[path]?[parameters] |
| 18 | */ |
| 19 | public function to(string $path, array $parameters = []): string |
| 20 | { |
| 21 | $uri = $path; |
| 22 | |
| 23 | if (!$this->isValidUrl($uri)) { |
| 24 | $uri = $this->generateUrl($path); |
| 25 | } |
| 26 | |
| 27 | if (!empty($parameters) && is_array($parameters)) { |
| 28 | $parameters = http_build_query($parameters); |
| 29 | $uri .= '?' . $parameters; |
| 30 | } |
| 31 | |
| 32 | return $uri; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Check if the URL is valid |
| 37 | */ |
| 38 | public function isValidUrl(string $path): bool |
| 39 | { |
| 40 | return preg_match('~^(?:\w+:(//)?|#)~', $path) || filter_var($path, FILTER_VALIDATE_URL) !== false; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Prepend the auto-detected or configured app base path and domain |
| 45 | */ |
| 46 | protected function generateUrl(string $path): string |
| 47 | { |
| 48 | $path = '/' . ltrim($path, '/'); |
| 49 | |
| 50 | $baseUrl = config('url'); |
| 51 | if ($baseUrl) { |
| 52 | $uri = rtrim($baseUrl, '/') . $path; |
| 53 | } else { |
| 54 | /** @var Request $request */ |
| 55 | $request = app('request'); |
| 56 | $uri = $request->getUriForPath($path); |
| 57 | } |
| 58 | |
| 59 | return $uri; |
| 60 | } |
| 61 | } |