Url.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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{c?:string,a?:string,params?: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 !== false) {
  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{c:string,a:string,params:array<string,mixed>} $url URL as array definition
  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. if (is_string($url['params']['#'])) {
  69. $anchor = '#' . ($encodage === 'html' ? htmlspecialchars($url['params']['#'], ENT_QUOTES, 'UTF-8') : $url['params']['#']);
  70. }
  71. unset($url['params']['#']);
  72. }
  73. if (isset($url['c']) && is_string($url['c'])
  74. && $url['c'] != Minz_Request::defaultControllerName()) {
  75. $uri .= $separator . 'c=' . $url['c'];
  76. $separator = $and;
  77. }
  78. if (isset($url['a']) && is_string($url['a'])
  79. && $url['a'] != Minz_Request::defaultActionName()) {
  80. $uri .= $separator . 'a=' . $url['a'];
  81. $separator = $and;
  82. }
  83. if (isset($url['params']) && is_array($url['params'])) {
  84. unset($url['params']['c']);
  85. unset($url['params']['a']);
  86. foreach ($url['params'] as $key => $param) {
  87. if (!is_string($key) || (!is_string($param) && !is_int($param) && !is_bool($param))) {
  88. continue;
  89. }
  90. $uri .= $separator . urlencode($key) . '=' . urlencode((string)$param);
  91. $separator = $and;
  92. }
  93. }
  94. $uri .= $anchor;
  95. return $uri;
  96. }
  97. /**
  98. * Check that all array elements representing the controller URL are OK
  99. * @param array{c?:string,a?:string,params?:array<string,mixed>} $url controller URL as array
  100. * @return array{c:string,a:string,params:array<string,mixed>} Verified controller URL as array
  101. */
  102. public static function checkControllerUrl(array $url): array {
  103. return [
  104. 'c' => empty($url['c']) || !is_string($url['c']) ? Minz_Request::defaultControllerName() : $url['c'],
  105. 'a' => empty($url['a']) || !is_string($url['a']) ? Minz_Request::defaultActionName() : $url['a'],
  106. 'params' => empty($url['params']) || !is_array($url['params']) ? [] : $url['params'],
  107. ];
  108. }
  109. /** @param array{c?:string,a?:string,params?:array<string,mixed>} $url */
  110. public static function serialize(?array $url = []): string {
  111. if (empty($url)) {
  112. return '';
  113. }
  114. try {
  115. return base64_encode(json_encode($url, JSON_THROW_ON_ERROR));
  116. } catch (\Throwable $exception) {
  117. return '';
  118. }
  119. }
  120. /** @return array{c?:string,a?:string,params?:array<string,mixed>} */
  121. public static function unserialize(string $url = ''): array {
  122. $result = json_decode(base64_decode($url, true) ?: '', true, JSON_THROW_ON_ERROR) ?? [];
  123. /** @var array{c?:string,a?:string,params?:array<string,mixed>} $result */
  124. return $result;
  125. }
  126. /**
  127. * Returns an array representing the URL as passed in the address bar
  128. * @return array{c?:string,a?:string,params?:array<string,string>} URL representation
  129. */
  130. public static function build(): array {
  131. $url = [
  132. 'c' => $_GET['c'] ?? Minz_Request::defaultControllerName(),
  133. 'a' => $_GET['a'] ?? Minz_Request::defaultActionName(),
  134. 'params' => $_GET,
  135. ];
  136. // post-traitement
  137. unset($url['params']['c']);
  138. unset($url['params']['a']);
  139. return $url;
  140. }
  141. }
  142. /**
  143. * @param string $controller
  144. * @param string $action
  145. * @param string|int ...$args
  146. * @return string|false
  147. */
  148. function _url(string $controller, string $action, ...$args) {
  149. $nb_args = count($args);
  150. if ($nb_args % 2 !== 0) {
  151. return false;
  152. }
  153. $params = array ();
  154. for ($i = 0; $i < $nb_args; $i += 2) {
  155. $arg = '' . $args[$i];
  156. $params[$arg] = '' . $args[$i + 1];
  157. }
  158. return Minz_Url::display(['c' => $controller, 'a' => $action, 'params' => $params]);
  159. }