<?php
class Response {
public function __construct(protected $targetUrl = ''){}
public function getTargetUrl(): string {
return $this->targetUrl;
}
public function setTargetUrl(string $target_url): void {
$this->targetUrl = $target_url;
}
}
$withQuery = new Response('https://example.com?foo=bar');
$withoutQuery = new Response('https://example.com?');
$withoutQuestion = new Response('https://example.com');
function queryManip(Response $response): Response {
// The 'destination' parameter should remain in the query but be
// unused by the target_url.
$target_url = $response->getTargetUrl();
if (str_contains($target_url, '?')) {
$query_string = parse_url($target_url, PHP_URL_QUERY) ?: '';
parse_str($query_string, $query);
$target_url = substr($target_url, 0, strpos($target_url, '?')) . '?' . http_build_query($query);
}
$response->setTargetUrl($target_url);
return $response;
}
echo sprintf('With query: %s%s', queryManip($withQuery)->getTargetUrl(), \PHP_EOL);
echo sprintf('Without query: %s%s', queryManip($withoutQuery)->getTargetUrl(), \PHP_EOL);
echo sprintf('Without question: %s%s', queryManip($withoutQuestion)->getTargetUrl(), \PHP_EOL);
preferences:
23.93 ms | 410 KiB | 5 Q