ArrayUtil.php
1 year ago
DefaultLogger.php
1 year ago
JsonSerializable.php
1 year ago
Logger.php
1 year ago
StringUtil.php
1 year ago
TimeUnit.php
1 year ago
TimeUtil.php
1 year ago
TimeValue.php
1 year ago
UrlUtil.php
1 year ago
UrlUtil.php
74 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WonderPush\Util; |
| 4 | |
| 5 | if (count(get_included_files()) === 1) { http_response_code(403); exit(); } // Prevent direct access |
| 6 | |
| 7 | /** |
| 8 | * Utility class for URL manipulation. |
| 9 | */ |
| 10 | class UrlUtil { |
| 11 | |
| 12 | /** |
| 13 | * Parses a query string into an associative array. |
| 14 | * |
| 15 | * PHP syntax and duplicated arguments are not supported (`foo[bar]=`, `foo[]=`, etc.). |
| 16 | * |
| 17 | * @param string|null|string[] $queryString |
| 18 | * @return string[] String parameter values by parameter name. |
| 19 | * @throws \InvalidArgumentException |
| 20 | */ |
| 21 | public static function parseQueryString($queryString) { |
| 22 | if (is_array($queryString)) { |
| 23 | return $queryString; |
| 24 | } |
| 25 | if ($queryString === '' || $queryString === null) { |
| 26 | return array(); |
| 27 | } |
| 28 | if (!is_string($queryString)) { |
| 29 | throw new \InvalidArgumentException('Query string must be a string, null, or already parsed array'); |
| 30 | } |
| 31 | return call_user_func_array('array_merge', array_map(function($queryPart) { |
| 32 | $keyValue = explode('=', $queryPart, 2); |
| 33 | return array(urldecode($keyValue[0]) => urldecode($keyValue[1])); |
| 34 | }, explode('&', $queryString))); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Returns a new URL with the desired query string in lieu of the original one, if any. |
| 39 | * @param string $url The original URL to replace the query string from. |
| 40 | * @param string|array $newQueryString The new query string to use. |
| 41 | * @return string The modified URL with a new query string. |
| 42 | */ |
| 43 | public static function replaceQueryStringInUrl($url, $newQueryString) { |
| 44 | $hashPos = strpos($url, '#'); |
| 45 | if ($hashPos === false) { |
| 46 | $fragment = null; |
| 47 | } else { |
| 48 | $fragment = substr($url, $hashPos + 1); |
| 49 | $url = substr($url, 0, $hashPos); |
| 50 | } |
| 51 | $questionMarkPos = strpos($url, '?'); |
| 52 | if ($questionMarkPos !== false) { |
| 53 | $url = substr($url, 0, $questionMarkPos); |
| 54 | } |
| 55 | $qs = $newQueryString; |
| 56 | if (!is_string($qs) && $qs !== null) { |
| 57 | if (defined('PHP_QUERY_RFC3986')) { |
| 58 | // @codingStandardsIgnoreLine |
| 59 | $qs = http_build_query($qs, '', '&', PHP_QUERY_RFC3986); |
| 60 | } else { |
| 61 | $qs = http_build_query($qs); |
| 62 | } |
| 63 | } |
| 64 | if (!empty($qs)) { |
| 65 | $url .= '?' . $qs; |
| 66 | } |
| 67 | if ($fragment !== null) { |
| 68 | $url .= '#' . $fragment; |
| 69 | } |
| 70 | return $url; |
| 71 | } |
| 72 | |
| 73 | } |
| 74 |