Url   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 102
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 0
dl 0
loc 102
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 15 6
A setAttribute() 0 6 1
A getAttribute() 0 4 1
A getSlug() 0 4 1
A getPath() 0 4 1
A getQuery() 0 4 2
A getPathParts() 0 4 1
A getQueryParts() 0 4 1
A getString() 0 4 2
1
<?php
2
3
/**
4
 * @package Cadmium\Framework\Url
5
 * @author Anton Romanov
6
 * @copyright Copyright (c) 2015-2017, Anton Romanov
7
 * @link http://cadmium-cms.com
8
 */
9
10
namespace {
11
12
	class Url {
13
14
		private $path = [], $query = [];
15
16
		/**
17
		 * Constructor
18
		 */
19
20
		public function __construct(string $url = '') {
21
22
			if (false === ($url = parse_url($url))) return;
23
24
			# Parse path
25
26
			if (isset($url['path'])) foreach (explode('/', $url['path']) as $part) {
27
28
				if ('' !== $part) $this->path[] = urldecode($part);
29
			}
30
31
			# Parse query
32
33
			if (isset($url['query'])) parse_str($url['query'], $this->query);
34
		}
35
36
		/**
37
		 * Set a query attribute. If the value is null, an attribute will be removed
38
		 *
39
		 * @return Url : the current url object
40
		 */
41
42
		public function setAttribute(string $name, string $value = null) : Url {
43
44
			$this->query[$name] = $value;
45
46
			return $this;
47
		}
48
49
		/**
50
		* Get a query attribute
51
		*
52
		* @return string|false : the value or false if the attribute does not exist
53
		*/
54
55
		public function getAttribute(string $name) {
56
57
			return ($this->query[$name] ?? false);
58
		}
59
60
		/**
61
		 * Get the slug (a path without leading slash)
62
		 */
63
64
		public function getSlug() : string {
65
66
			return implode('/', array_map('urlencode', $this->path));
67
		}
68
69
		/**
70
		 * Get the url path
71
		 */
72
73
		public function getPath() : string {
74
75
			return ('/' . implode('/', array_map('urlencode', $this->path)));
76
		}
77
78
		/**
79
		 * Get the url query
80
		 */
81
82
		public function getQuery() : string {
83
84
			return (($query = http_build_query($this->query)) ? ('?' . $query) : '');
85
		}
86
87
		/**
88
		 * Get the url path as an array
89
		 */
90
91
		public function getPathParts() : array {
92
93
			return $this->path;
94
		}
95
96
		/**
97
		 * Get the url query as an array
98
		 */
99
100
		public function getQueryParts() : array {
101
102
			return $this->query;
103
		}
104
105
		/**
106
		 * Get the url as a string
107
		 */
108
109
		public function getString(bool $include_query = true) : string {
110
111
			return ($this->getPath() . ($include_query ? $this->getQuery() : ''));
112
		}
113
	}
114
}
115