depage-forms v1.4.1
html forms made easy
Loading...
Searching...
No Matches
Validators/Url.php
Go to the documentation of this file.
1<?php
2
7
8namespace Depage\HtmlForm\Validators;
9
13class Url extends Validator
14{
22 public function validate($url, $parameters = []): bool
23 {
24 return (bool) filter_var(self::normalizeUrl($url), FILTER_VALIDATE_URL);
25 }
26
33 public static function normalizeUrl($url): string
34 {
35 $info = parse_url(trim($url));
36
37 $scheme = isset($info['scheme']) ? $info['scheme'] . '://' : '';
38 $host = $info['host'] ?? '';
39 $host = idn_to_ascii($host);
40 $port = isset($info['port']) ? ':' . $info['port'] : '';
41 $user = isset($info['user']) ? rawurlencode($info['user']) : '';
42 $pass = isset($info['pass']) ? ':' . rawurlencode($info['pass']) : '';
43 $pass = ($user || $pass) ? "$pass@" : '';
44 $path = $info['path'] ?? '';
45 $query = isset($info['query']) ? '?' . $info['query'] : '';
46 $fragment = isset($info['fragment']) ? '#' . $info['fragment'] : '';
47
48
49 $encodedPath = implode('/', array_map('Depage\HtmlForm\Validators\Url::encodeUrlPath', explode('/', $path)));
50
51 return "$scheme$user$pass$host$port$encodedPath$query$fragment";
52 }
53
60 public static function humanReadableUrl($url): string
61 {
62 $info = parse_url(trim($url));
63
64 $scheme = isset($info['scheme']) ? $info['scheme'] . '://' : '';
65 $host = $info['host'] ?? '';
66 $host = idn_to_utf8($host);
67 $port = isset($info['port']) ? ':' . $info['port'] : '';
68 $user = isset($info['user']) ? rawurldecode($info['user']) : '';
69 $pass = isset($info['pass']) ? ':' . rawurldecode($info['pass']) : '';
70 $pass = ($user || $pass) ? "$pass@" : '';
71 $path = $info['path'] ?? '';
72 $query = isset($info['query']) ? '?' . rawurldecode($info['query']) : '';
73 $fragment = isset($info['fragment']) ? '#' . rawurldecode($info['fragment']) : '';
74
75 return "$scheme$user$pass$host$port$path$query$fragment";
76 }
77
85 protected static function encodeUrlPath($path): string
86 {
87 if (rawurlencode($path) != str_replace(['%','+'], ['%25','%2B'], $path)) {
88 $path = rawurlencode($path);
89 }
90
91 return $path;
92 }
93}
default validator for url input elements
static normalizeUrl($url)
normalizes url
static humanReadableUrl($url)
changes encoded url to a human readable format
validate($url, $parameters=[])
url validator
static encodeUrlPath($path)
Encodes the path of an URL.