2023-12-12 19:46:11 +00:00
|
|
|
<?php
|
|
|
|
|
2023-12-12 20:25:41 +00:00
|
|
|
namespace urlManipulator;
|
|
|
|
|
|
|
|
class UrlManipulator extends AbstractUrlManipulator
|
2023-12-12 19:46:11 +00:00
|
|
|
{
|
|
|
|
private $paramsArray = ['param1', 'param2', 'param3', 'param4'];
|
|
|
|
|
2023-12-12 20:25:41 +00:00
|
|
|
public function manipulateUrl($url): array
|
2023-12-12 19:46:11 +00:00
|
|
|
{
|
|
|
|
if (!filter_var($url, FILTER_VALIDATE_URL)) {
|
|
|
|
return ['error' => 'Invalid URL', 'input' => $url];
|
|
|
|
}
|
|
|
|
|
|
|
|
$parsedUrl = parse_url($url);
|
|
|
|
$existingParams = [];
|
|
|
|
if (isset($parsedUrl['query'])) {
|
|
|
|
parse_str($parsedUrl['query'], $existingParams);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (empty($this->paramsArray)) {
|
|
|
|
return ['error' => 'Params array is full', 'input' => $url];
|
|
|
|
}
|
|
|
|
|
|
|
|
$newParam = $this->getNewParam($existingParams);
|
|
|
|
|
|
|
|
if (!$newParam) {
|
|
|
|
return ['error' => 'Unable to find a unique parameter to add', 'input' => $url];
|
|
|
|
}
|
|
|
|
|
|
|
|
$randomValue = $this->generateRandomValue();
|
|
|
|
|
|
|
|
$modifiedUrl = $this->addParamToUrl($url, $newParam, $randomValue);
|
|
|
|
|
2023-12-12 20:25:41 +00:00
|
|
|
return ['status' => 200, 'data' => $modifiedUrl];
|
2023-12-12 19:46:11 +00:00
|
|
|
}
|
|
|
|
|
2023-12-12 20:25:41 +00:00
|
|
|
protected function addParamToUrl(string $url, string $param, string $value): string
|
2023-12-12 19:46:11 +00:00
|
|
|
{
|
|
|
|
$separator = (parse_url($url, PHP_URL_QUERY) == null) ? '?' : '&';
|
|
|
|
|
|
|
|
if (strpos($url, $param . '=') !== false) {
|
|
|
|
$modifiedUrl = preg_replace('/(' . $param . '=)[^&]+/', '$1' . urlencode($value), $url);
|
|
|
|
} else {
|
|
|
|
$modifiedUrl = $url . $separator . urlencode($param) . '=' . urlencode($value);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $modifiedUrl;
|
|
|
|
}
|
|
|
|
|
2023-12-12 20:25:41 +00:00
|
|
|
protected function generateRandomValue(): string
|
2023-12-12 19:46:11 +00:00
|
|
|
{
|
|
|
|
return uniqid();
|
|
|
|
}
|
|
|
|
|
2023-12-12 20:25:41 +00:00
|
|
|
protected function getNewParam(array $existingParams): string | null
|
|
|
|
{
|
2023-12-12 19:46:11 +00:00
|
|
|
while (!empty($this->paramsArray)) {
|
|
|
|
$newParam = array_pop($this->paramsArray);
|
|
|
|
|
|
|
|
if (!array_key_exists($newParam, $existingParams)) {
|
|
|
|
return $newParam;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|