aboutsummaryrefslogtreecommitdiff
path: root/src/Service/URL.php
blob: e6f986c5e7fc47df71150793b34756ae6c275894 (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
<?php
// src/Service/URL.php

declare(strict_types=1);

namespace App\Service;

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 = '';

	public function __construct(array $gets = [], string $anchor = ''){
		$this->params = $gets;
		if($anchor != ''){
			$this->setAnchor($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, '/');
	}
	
	//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 = '#' . rawurlencode(ltrim($anchor, '#'));// rawurlencode échappe les mêmes caractères
		}
		else{
			$this->anchor = '';
		}
	}

	public function __toString(): string
	{
		return self::$protocol . self::$host . self::$port . self::$path
			. ($this->params ? '?' . http_build_query($this->params) : '')
			. $this->anchor;
		// http_build_query change un tableau comme ['key1' => 'value 1', 'key2' => 'value 2']
		// en chaine: key1=value+1&key2=value+2
		// les caractères ", ', <, >, &, #, = et espaces sont échappés (comme avec rawurlencode pour les ancres)
	}
}