| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- <?php
- declare(strict_types=1);
- namespace App\Service\Utils;
- /**
- * Building url utilities.
- */
- class UrlBuilder
- {
- public function __construct(private string $baseUrl)
- {
- }
- /**
- * Concatenate a base url and a path.
- *
- * @param string $base The base url
- * @param array<string> $tails La suite de l'URL sous forme de tableau
- */
- public static function concatPath(string $base, array $tails): string
- {
- $url = $base;
- foreach ($tails as $tail) {
- $url = rtrim($url, '/').'/'.ltrim(strval($tail), '/');
- }
- return $url;
- }
- /**
- * Concatenate an url and a list of parameters.
- *
- * @param list<string|int> $parameters
- */
- public static function concatParameters(string $url, array $parameters = []): string
- {
- if (!$parameters) {
- return $url;
- }
- $url = rtrim($url, '?&/');
- $query = implode(
- '&',
- array_map(
- static function ($k, $v = '') {
- $q = urlencode((string) $k);
- if ((string) $v) {
- $q .= '='.urlencode((string) $v);
- }
- return $q;
- },
- array_keys($parameters),
- array_values($parameters)
- )
- );
- return $url.(str_contains($url, '?') ? '&' : '?').$query;
- }
- /**
- * Prepend the 'https://' part if neither 'http://' of 'https://' is present, else: does nothing.
- */
- public static function prependHttps(string $url): string
- {
- if (!preg_match('/^https?:\/\/.*/', $url)) {
- $url = 'https://'.$url;
- }
- return $url;
- }
- /**
- * Build an url.
- *
- * @param string $url The base url
- * @param array<string> $tails la suite de l'url sous forme de tableau
- * @param list<string> $parameters A list of parameters (can be an empty array)
- * @param bool $preprendHttps Should the 'https://' be prepended if missing
- */
- public static function concat(string $url, array $tails, array $parameters = [], bool $preprendHttps = false): string
- {
- $url = self::concatParameters(self::concatPath($url, $tails), $parameters);
- if ($preprendHttps) {
- $url = self::prependHttps($url);
- }
- return $url;
- }
- /**
- * Retourne l'URL relative sans le scheme et l'host.
- */
- public function getRelativeUrl(string $url): string
- {
- $parts = parse_url($url);
- return ($parts['path'] ?? '').(isset($parts['query']) ? '?'.$parts['query'] : '');
- }
- /**
- * Retourne l'URL absolue avec le scheme et l'host.
- */
- public function getAbsoluteUrl(string $path): string
- {
- return self::concat($this->baseUrl, [$path]);
- }
- }
|