The League of Extraordinary Packages

Our Packages:

Presented by The League of Extraordinary Packages

Getting Started

Uri

Uri Schemes

Uri manipulation

Uri Parts API

Services

Upgrading Guide

The Query component

The library provides a Query class to ease complex query manipulation.

Query creation

Using the default constructor

<?php

public function __contruct(string $query = null)

The constructor accepts:

Example

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=yolo&z=');
echo $query->getContent(); //display 'foo=bar&p=yolo&z'
echo $query; //display 'foo=bar&p=yolo&z'
echo $query->getUriComponent(); //display '?foo=bar&p=yolo&z'

When using the default constructor do not prepend your query delimiter to the string as it will be considered as part of the first parameter name.

If the submitted value is not a valid query an InvalidArgumentException will be thrown.

Using a League Uri object

<?php

use League\Uri\Ws as WsUri;

$uri = WsUri::createFromString('wss://uri.thephpleague.com/path/to/here?foo=bar');
$query = $uri->query; //$query is a League\Uri\Components\Query object;

Using a named constructor

Since version 4.2 createFromPairs replaces createFromArray. createFromArray is deprecated and will be removed in the next major release

Returns a new Query object from an array or a Traversable object.

<?php

public static function Query::createFromPairs(array $pairs): Query

Examples

<?php

use League\Uri\Components\Query;

$query =  Query::createFromPairs([
    'foo' => 'bar',
    'p' => 'yolo',
    'z' => ''
]);
echo $query; //display 'foo=bar&p=yolo&z='

$query =  Query::createFromPairs([
    'foo' => 'bar',
    'p' => null,
    'z' => ''
]);
echo $query; //display 'foo=bar&p&z='

Properties and methods

The component representation, comparison and manipulation is done using the package UriPart and the Component interfaces methods.

Accessing query pairs

Since version 4.2 getPairs replaces toArray. toArray is deprecated and will be removed in the next major release

<?php

public function Query::getIterator(): ArrayIterator
public function Query::count(): int
public function Query::getPairs(): array
public function Query::keys(mixed $value = null): array
public function Query::hasKey(string $offset): bool
public function Query::getValue(string $offset, $default = null): mixed

Countable and IteratorAggregate

The class provides several methods to work with its parameters. The class implements PHP’s Countable and IteratorAggregate interfaces. This means that you can count the number of parameters and use the foreach construct to iterate over them.

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=y+olo&z=');
count($query); //return 4
foreach ($query as $key => $value) {
    //do something meaningful here
}

When looping the returned data are decoded.

Query::getPairs

Since version 4.2 getPairs replaces toArray. toArray is deprecated and will be removed in the next major release

A query can be represented as an array of its internal key/value pairs. Through the use of the Query::getPairs method the class returns the object’s array representation. This method uses QueryParser::parse to create the array.

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=y+olo&z=');
$query->getPairs();
// returns [
//     'foo' => 'bar',
//     'p'   => 'y olo',
//     'z'   => '',
// ]

The returned array contains decoded data.

The array returned by getPairs differs from the one returned by parse_str as it preserves the query string values.

Query::keys

Returns the decoded query keys as shown below:

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=y+olo&z=');
$query->keys();        //return ['foo', 'p', 'z'];
$query->keys('bar');   //return ['foo'];
$query->keys('gweta'); //return [];

By default, the method returns all the keys names, but if you supply a value, only the keys whose value equals the value are returned.

Query::hasKey

Tells whether the submitted key exists in the current Query object.

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=y+olo&z=');
$query->hasKey('p');    //return true
$query->hasKey('john'); //return false

Query::getValue

Returns the decoded query value of a specified pair key as shown below:

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=y+olo&z=');
$query->getValue('foo');          //return 'bar'
$query->getValue('gweta');        //return null
$query->getValue('gweta', 'now'); //return 'now'

The method returns the value of a specific parameter name. If the offset does not exist it will return the value specified by the second argument which defaults to null.

Modifying a query

If the modifications do not change the current object, it is returned as is, otherwise, a new modified object is returned.

When a modification fails an InvalidArgumentException is thrown.

Query::ksort

Returns a Query object with its pairs sorted according to its keys.

<?php

public function Query::ksort(mixed $sort): Query

The single argument sort can be:

One of PHP’s sorting constant used by the sort function. In this case the query parameters are sorted from low to high like PHP’s ksort function

<?php

use League\Uri\Components\Query;

$query    = new Query('foo=bar&baz=toto');
$newQuery = $query->ksort(SORT_STRING);
$newQuery->__toString(); //return baz=toto&foo=bar

A user-defined comparison function which must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second, like PHP’s uksort function

<?php

use League\Uri\Components\Query;


$query    = new Query('foo=bar&baz=toto');
$newQuery = $query->ksort('strcmp');
$newQuery->__toString(); //return baz=toto&foo=bar

This method is used by the URI modifier KsortQuery

Query::merge

Returns a new Query object with its data merged.

<?php

public function Query::merge(mixed $query): Query

This method expects a single argument which can be:

A string or a stringable object:

<?php

use League\Uri\Components\Query;

$query    = new Query('foo=bar&baz=toto');
$newQuery = $query->merge('foo=jane&r=stone');
$newQuery->__toString(); //return foo=jane&baz=toto&r=stone
// the 'foo' parameter was updated
// the 'r' parameter was added

Another Query object

<?php

use League\Uri\Components\Query;

$query    = Query::createFromPairs(['foo' => 'bar', 'baz' => 'toto']);
$newQuery = $query->merge(new Query('foo=jane&r=stone'));
$newQuery->__toString(); //return foo=jane&baz=toto&r=stone
// the 'foo' parameter was updated
// the 'r' parameter was added

Values equal to null or the empty string are merge differently.

<?php

use League\Uri\Components\Query;

$query    = Query::createFromPairs(['foo' => 'bar', 'baz' => 'toto']);
$newQuery = $query->merge('baz=&r');
$newQuery->__toString(); //return foo=bar&baz=&r
// the 'r' parameter was added without any value
// the 'baz' parameter was updated to an empty string and its = sign remains

This method is used by the URI modifier MergeQuery

Query::without

Returns a new Query object with deleted pairs according to their keys.

<?php

public function Query::without(array $keys): Query

This method expects an array containing a list of keys to remove as its single argument.

<?php

use League\Uri\Components\Query;

$query    = new Query('foo=bar&p=y+olo&z=');
$newQuery = $query->without(['foo', 'p']);
echo $newQuery; //displays 'z='

This method is used by the URI modifier RemoveQueryKeys

Query::filter

Returns a new Query object with filtered pairs.

<?php

public function Query::filter(callable $filter, $flag = Query::FILTER_USE_VALUE): Query

Filtering is done using the same arguments as PHP’s array_filter.

You can filter the query by the pairs values:

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=y+olo&z=');
$filter = function ($value) {
    return !empty($value);
};

$newQuery = $query->filter($filter, Query::FILTER_USE_VALUE);
echo $newQuery; //displays 'foo=bar&p=y+olo'

You can filter the query by the pairs keys:

<?php

use League\Uri\Components\Query;

$query = new Query('foo=bar&p=y+olo&z=');
$filter = function ($key) {
    return strpos($key, 'f');
};

$newQuery = $query->filter($filter, Query::FILTER_USE_KEY);
echo $newQuery; //displays 'foo=bar'

You can filter the query by pairs

<?php

use League\Uri\Components\Query;

$query = new Query('toto=foo&bar=foo&john=jane');
$filter = function ($value, $key) {
    return (strpos($value, 'o') !== false && strpos($key, 'o') !== false);
};

$newQuery = $query->filter($filter, Query::FILTER_USE_BOTH);
echo $newQuery; //displays 'toto=foo'

By specifying the second argument flag you can change how filtering is done:

By default, if no flag is specified the method will filter the query using the Query::FILTER_USE_VALUE flag.

If you are using PHP 5.6+ you can substitute these constants with PHP's array_filter flags constants ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH

This method is used by the URI modifier FilterQuery