71 lines
1.9 KiB
PHP
71 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace urlManipulator;
|
|
|
|
class UrlManipulator extends AbstractUrlManipulator
|
|
{
|
|
private $paramsArray = ['param1', 'param2', 'param3', 'param4'];
|
|
|
|
public function manipulateUrl($url): array
|
|
{
|
|
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);
|
|
|
|
return ['status' => 200, 'data' => $modifiedUrl];
|
|
}
|
|
|
|
protected function addParamToUrl(string $url, string $param, string $value): string
|
|
{
|
|
$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;
|
|
}
|
|
|
|
protected function generateRandomValue(): string
|
|
{
|
|
return uniqid();
|
|
}
|
|
|
|
protected function getNewParam(array $existingParams): string | null
|
|
{
|
|
while (!empty($this->paramsArray)) {
|
|
$newParam = array_pop($this->paramsArray);
|
|
|
|
if (!array_key_exists($newParam, $existingParams)) {
|
|
return $newParam;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
}
|
|
|