UrlManipulator-php/server/urlManipulator/UrlManipulator.php

83 lines
2.6 KiB
PHP

<?php
namespace urlManipulator;
class UrlManipulator extends AbstractUrlManipulator
{
private $paramsArray = ['param1', 'param2', 'param3', 'param4'];
public function manipulateUrl($url): array
{
// Using Session to store the original URL and used parameters
session_start();
// Check if the original URL is stored in the session
if (!isset($_SESSION['originalUrl'])) {
// Store the original URL in the session
$_SESSION['originalUrl'] = $url;
// Initialize the used parameters array in the session
$_SESSION['usedParams'] = [];
}
$originalUrl = $_SESSION['originalUrl'];
$usedParams = $_SESSION['usedParams'];
// Get a new parameter to add to the URL from the predefined array and existing parameters
$newParam = $this->getNewParam($usedParams, $originalUrl);
// If no new parameter is found, return an error
if (!$newParam) {
return ['error' => 'Unable to find a unique parameter to add', 'input' => $url];
}
$randomValue = $this->generateRandomValue();
$modifiedUrl = $this->addParamToUrl($originalUrl, $newParam, $randomValue);
// Store the used parameter in the session
$usedParams[] = $newParam;
$_SESSION['usedParams'] = $usedParams;
return [
'before' => $originalUrl,
'after' => $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 $usedParams, string $originalUrl)
{
$parsedUrl = parse_url($originalUrl);
$existingParams = [];
// Extract existing params from the original URL
if (isset($parsedUrl['query'])) {
parse_str($parsedUrl['query'], $existingParams);
}
// Find the first unused parameter from the predefined array and existing parameters
foreach ($this->paramsArray as $param) {
if (!in_array($param, $usedParams) && !array_key_exists($param, $existingParams)) {
return $param;
}
}
return null;
}
}