33 lines
923 B
PHP
33 lines
923 B
PHP
<?php
|
|
|
|
namespace App\Services\Tenant;
|
|
|
|
use InvalidArgumentException;
|
|
|
|
final class DomainNormalizer
|
|
{
|
|
public function normalize(string $value): string
|
|
{
|
|
$value = trim($value);
|
|
|
|
if ($value === '') {
|
|
throw new InvalidArgumentException('A domain is required.');
|
|
}
|
|
|
|
$candidate = str_contains($value, '://') ? $value : 'http://'.$value;
|
|
$host = parse_url($candidate, PHP_URL_HOST);
|
|
|
|
if (! is_string($host) || $host === '' || str_contains($host, '/')) {
|
|
throw new InvalidArgumentException('Enter a valid hostname, such as book.example.com.');
|
|
}
|
|
|
|
$host = strtolower(rtrim($host, '.'));
|
|
|
|
if (strlen($host) > 253 || preg_match('/\s/', $host) || ! preg_match('/^[a-z0-9.-]+$/', $host)) {
|
|
throw new InvalidArgumentException('Enter a valid hostname, such as book.example.com.');
|
|
}
|
|
|
|
return $host;
|
|
}
|
|
}
|