2017-08-29 16:21:25 +02:00
|
|
|
<?php
|
|
|
|
|
2018-08-22 03:10:08 +02:00
|
|
|
namespace Engelsystem\Http;
|
2017-08-29 16:21:25 +02:00
|
|
|
|
2018-08-06 12:50:34 +02:00
|
|
|
/**
|
2020-04-07 15:08:49 +02:00
|
|
|
* Provides URLs
|
2019-04-24 11:01:37 +02:00
|
|
|
*
|
2018-08-06 12:50:34 +02:00
|
|
|
* The urls have the form <app url>/<path>?<parameters>
|
|
|
|
*/
|
2018-03-31 05:19:49 +02:00
|
|
|
class UrlGenerator implements UrlGeneratorInterface
|
2017-08-29 16:21:25 +02:00
|
|
|
{
|
|
|
|
/**
|
2020-04-07 15:08:49 +02:00
|
|
|
* Create a URL for the given path, using the applications base url if configured
|
|
|
|
*
|
2017-08-29 16:21:25 +02:00
|
|
|
* @param string $path
|
|
|
|
* @param array $parameters
|
2018-08-06 12:50:34 +02:00
|
|
|
* @return string url in the form [app url]/[path]?[parameters]
|
2017-08-29 16:21:25 +02:00
|
|
|
*/
|
2020-04-07 15:08:49 +02:00
|
|
|
public function to(string $path, array $parameters = []): string
|
2017-08-29 16:21:25 +02:00
|
|
|
{
|
2020-04-07 15:08:49 +02:00
|
|
|
$uri = $path;
|
|
|
|
|
|
|
|
if (!$this->isValidUrl($uri)) {
|
|
|
|
$uri = $this->generateUrl($path);
|
|
|
|
}
|
2017-08-29 16:21:25 +02:00
|
|
|
|
|
|
|
if (!empty($parameters) && is_array($parameters)) {
|
|
|
|
$parameters = http_build_query($parameters);
|
|
|
|
$uri .= '?' . $parameters;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $uri;
|
|
|
|
}
|
2020-04-07 15:08:49 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Check if the URL is valid
|
|
|
|
*
|
|
|
|
* @param string $path
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function isValidUrl(string $path): bool
|
|
|
|
{
|
|
|
|
return preg_match('~^(?:\w+:(//)?|#)~', $path) || filter_var($path, FILTER_VALIDATE_URL) !== false;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Prepend the auto detected or configured app base path and domain
|
|
|
|
*
|
|
|
|
* @param $path
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
protected function generateUrl(string $path): string
|
|
|
|
{
|
|
|
|
$path = '/' . ltrim($path, '/');
|
|
|
|
|
|
|
|
$baseUrl = config('url');
|
|
|
|
if ($baseUrl) {
|
|
|
|
$uri = rtrim($baseUrl, '/') . $path;
|
|
|
|
} else {
|
|
|
|
/** @var Request $request */
|
|
|
|
$request = app('request');
|
|
|
|
$uri = $request->getUriForPath($path);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $uri;
|
|
|
|
}
|
2017-08-29 16:21:25 +02:00
|
|
|
}
|