Percent encode the URI template literals as per RFC6570 section 3.1

Template::expandAll swapped every expression notation in the raw template
string with str_replace, so the literal text surrounding the expressions was
copied verbatim and never percent encoded. The expression detection pattern is
now used to split the template into an ordered list of parts: literals are
encoded once at construction, expressions stay Expression objects, and the
expansion simply concatenates them. Keeping the parts apart is what prevents
the already encoded expansion results from being encoded a second time.

Fixes the "Additional Examples 8: Literal Encoding" case of the vendored
uritemplate-test compliance suite.
This commit is contained in:
dualfroz committed 2026-09-04 08:43:47 +02:00
1 parent 432904515e
commit 2f4f2d71c4
3 files changed
+144 -23

No files matched your search

+25
View File
@@ -85,6 +85,31 @@ echo $uriTemplate->expandOrFail($params);
<p class="message-notice"><code>expandToUriOrFail()</code> and <code>expandToUrlOrFail()</code> are available since
version <code>7.6.0</code></p>
### Literal Expansion
The characters located outside of the template expressions are literals. As per
[RFC6570 section 3.1](https://www.rfc-editor.org/rfc/rfc6570#section-3.1) a literal character is
copied as is when it is allowed anywhere in the URI syntax, in other words when it belongs to the
`unreserved / reserved / pct-encoded` set. Any other character is percent encoded using its UTF-8
octets.
~~~php
$uriTemplate = new UriTemplate('https://example.com/café/{hotel}');
echo $uriTemplate->expand(['hotel' => 'Rest & Relax']), PHP_EOL;
// display https://example.com/caf%C3%A9/Rest%20%26%20Relax
~~~
Percent encoded triplets already present in the template are left untouched, they are never
encoded a second time.
~~~php
$uriTemplate = new UriTemplate('https://example.com/caf%C3%A9/{hotel}');
echo $uriTemplate->expand(['hotel' => 'Rest & Relax']), PHP_EOL;
// display https://example.com/caf%C3%A9/Rest%20%26%20Relax
~~~
## Template Variables
<p class="message-notice">For maximum interoperability you should make sure your variables are