Set the query part of the URL

@param Query|string|array $query Query string value to set. Can
be a string that will be parsed into a Query object, an array
of key value pairs, or a Query object.

@return Url
@throws \InvalidArgumentException
194122
public function setQuery($query)
    {
        if ($query instanceof Query) {
            $this->query = $query;
        } elseif (is_string($query)) {
            $this->query = Query::fromString($query);
        } elseif (is_array($query)) {
            $this->query = new Query($query);
        } else {
            throw new \InvalidArgumentException('Query must be a '
                . 'QueryInterface, array, or string');
        }

        return $this;
    }
889476
public function query($query, array $params = [])
    {
        $this->queryString = $query;
        $this->queryParams = $params;

        return $this;
    }
405102
private function buildQueryUrlParameter($query)
    {
        switch ($query) {
            case is_array($query) && isset($query['lat']) && isset($query['lon']) && is_numeric($query['lat']) && is_numeric($query['lon']):
                return "lat={$query['lat']}&lon={$query['lon']}";
            case is_array($query) && is_numeric($query[0]):
                return 'id='.implode(',', $query);
            case is_numeric($query):
                return "id=$query";
            case is_string($query) && strpos($query, 'zip:') === 0:
                $subQuery = str_replace('zip:', '', $query);
                return 'zip='.urlencode($subQuery);
            case is_string($query):
                return 'q='.urlencode($query);
            default:
                throw new \InvalidArgumentException('Error: $query has the wrong format. See the documentation of OpenWeatherMap::getWeather() to read about valid formats.');
        }
    }
1370446
private static function parseUrl(string $url, array $query = [], array $allowedSchemes = ['http' => 80, 'https' => 443]): array
    {
        if (false === $parts = parse_url($url)) {
            throw new InvalidArgumentException(sprintf('Malformed URL "%s".', $url));
        }

        if ($query) {
            $parts['query'] = self::mergeQueryString($parts['query'] ?? null, $query, true);
        }

        $port = $parts['port'] ?? 0;

        if (null !== $scheme = $parts['scheme'] ?? null) {
            if (!isset($allowedSchemes[$scheme = strtolower($scheme)])) {
                throw new InvalidArgumentException(sprintf('Unsupported scheme in "%s".', $url));
            }

            $port = $allowedSchemes[$scheme] === $port ? 0 : $port;
            $scheme .= ':';
        }

        if (null !== $host = $parts['host'] ?? null) {
            if (!\defined('INTL_IDNA_VARIANT_UTS46') && preg_match('/[\x80-\xFF]/', $host)) {
                throw new InvalidArgumentException(sprintf('Unsupported IDN "%s", try enabling the "intl" PHP extension or running "composer require symfony/polyfill-intl-idn".', $host));
            }

            if (false === $host = \defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) : strtolower($host)) {
                throw new InvalidArgumentException(sprintf('Unsupported host in "%s".', $url));
            }

            $host .= $port ? ':'.$port : '';
        }

        foreach (['user', 'pass', 'path', 'query', 'fragment'] as $part) {
            if (!isset($parts[$part])) {
                continue;
            }

            if (false !== strpos($parts[$part], '%')) {
                // https://tools.ietf.org/html/rfc3986#section-2.3
                $parts[$part] = preg_replace_callback('/%(?:2[DE]|3[0-9]|[46][1-9A-F]|5F|[57][0-9A]|7E)++/i', function ($m) { return rawurldecode($m[0]); }, $parts[$part]);
            }

            // https://tools.ietf.org/html/rfc3986#section-3.3
            $parts[$part] = preg_replace_callback("#[^-A-Za-z0-9._~!$&/'()*+,;=:@%]++#", function ($m) { return rawurlencode($m[0]); }, $parts[$part]);
        }

        return [
            'scheme' => $scheme,
            'authority' => null !== $host ? '//'.(isset($parts['user']) ? $parts['user'].(isset($parts['pass']) ? ':'.$parts['pass'] : '').'@' : '').$host : null,
            'path' => isset($parts['path'][0]) ? $parts['path'] : null,
            'query' => isset($parts['query']) ? '?'.$parts['query'] : null,
            'fragment' => isset($parts['fragment']) ? '#'.$parts['fragment'] : null,
        ];
    }
171943
public static function fromString($query)
    {
        $q = new static();

        if ($query || $query === '0') {
            if ($query[0] == '?') {
                $query = substr($query, 1);
            }
            foreach (explode('&', $query) as $kvp) {
                $parts = explode('=', $kvp, 2);
                $key = rawurldecode($parts[0]);

                if ($paramIsPhpStyleArray = substr($key, -2) == '[]') {
                    $key = substr($key, 0, -2);
                }

                if (isset($parts[1])) {
                    $value = rawurldecode(str_replace('+', '%20', $parts[1]));
                    if ($paramIsPhpStyleArray && !$q->hasKey($key)) {
                        $value = array($value);
                    }
                    $q->add($key, $value);
                } else {
                    $q->add($key, null);
                }
            }
        }

        return $q;
    }
668419
public function sql($query, $args = []) {
		if (!is_string($query) || empty($query))
			throw new \InvalidArgumentException("Query is not a valid string");
	
		//open connection
		$this->driver->connect();
			
		//build statement
		$stmt = $this->driver->buildStatement($this->typeManager);
	
		//build query
		$query = $stmt->format($query, $args, $this->config);
		
		//invoke debug callback
		if ($this->hasOption('callback.debug')) {
			$callback = $this->getOption('callback.debug');
			if ($callback instanceof \Closure)
				$callback->__invoke($query);
		}
		
		//run query
		$result = $this->driver->query($query);
	
		//check query execution
		if ($result === false)
			$this->driver->throwQueryException($stmt);
	
		return $result;
	}
854486
public function withQuery($query)
    {
        if (!is_string($query) && !method_exists($query, '__toString')) {
            throw new InvalidArgumentException('Uri query must be a string');
        }
        $query = ltrim((string)$query, '?');
        $clone = clone $this;
        $clone->query = Validator::checkQuery($query);

        return $clone;
    }
1054343
protected function prepareUrl($url, $query = array())
    {
        $processedUrl = $url;

        if ($query) {
            // URL has already query string, merge
            if (strpos($url, '?') !== false) {
                $components = parse_url($url);
                $params = array();
                parse_str($components['query'], $params);
                $params = $params + $query;
                $components['query'] = http_build_query($params);
                $processedUrl = http_build_url($components);
            } else {
                $processedUrl .= '?' . http_build_query($query);
            }
        }

        return $processedUrl;
    }
757042
public static function quoteUrl($query) {
        $queryParts = explode(' ', Str::assert($query, 'query'));

        return trim(array_reduce($queryParts, function($carry, $part) {
            return $carry . (Url::is($part) ? ('"' . $part . '" ') : ($part . ' '));
        }));
    }
1166090
public static function parseUrlQuery($query)
    {
        $result = [];
        $pairs = explode('&', $query);
        foreach ($pairs as $pair) {
            $parts = explode('=', $pair);
            $rawKey = $parts[0];
            $rawValue = isset($parts[1]) ? $parts[1] : '';
            $value = urldecode($rawValue);
            $key = strtr(urldecode($rawKey), ['[' => '.', ']' => '']);
            Arr::set($result, $key, $value);
        }
        return $result;
    }
935907
public function parse($query)
    {
        $queries = array();
        parse_str($query, $queries);

        return new Query($this->parseHttpQueryComponents($queries), $this->getPersister());
    }
49656
public static function filterQueryOrFragment($query)
    {
        if (!\is_string($query)) {
            throw new \InvalidArgumentException('Uri query string and fragment must be a string');
        }

        return preg_replace_callback(
            '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/u',
            function ($match) {
                return rawurlencode($match[0]);
            },
            $query
        ) ?? '';
    }
128446
public function withQuery(string $query): UriInterface
    {
        $query = $this->marshalQueryAndFragment($query);

        if ( $this->query === $query ) {
            return $this;
        }

        $instance = clone $this;
        $instance->query = $query;

        return $instance;
    }
443198
function setQuery($query)
    {
        if ($query !== null) {
            $q = $this->getQuery();
            $q->with($q::parseWith($query));
        }

        return $this;
    }
514409
public function setQueryVariables($array)
    {
        if (! is_array($array)) {

            throw new InvalidArgumentException('Must pass an array to setQueryVariables()');
        }

        $parts = array();

        foreach ($array as $name => $value) {

            $name = urlencode($name);

            if (! is_null($value)) {

                $parts[] = $name . '=' . urlencode($value);

            } else {

                $parts[] = $name;
            }
        }

        $this->setQuery(implode('&', $parts));
    }
1185106
public function doSearch($query = [])
    {
        if (!$this->index) {
            throw new \RuntimeException("You must set an index");
        }

        $this->prepare($query);

        // Only process query when there is a value, in order to avoid sending
        // an empty query string to ElasticSearch, its API is so weird that we
        // probably would end up with exceptions
        $value = $this->getQueryParam($query, $this->fulltextParameterName);
        if ($value) {
            $isQueryEmpty = false;

            $queryPart = [
                'query_string' => [
                    'query' => $this->fixSmartSearch((string)$value),
                    'fields' => $this->fulltextFields,
                 ],
            ];

            if ($this->fulltextAnalyzer) {
                $queryPart['query_string']['analyzer'] = $this->fulltextAnalyzer;
            }

        } else {
            $isQueryEmpty = true;
            $queryPart = [];
        }

        // This must be set before filter since filter query will be altered by
        // the applied aggregations
        $aggs = $this->buildAggQueryData($query);

        if (count($this->filterQuery)) {
            if ($isQueryEmpty) {
                $body = [
                    'query' => [
                        'constant_score' => [
                            'filter' => [
                                'fquery' => [
                                    'query' => [
                                        'query_string' => [
                                            'query' => (string)$this->filterQuery
                                        ],
                                    ],
                                    // @todo Without this ElasticSearch seems to
                                    // throw exceptions...
                                    '_cache' => true,
                                ],
                            ],
                        ],
                    ],
                ];
            } else {
                $body = [
                    'query' => [
                        'filtered' => [
                            'query'  => $queryPart,
                            'filter' => [
                                'fquery' => [
                                    'query' => [
                                        'query_string' => [
                                            'query' => (string)$this->filterQuery
                                        ],
                                    ],
                                    // @todo Without this ElasticSearch seems to
                                    // throw exceptions...
                                    '_cache' => true,
                                ],
                            ],
                        ],
                    ],
                ];
            }
        } else {
            if ($isQueryEmpty) {
                $body = [
                    'query' => [
                        'match_all' => []
                    ],
                ];
            } else {
                $body = [
                    'query' => $queryPart,
                ];
            }
        }

        if (count($this->postFilterQuery)) {
            $body['post_filter']['query_string']['query'] = (string)$this->postFilterQuery;
        }

        if ($aggs) {
            $body['aggs'] = $aggs;
        }
/*
        if ($this->fields) {
            $body['fields'] = $this->fields;
        }*/

        if (count($this->sortFields)) {
            foreach ($this->sortFields as $sort) {
                $body['sort'][] = $sort->getSortStructure();
            }
        }

        $data = [
            'index' => $this->index,
            'type'  => 'node',
            'body'  => $body,
        ];

        if (!empty($this->limit)) {
            $data['size'] = $this->limit;
            if (!empty($this->page)) {
                $data['from'] = max([0, $this->page - 1]) * $this->limit;
            }
        }

        return new Response($this, $this->client->search($data));
    }
1260595
public function setQueryString(array $query): self
    {

        foreach ($query as $key => $value) {
            if (is_array($value)) {
                $query[$key] = implode(',', $value);
            }
        }

        $this->query_string = array_merge($this->query_string, $query);

        return $this;
    }