Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
88.24% |
15 / 17 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| LiveReload | |
88.24% |
15 / 17 |
|
50.00% |
1 / 2 |
10.16 | |
0.00% |
0 / 1 |
| url | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 | |||
| withHost | |
83.33% |
10 / 12 |
|
0.00% |
0 / 1 |
6.17 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Util; |
| 6 | |
| 7 | use Celema\Core\Request; |
| 8 | |
| 9 | /** |
| 10 | * The script of celema/server's live reload. The server only sets its URL |
| 11 | * while running with `--watch`, so pages can include it unconditionally. |
| 12 | */ |
| 13 | final class LiveReload |
| 14 | { |
| 15 | /** |
| 16 | * The script URL, or null without a watching dev server. It gets the host |
| 17 | * the page was requested under, so the script also loads on other devices, |
| 18 | * in virtual machines, and under local domain names, as long as the dev |
| 19 | * server listens there. |
| 20 | */ |
| 21 | public static function url(?Request $request): ?string |
| 22 | { |
| 23 | $url = getenv('CELEMA_LIVE_RELOAD'); |
| 24 | |
| 25 | if (!is_string($url) || $url === '') { |
| 26 | return null; |
| 27 | } |
| 28 | |
| 29 | $host = $request?->uri()->getHost() ?? ''; |
| 30 | |
| 31 | return $host === '' ? $url : self::withHost($url, $host); |
| 32 | } |
| 33 | |
| 34 | private static function withHost(string $url, string $host): string |
| 35 | { |
| 36 | $parts = parse_url($url); |
| 37 | |
| 38 | if ($parts === false) { |
| 39 | return $url; |
| 40 | } |
| 41 | |
| 42 | if (str_contains($host, ':') && !str_starts_with($host, '[')) { |
| 43 | $host = "[{$host}]"; |
| 44 | } |
| 45 | |
| 46 | return ( |
| 47 | ($parts['scheme'] ?? 'http') |
| 48 | . "://{$host}" |
| 49 | . (isset($parts['port']) ? ":{$parts['port']}" : '') |
| 50 | . ($parts['path'] ?? '') |
| 51 | . (isset($parts['query']) ? "?{$parts['query']}" : '') |
| 52 | ); |
| 53 | } |
| 54 | } |