URL   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 26
lcom 1
cbo 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 3
B parse() 0 13 8
A __get() 0 5 3
A __set() 0 4 2
C __toString() 0 15 10
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