1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* URL |
5
|
|
|
* |
6
|
|
|
* Helper object for handling URLs |
7
|
|
|
* |
8
|
|
|
* @package core |
9
|
|
|
* @author [email protected] |
10
|
|
|
* @copyright Caffeina srl - 2016 - http://caffeina.com |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
class URL { |
|
|
|
|
14
|
|
|
|
15
|
|
|
private $_origin = '', |
|
|
|
|
16
|
|
|
$_parsed = false, |
17
|
|
|
$scheme = false, |
18
|
|
|
$user = false, |
19
|
|
|
$pass = false, |
20
|
|
|
$host = false, |
21
|
|
|
$port = false, |
22
|
|
|
$path = false, |
23
|
|
|
$query = [], |
24
|
|
|
$fragment = false; |
25
|
|
|
|
26
|
|
|
public function __construct($url=''){ |
27
|
|
|
if (empty($url) || !is_string($url)) return; |
28
|
|
|
$this->_origin = $url; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
private function parse(){ |
32
|
|
|
$url = $this->_origin; |
33
|
|
|
$tmp_url = (strpos($url, '://') === false) ? "..N..://$url" : $url; |
34
|
|
|
if (mb_detect_encoding($tmp_url, 'UTF-8', true) || ($parsed = parse_url($tmp_url)) === false) { |
35
|
|
|
preg_match('(^((?P<scheme>[^:/?#]+):(//))?((\\3|//)?(?:(?P<user>[^:]+):(?P<pass>[^@]+)@)?(?P<host>[^/?:#]*))(:(?P<port>\\d+))?(?P<path>[^?#]*)(\\?(?P<query>[^#]*))?(#(?P<fragment>.*))?)u', $tmp_url, $parsed); |
36
|
|
|
} |
37
|
|
|
foreach($parsed as $k => $v) if(isset($this->$k)) $this->$k = $v; |
38
|
|
|
if ($this->scheme == '..N..') $this->scheme = null; |
39
|
|
|
if (!empty($this->query)) { |
40
|
|
|
parse_str($this->query, $this->query); |
41
|
|
|
} |
42
|
|
|
$this->_parsed = true; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function & __get($name){ |
46
|
|
|
$this->_parsed || $this->parse(); |
47
|
|
|
if (isset($this->$name)) return $this->$name; |
48
|
|
|
else throw new Exception('Trying to read an unknown URL property'); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function __set($name, $value){ |
52
|
|
|
$this->_parsed || $this->parse(); |
53
|
|
|
return $this->$name = $value; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function __toString(){ |
57
|
|
|
if ($this->_parsed) { |
58
|
|
|
$d = []; |
59
|
|
|
if ($this->scheme) $d[] = "{$this->scheme}://"; |
60
|
|
|
if ($this->user) $d[] = "{$this->user}" . (empty($this->pass)?'':":{$this->pass}") . "@"; |
61
|
|
|
if ($this->host) $d[] = "{$this->host}"; |
62
|
|
|
if ($this->port) $d[] = ":{$this->port}"; |
63
|
|
|
if ($this->path) $d[] = "/" . ltrim($this->path,"/"); |
64
|
|
|
if (!empty($this->query)) $d[] = "?" . http_build_query($this->query); |
65
|
|
|
if ($this->fragment) $d[] = "#{$this->fragment}"; |
66
|
|
|
return implode('', $d); |
67
|
|
|
} else { |
68
|
|
|
return $this->_origin; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
} /* End of class */ |
73
|
|
|
|
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.