Passed
Branch v1.5.1 (4f5540)
by Wanderson
05:07
created

Url::setSuffix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Win\Request;
4
5
use Win\Common\Traits\SingletonTrait;
6
7
/**
8
 * Manipulador de URLs
9
 */
10
class Url
11
{
12
	use SingletonTrait;
13
14
	const HOME = ['index', 'index'];
15
	public $suffix = '/';
16
17
	protected $base = null;
18
	protected $url = null;
19
	protected $protocol = null;
20
	protected $segments = null;
21
22
	/**
23
	 * Retorna no formato de URL
24
	 * @param string $url
25
	 * @return string
26
	 */
27
	public function format($url)
28
	{
29
		return rtrim($url, $this->suffix) . $this->suffix;
30
	}
31
32
	/**
33
	 * Redireciona para a URL escolhida
34
	 * @param string $url URL relativa ou absoluta
35
	 * @codeCoverageIgnore
36
	 */
37
	public function redirect($url = '')
38
	{
39
		if (false === strpos($url, '://')) {
40
			$url = $this->getBaseUrl() . $url;
41
		}
42
		header('location:' . $url);
43
		die();
44
	}
45
46
	/**
47
	 * Retorna a URL base
48
	 * @return string
49
	 */
50
	public function getBaseUrl()
51
	{
52
		if (is_null($this->base)) {
53
			$protocol = $this->getProtocol();
54
			$host = Input::server('HTTP_HOST');
55
			$script = Input::server('SCRIPT_NAME');
56
			$basePath = preg_replace('@/+$@', '', dirname($script)) . '/';
57
			$this->base = $protocol . '://' . $host . $basePath;
58
		}
59
60
		return $this->base;
61
	}
62
63
	/**
64
	 * Retorna o protocolo atual
65
	 * @return string (http|https)
66
	 */
67
	public function getProtocol()
68
	{
69
		if (is_null($this->protocol)) {
70
			$this->protocol = Input::protocol();
71
		}
72
73
		return $this->protocol;
74
	}
75
76
	/**
77
	 * Retorna a URL atual
78
	 * @return string
79
	 */
80
	public function getUrl()
81
	{
82
		if (is_null($this->url)) {
83
			$host = Input::server('HTTP_HOST');
84
			$url = '';
85
			if ($host) {
86
				$requestUri = explode('?', Input::server('REQUEST_URI'));
87
				$context = explode($host, $this->getBaseUrl());
88
				$uri = (explode(end($context), $requestUri[0], 2));
89
				$url = end($uri);
90
			}
91
			$this->url = $this->format($url);
92
		}
93
94
		return $this->url;
95
	}
96
97
	/**
98
	 * @param string $url
99
	 */
100
	public function setUrl($url)
101
	{
102
		$this->url = $this->format($url);
103
		$this->segments = null;
104
	}
105
106
	/**
107
	 * Retorna o array de fragmentos da URL
108
	 * @return string[]
109
	 */
110
	public function getSegments()
111
	{
112
		if (is_null($this->segments)) {
113
			$url = rtrim($this->getUrl(), $this->suffix);
114
			$this->segments = array_filter(explode('/', $url)) + static::HOME;
115
		}
116
117
		return $this->segments;
118
	}
119
}
120