URI modifiers

Example

For instance here’s how you would update the query string from a given URI object:

<?php

use Slim\Http\Uri;

$uriString = "http://www.example.com?fo.o=toto#~typo";
$queryToMerge = 'fo.o=bar&taz=';

$uri = Uri::createFromString($uriString);
parse_str($uri->getQuery(), $params);
parse_str($queryToMerge, $paramsToMerge);
$query = http_build_query(
    array_merge($params, $paramsToMerge),
    '',
    '&',
    PHP_QUERY_RFC3986
);

$newUri = $uri->withQuery($query);
echo $newUri; // display http://www.example.com?fo_o=bar&taz=#~typo

Using the provided League\Uri\UriModifier::mergeQuery modifier the code becomes

<?php

use League\Uri\UriModifier;
use Slim\Http\Uri;

$uriString = "http://www.example.com?fo.o=toto#~typo";
$queryToMerge = 'fo.o=bar&taz=';

$uri = Uri::createFromString($uriString);
$newUri = UriModifier::mergeQuery($uri, $queryToMerge);

echo get_class($newUri); // returns \Slim\Http\Uri
echo $newUri; // display http://www.example.com?fo.o=bar&taz=#~typo

In addition to merging the query to the URI, mergeQuery has:

Definition

An URI modifier is a method or a function which provides a convenient mechanism for filtering and manipulating an URI object. The only hard requirement is that the modifier MUST returns an URI instance of the same type that the one it received.

References

Under the hood the UriModifier class uses the URI components objects to apply changes to the submitted URI object.