summaryrefslogtreecommitdiff
path: root/src/URL.php
blob: 689332f92bb58cc7e420455f3d8b8586c3eb75ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
// src/URL.php

declare(strict_types=1);

class URL implements Stringable
{
	static private string $protocol = 'http://';
	static private string $host = '';
	static private string $port;
	static private string $path = '/index.php';
	private array $params;
	private string $anchor = '';

	// setters statiques
	static public function setProtocol(string $protocol = 'http'): void
	{
		self::$protocol = $protocol === 'https' ? 'https://' : 'http://';
	}
	static public function setPort(int|string $port = 80): void
	{
		if((int)$port === 443){
			self::$protocol = 'https://';
			self::$port = '';
		}
		elseif((int)$port === 80){
			self::$protocol = 'http://';
			self::$port = '';
		}
		else{
			self::$port = ':' . (string)$port;
		}
	}
	static public function setHost(string $host): void
	{
		self::$host = $host;
	}
	static public function setPath(string $path): void
	{
		self::$path = '/' . ltrim($path, '/');
	}

	public function __construct(array $gets = [], string $anchor = ''){
		$this->params = $gets;
		if($anchor != ''){
			$this->setAnchor($anchor);
		}
	}

	//setters normaux
	public function addParams(array $gets): void
	{
		// array_merge est préféré à l'opérateur d'union +, si une clé existe déjà la valeur est écrasée
		$this->params = array_merge($this->params, $gets);
	}
	public function setAnchor(string $anchor = ''): void
	{
		if($anchor != ''){
			$this->anchor = '#' . ltrim($anchor, '#');
		}
		else{
			$this->anchor = '';
		}
	}

	private function makeParams(): string
	{
		$output = '';
		$first = true;
		
		foreach($this->params as $key => $value) {
			if($first){
				$output .= '?';
				$first = false;
			}
			else{
				$output .= '&';
			}
			$output .= $key . '=' . $value;
		}
		return $output;
	}

	public function __toString(): string
	{
		return self::$protocol . self::$host . self::$port . self::$path . $this->makeParams() . $this->anchor;
	}
}