public static function mergeQuery($url, array $query)
    {
        // No query.
        if (!$query) {
            return $url;
        }

        $queryString = http_build_query($query);
        $qPos = strpos($url, '?');
        $hashPos = strpos($url, '#');
        $pos = strlen($url);
        $hasQuery = $qPos !== false && ($qPos < $hashPos || $hashPos === false);

        if ($qPos || $hashPos) {
            $pos = $hasQuery ? $qPos + 1 : $hashPos;
        }

        $prefix = substr($url, 0, $pos);
        $suffix = substr($url, $pos);

        return sprintf(
            '%s%s%s%s%s',
            $prefix,
            $hasQuery ? '' : '?',
            $queryString,
            $hasQuery ? '&' : '',
            $suffix
        );
    }