In PHP 7.4, for URI, add query parameters based on League/URI
1. In Laravel 6, there is a simple implementation based on the judgment that the string contains ?
use Illuminate\Support\Str;
if (Str::contains($themeAwareUrlPath, '?')) {
$suffix = '&';
} else {
$suffix = '?';
}
return new HtmlString($prefix.$themeAwareUrlPath.$suffix.'d='.config('app.url'));
2. However, this implementation, some complex URIs are not considered. Example: ?d=3&e=5#6, will be replaced with: ?d=3&e=5#6&d=https://xxx.com.
3. The final decision is to add query parameters based on the League/URI, and execute the composer require League/uri-components and composer require League/URI
4. The code is implemented as follows
use League\Uri\Uri;
use League\Uri\UriModifier;
$uri = Uri::createFromString($themeAwareUrlPath);
$cdnUri = UriModifier::mergeQuery($uri, 'd=' . config('app.url'));
return new HtmlString($prefix . $cdnUri->jsonSerialize());
5. Based on some common URIs, the replacement results are as follows, in line with expectations
$themeAwareUrlPath = '9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg';
$themeAwareUrlPath .= '?a=3';
string(102) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?a=3&d=https://xxx.local"
$themeAwareUrlPath .= '?d=3';
string(98) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?d=https://xxx.local"
$themeAwareUrlPath .= '?d=3&e=5#6';
string(104) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?d=https://xxx.local&e=5#6"
$themeAwareUrlPath .= '?a=1&d=3&e=5#6';
string(108) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?a=1&d=https://xxx.local&e=5#6"
$themeAwareUrlPath .= '?#';
string(100) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?&d=https://xxx.local#"
$themeAwareUrlPath .= '?';
string(99) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?&d=https://xxx.local"