Url.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. * @return string Formatted URL
  16. * @throws Minz_ConfigurationException
  17. */
  18. public static function display($url = [], string $encoding = 'html', bool|string $absolute = false): string {
  19. $isArray = is_array($url);
  20. if ($isArray) {
  21. $url = self::checkControllerUrl($url);
  22. }
  23. $url_string = '';
  24. if ($absolute !== false) {
  25. $url_string = Minz_Request::getBaseUrl();
  26. if (strlen($url_string) < strlen('http://a.bc')) {
  27. $url_string = Minz_Request::guessBaseUrl();
  28. if (PUBLIC_RELATIVE === '..' && preg_match('%' . PUBLIC_TO_INDEX_PATH . '(/|$)%', $url_string)) {
  29. //TODO: Implement proper resolver of relative parts such as /test/./../
  30. $url_string = dirname($url_string);
  31. }
  32. }
  33. if ($isArray) {
  34. $url_string .= PUBLIC_TO_INDEX_PATH;
  35. }
  36. if ($absolute === 'root') {
  37. $url_string = parse_url($url_string, PHP_URL_PATH);
  38. }
  39. } else {
  40. $url_string = $isArray ? '.' : PUBLIC_RELATIVE;
  41. }
  42. if ($isArray) {
  43. $url_string .= '/' . self::printUri($url, $encoding);
  44. } elseif ($encoding === 'html') {
  45. $url_string = Minz_Helper::htmlspecialchars_utf8($url_string . $url);
  46. } else {
  47. $url_string .= $url;
  48. }
  49. return $url_string;
  50. }
  51. /**
  52. * Construit l'URI d'une URL
  53. * @param array{c:string,a:string,params:array<string,mixed>} $url URL as array definition
  54. * @param string $encodage pour indiquer comment encoder les & (& ou &amp; pour html)
  55. * @return string uri sous la forme ?key=value&key2=value2
  56. */
  57. private static function printUri(array $url, string $encodage): string {
  58. $uri = '';
  59. $separator = '?';
  60. $anchor = '';
  61. if ($encodage === 'html') {
  62. $and = '&amp;';
  63. } else {
  64. $and = '&';
  65. }
  66. if (!empty($url['params']) && is_array($url['params']) && !empty($url['params']['#'])) {
  67. if (is_string($url['params']['#'])) {
  68. $anchor = '#' . ($encodage === 'html' ? htmlspecialchars($url['params']['#'], ENT_QUOTES, 'UTF-8') : $url['params']['#']);
  69. }
  70. unset($url['params']['#']);
  71. }
  72. if (isset($url['c']) && is_string($url['c'])
  73. && $url['c'] != Minz_Request::defaultControllerName()) {
  74. $uri .= $separator . 'c=' . $url['c'];
  75. $separator = $and;
  76. }
  77. if (isset($url['a']) && is_string($url['a'])
  78. && $url['a'] != Minz_Request::defaultActionName()) {
  79. $uri .= $separator . 'a=' . $url['a'];
  80. $separator = $and;
  81. }
  82. if (isset($url['params']) && is_array($url['params'])) {
  83. unset($url['params']['c']);
  84. unset($url['params']['a']);
  85. foreach ($url['params'] as $key => $param) {
  86. if (!is_string($key) || (!is_string($param) && !is_int($param) && !is_bool($param))) {
  87. continue;
  88. }
  89. $uri .= $separator . urlencode($key) . '=' . urlencode((string)$param);
  90. $separator = $and;
  91. }
  92. }
  93. $uri .= $anchor;
  94. return $uri;
  95. }
  96. /**
  97. * Check that all array elements representing the controller URL are OK
  98. * @param array{c?:string,a?:string,params?: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. /** @return array{c?:string,a?:string,params?:array<string,mixed>} */
  120. public static function unserialize(string $url = ''): array {
  121. $result = json_decode(base64_decode($url, true) ?: '', true, JSON_THROW_ON_ERROR) ?? [];
  122. /** @var array{c?:string,a?:string,params?:array<string,mixed>} $result */
  123. return $result;
  124. }
  125. /**
  126. * Returns an array representing the URL as passed in the address bar
  127. * @return array{c?:string,a?:string,params?:array<string,string>} URL representation
  128. */
  129. public static function build(): array {
  130. $url = [
  131. 'c' => $_GET['c'] ?? Minz_Request::defaultControllerName(),
  132. 'a' => $_GET['a'] ?? Minz_Request::defaultActionName(),
  133. 'params' => $_GET,
  134. ];
  135. // post-traitement
  136. unset($url['params']['c']);
  137. unset($url['params']['a']);
  138. return $url;
  139. }
  140. }
  141. function _url(string $controller, string $action, int|string ...$args): string|false {
  142. $nb_args = count($args);
  143. if ($nb_args % 2 !== 0) {
  144. return false;
  145. }
  146. $params = array ();
  147. for ($i = 0; $i < $nb_args; $i += 2) {
  148. $arg = '' . $args[$i];
  149. $params[$arg] = '' . $args[$i + 1];
  150. }
  151. return Minz_Url::display(['c' => $controller, 'a' => $action, 'params' => $params]);
  152. }