aboutsummaryrefslogtreecommitdiff
path: root/src/Service/URL.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/Service/URL.php')
-rw-r--r--src/Service/URL.php90
1 files changed, 90 insertions, 0 deletions
diff --git a/src/Service/URL.php b/src/Service/URL.php
new file mode 100644
index 0000000..035f572
--- /dev/null
+++ b/src/Service/URL.php
@@ -0,0 +1,90 @@
1<?php
2// src/Service/URL.php
3
4declare(strict_types=1);
5
6namespace App\Service;
7
8class URL implements \Stringable
9{
10 static private string $protocol = 'http://';
11 static private string $host = '';
12 static private string $port;
13 static private string $path = '/index.php';
14 private array $params;
15 private string $anchor = '';
16
17 public function __construct(array $gets = [], string $anchor = ''){
18 $this->params = $gets;
19 if($anchor != ''){
20 $this->setAnchor($anchor);
21 }
22 }
23
24 // setters statiques
25 static public function setProtocol(string $protocol = 'http'): void
26 {
27 self::$protocol = $protocol === 'https' ? 'https://' : 'http://';
28 }
29 static public function setPort(int|string $port = 80): void
30 {
31 if((int)$port === 443){
32 self::$protocol = 'https://';
33 self::$port = '';
34 }
35 elseif((int)$port === 80){
36 self::$protocol = 'http://';
37 self::$port = '';
38 }
39 else{
40 self::$port = ':' . (string)$port;
41 }
42 }
43 static public function setHost(string $host): void
44 {
45 self::$host = $host;
46 }
47 static public function setPath(string $path): void
48 {
49 self::$path = '/' . ltrim($path, '/');
50 }
51
52 //setters normaux
53 public function addParams(array $gets): void
54 {
55 // array_merge est préféré à l'opérateur d'union +, si une clé existe déjà la valeur est écrasée
56 $this->params = array_merge($this->params, $gets);
57 }
58 public function setAnchor(string $anchor = ''): void
59 {
60 if($anchor != ''){
61 $this->anchor = '#' . ltrim($anchor, '#');
62 }
63 else{
64 $this->anchor = '';
65 }
66 }
67
68 private function makeParams(): string
69 {
70 $output = '';
71 $first = true;
72
73 foreach($this->params as $key => $value) {
74 if($first){
75 $output .= '?';
76 $first = false;
77 }
78 else{
79 $output .= '&';
80 }
81 $output .= $key . '=' . $value;
82 }
83 return $output;
84 }
85
86 public function __toString(): string
87 {
88 return self::$protocol . self::$host . self::$port . self::$path . $this->makeParams() . $this->anchor;
89 }
90} \ No newline at end of file