Url.php 5.3 KB

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