<?php
declare(strict_types=1);

namespace App\Security;

final class UrlPolicy
{
    public static function isAllowed(string $url, bool $allowRelative = true): bool
    {
        if ($url === '' || preg_match('/[\x00-\x1F\x7F]/', $url) === 1) return false;
        $url = trim($url);
        if ($url === '' || str_starts_with($url, '//')) return false;
        if ($allowRelative && str_starts_with($url, '/')) return true;
        // Same-origin fragments are safe when the caller permits relative URLs.
        if (str_starts_with($url, '#')) return $allowRelative;
        if (filter_var($url, FILTER_VALIDATE_URL) === false) return false;
        return in_array(strtolower((string) parse_url($url, PHP_URL_SCHEME)), ['http', 'https'], true);
    }

    public static function sanitize(string $url, bool $allowRelative = true): string
    {
        return self::isAllowed($url, $allowRelative) ? trim($url) : '';
    }
}
