Url.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * The Minz_Url class handles URLs across the MINZ framework
  5. */
  6. class Minz_Url {
  7. /**
  8. * Display a formatted URL
  9. * @param string|array<string,string|array<string,mixed>> $url The URL to format, defined as an array:
  10. * $url['c'] = controller
  11. * $url['a'] = action
  12. * $url['params'] = array of additional parameters
  13. * or as a string
  14. * @param string $encoding how to encode & (& ou &amp; pour html)
  15. * @param bool|string $absolute
  16. * @return string Formatted URL
  17. * @throws Minz_ConfigurationException
  18. */
  19. public static function display($url = [], string $encoding = 'html', $absolute = false): string {
  20. $isArray = is_array($url);
  21. if ($isArray) {
  22. $url = self::checkControllerUrl($url);
  23. }
  24. $url_string = '';
  25. if ($absolute) {
  26. $url_string = Minz_Request::getBaseUrl();
  27. if (strlen($url_string) < strlen('http://a.bc')) {
  28. $url_string = Minz_Request::guessBaseUrl();
  29. if (PUBLIC_RELATIVE === '..' && preg_match('%' . PUBLIC_TO_INDEX_PATH . '(/|$)%', $url_string)) {
  30. //TODO: Implement proper resolver of relative parts such as /test/./../
  31. $url_string = dirname($url_string);
  32. }
  33. }
  34. if ($isArray) {
  35. $url_string .= PUBLIC_TO_INDEX_PATH;
  36. }
  37. if ($absolute === 'root') {
  38. $url_string = parse_url($url_string, PHP_URL_PATH);
  39. }
  40. } else {
  41. $url_string = $isArray ? '.' : PUBLIC_RELATIVE;
  42. }
  43. if ($isArray) {
  44. $url_string .= '/' . self::printUri($url, $encoding);
  45. } elseif ($encoding === 'html') {
  46. $url_string = Minz_Helper::htmlspecialchars_utf8($url_string . $url);
  47. } else {
  48. $url_string .= $url;
  49. }
  50. return $url_string;
  51. }
  52. /**
  53. * Construit l'URI d'une URL
  54. * @param array<string,mixed> $url l'url sous forme de tableau
  55. * @param string $encodage pour indiquer comment encoder les & (& ou &amp; pour html)
  56. * @return string uri sous la forme ?key=value&key2=value2
  57. */
  58. private static function printUri(array $url, string $encodage): string {
  59. $uri = '';
  60. $separator = '?';
  61. $anchor = '';
  62. if ($encodage === 'html') {
  63. $and = '&amp;';
  64. } else {
  65. $and = '&';
  66. }
  67. if (!empty($url['params']) && is_array($url['params']) && !empty($url['params']['#'])) {
  68. $anchor = '#' . ($encodage === 'html' ? htmlspecialchars($url['params']['#'], ENT_QUOTES, 'UTF-8') : $url['params']['#']);
  69. unset($url['params']['#']);
  70. }
  71. if (isset($url['c'])
  72. && $url['c'] != Minz_Request::defaultControllerName()) {
  73. $uri .= $separator . 'c=' . $url['c'];
  74. $separator = $and;
  75. }
  76. if (isset($url['a'])
  77. && $url['a'] != Minz_Request::defaultActionName()) {
  78. $uri .= $separator . 'a=' . $url['a'];
  79. $separator = $and;
  80. }
  81. if (isset($url['params']) && is_array($url['params'])) {
  82. unset($url['params']['c']);
  83. unset($url['params']['a']);
  84. foreach ($url['params'] as $key => $param) {
  85. if (!is_string($key) || (!is_string($param) && !is_int($param))) {
  86. continue;
  87. }
  88. $uri .= $separator . urlencode($key) . '=' . urlencode((string)$param);
  89. $separator = $and;
  90. }
  91. }
  92. if (!empty($url['#']) && is_string($url['#'])) {
  93. $uri .= '#' . ($encodage === 'html' ? htmlspecialchars($url['#'], ENT_QUOTES, 'UTF-8') : $url['#']);
  94. }
  95. $uri .= $anchor;
  96. return $uri;
  97. }
  98. /**
  99. * Check that all array elements representing the controller URL are OK
  100. * @param array<string,string|array<string,mixed>> $url controller URL as array
  101. * @return array{'c':string,'a':string,'params':array<string,mixed>} Verified controller URL as array
  102. */
  103. public static function checkControllerUrl(array $url): array {
  104. return [
  105. 'c' => empty($url['c']) || !is_string($url['c']) ? Minz_Request::defaultControllerName() : $url['c'],
  106. 'a' => empty($url['a']) || !is_string($url['a']) ? Minz_Request::defaultActionName() : $url['a'],
  107. 'params' => empty($url['params']) || !is_array($url['params']) ? [] : $url['params'],
  108. ];
  109. }
  110. /** @param array{'c'?:string,'a'?:string,'params'?:array<string,mixed>} $url */
  111. public static function serialize(?array $url = []): string {
  112. if (empty($url)) {
  113. return '';
  114. }
  115. try {
  116. return base64_encode(json_encode($url, JSON_THROW_ON_ERROR));
  117. } catch (\Throwable $exception) {
  118. return '';
  119. }
  120. }
  121. /**
  122. * @phpstan-return array{'c'?:string,'a'?:string,'params'?:array<string,mixed>}
  123. * @return array<string,string|array<string,string>>
  124. */
  125. public static function unserialize(string $url = ''): array {
  126. $result = json_decode(base64_decode($url, true) ?: '', true, JSON_THROW_ON_ERROR) ?? [];
  127. /** @var array{'c'?:string,'a'?:string,'params'?:array<string,mixed>} $result */
  128. return $result;
  129. }
  130. /**
  131. * Returns an array representing the URL as passed in the address bar
  132. * @return array{'c'?:string,'a'?:string,'params'?:array<string,mixed>} URL representation
  133. */
  134. public static function build(): array {
  135. $url = [
  136. 'c' => $_GET['c'] ?? Minz_Request::defaultControllerName(),
  137. 'a' => $_GET['a'] ?? Minz_Request::defaultActionName(),
  138. 'params' => $_GET,
  139. ];
  140. // post-traitement
  141. unset($url['params']['c']);
  142. unset($url['params']['a']);
  143. return $url;
  144. }
  145. }
  146. /**
  147. * @param string $controller
  148. * @param string $action
  149. * @param string|int ...$args
  150. * @return string|false
  151. */
  152. function _url(string $controller, string $action, ...$args) {
  153. $nb_args = count($args);
  154. if ($nb_args % 2 !== 0) {
  155. return false;
  156. }
  157. $params = array ();
  158. for ($i = 0; $i < $nb_args; $i += 2) {
  159. $arg = '' . $args[$i];
  160. $params[$arg] = '' . $args[$i + 1];
  161. }
  162. return Minz_Url::display (array ('c' => $controller, 'a' => $action, 'params' => $params));
  163. }