|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace JsonSchema\Tool\Validator; |
| 6 | + |
| 7 | +class UriValidator |
| 8 | +{ |
| 9 | + public static function isValid(string $uri): bool |
| 10 | + { |
| 11 | + // RFC 3986: Hierarchical URIs (http, https, ftp, etc.) |
| 12 | + $hierarchicalPattern = '/^ |
| 13 | + ([a-z][a-z0-9+\-.]*):\/\/ # Scheme (http, https, ftp, etc.) |
| 14 | + (?:([^:@\/?#]+)(?::([^@\/?#]*))?@)? # Optional userinfo (user:pass@) |
| 15 | + ([a-z0-9.-]+|\[[a-f0-9:.]+\]) # Hostname or IPv6 in brackets |
| 16 | + (?::(\d{1,5}))? # Optional port |
| 17 | + (\/[a-zA-Z0-9._~!$&\'()*+,;=:@\/%-]*)* # Path (valid characters only) |
| 18 | + (\?([^#]*))? # Optional query |
| 19 | + (\#(.*))? # Optional fragment |
| 20 | + $/ix'; |
| 21 | + |
| 22 | + // RFC 3986: Non-Hierarchical URIs (mailto, data, urn) |
| 23 | + $nonHierarchicalPattern = '/^ |
| 24 | + (mailto|data|urn): # Only allow known non-hierarchical schemes |
| 25 | + (.+) # Must contain at least one character after scheme |
| 26 | + $/ix'; |
| 27 | + |
| 28 | + // RFC 5322-compliant email validation for `mailto:` URIs |
| 29 | + $emailPattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'; |
| 30 | + |
| 31 | + // First, check if it's a valid hierarchical URI |
| 32 | + if (preg_match($hierarchicalPattern, $uri, $matches) === 1) { |
| 33 | + // Validate domain name (no double dots like example..com) |
| 34 | + if (!empty($matches[4]) && preg_match('/\.\./', $matches[4])) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + // Validate port (should be between 1 and 65535 if specified) |
| 39 | + if (!empty($matches[5]) && ($matches[5] < 1 || $matches[5] > 65535)) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + // Validate path (reject illegal characters: < > { } | \ ^ `) |
| 44 | + if (!empty($matches[6]) && preg_match('/[<>{}|\\\^`]/', $matches[6])) { |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | + return true; |
| 49 | + } |
| 50 | + |
| 51 | + // If not hierarchical, check non-hierarchical URIs |
| 52 | + if (preg_match($nonHierarchicalPattern, $uri, $matches) === 1) { |
| 53 | + $scheme = strtolower($matches[1]); // Extract the scheme |
| 54 | + |
| 55 | + // Special case: `mailto:` must contain a **valid email address** |
| 56 | + if ($scheme === 'mailto') { |
| 57 | + return preg_match($emailPattern, $matches[2]) === 1; |
| 58 | + } |
| 59 | + |
| 60 | + return true; // Valid non-hierarchical URI |
| 61 | + } |
| 62 | + |
| 63 | + return false; |
| 64 | + } |
| 65 | +} |
0 commit comments