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 if (empty($url)) {
36 return "";
37 }
38
39 $info = parse_url(trim($url));
40
41 $scheme = isset($info['scheme']) ? $info['scheme'] . '://' : '';
42 $host = $info['host'] ?? '';
43 if (!empty($host)) {
44 $host = idn_to_ascii($host);
45 }
46 $port = isset($info['port']) ? ':' . $info['port'] : '';
47 $user = isset($info['user']) ? rawurlencode($info['user']) : '';
48 $pass = isset($info['pass']) ? ':' . rawurlencode($info['pass']) : '';
49 $pass = ($user || $pass) ? "$pass@" : '';
50 $path = $info['path'] ?? '';
51 $query = isset($info['query']) ? '?' . $info['query'] : '';
52 $fragment = isset($info['fragment']) ? '#' . $info['fragment'] : '';
53
54
55 $encodedPath = implode('/', array_map('Depage\HtmlForm\Validators\Url::encodeUrlPath', explode('/', $path)));
56
57 return "$scheme$user$pass$host$port$encodedPath$query$fragment";
58 }
59
66 public static function humanReadableUrl($url): string
67 {
68 if (empty($url)) {
69 return "";
70 }
71 $info = parse_url(trim($url));
72
73 $scheme = isset($info['scheme']) ? $info['scheme'] . '://' : '';
74 $host = $info['host'] ?? '';
75 if (!empty($host)) {
76 $host = idn_to_utf8($host);
77 }
78 $port = isset($info['port']) ? ':' . $info['port'] : '';
79 $user = isset($info['user']) ? rawurldecode($info['user']) : '';
80 $pass = isset($info['pass']) ? ':' . rawurldecode($info['pass']) : '';
81 $pass = ($user || $pass) ? "$pass@" : '';
82 $path = $info['path'] ?? '';
83 $query = isset($info['query']) ? '?' . rawurldecode($info['query']) : '';
84 $fragment = isset($info['fragment']) ? '#' . rawurldecode($info['fragment']) : '';
85
86 return "$scheme$user$pass$host$port$path$query$fragment";
87 }
88
96 protected static function encodeUrlPath($path): string
97 {
98 if (rawurlencode($path) != str_replace(['%','+'], ['%25','%2B'], $path)) {
99 $path = rawurlencode($path);
100 }
101
102 return $path;
103 }
104}
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.