type orianted methods and responses

This commit is contained in:
Kfir Dayan 2023-12-12 22:25:41 +02:00
parent b8595cdca8
commit 583e45b31c
6 changed files with 49 additions and 18 deletions

10
server/autoloader.php Normal file
View file

@ -0,0 +1,10 @@
<?php
function customAutoloader($className) {
$filePath = __DIR__ . '/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($filePath)) {
include $filePath;
}
}
spl_autoload_register('customAutoloader');

14
server/index.php Normal file
View file

@ -0,0 +1,14 @@
<?php
ini_set('display_errors', 1);
require('./autoloader.php');
use urlManipulator\UrlManipulator;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$urlManipulator = new UrlManipulator();
$url = $_POST['url'];
$result = $urlManipulator->manipulateUrl($url);
header('Content-Type: application/json');
echo json_encode($result);
}

View file

@ -0,0 +1,15 @@
<?php
namespace urlManipulator;
abstract class AbstractUrlManipulator
{
abstract public function manipulateUrl(string $url);
abstract protected function addParamToUrl(string $url, string $param, string $value);
abstract protected function generateRandomValue();
abstract protected function getNewParam(array $existingParams);
}

View file

@ -1,10 +1,12 @@
<?php
class UrlManipulator
namespace urlManipulator;
class UrlManipulator extends AbstractUrlManipulator
{
private $paramsArray = ['param1', 'param2', 'param3', 'param4'];
public function manipulateUrl($url)
public function manipulateUrl($url): array
{
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return ['error' => 'Invalid URL', 'input' => $url];
@ -31,13 +33,10 @@ class UrlManipulator
$modifiedUrl = $this->addParamToUrl($url, $newParam, $randomValue);
return [
'before' => $url,
'after' => $modifiedUrl,
];
return ['status' => 200, 'data' => $modifiedUrl];
}
private function addParamToUrl($url, $param, $value)
protected function addParamToUrl(string $url, string $param, string $value): string
{
$separator = (parse_url($url, PHP_URL_QUERY) == null) ? '?' : '&';
@ -50,12 +49,13 @@ class UrlManipulator
return $modifiedUrl;
}
private function generateRandomValue()
protected function generateRandomValue(): string
{
return uniqid();
}
private function getNewParam($existingParams){
protected function getNewParam(array $existingParams): string | null
{
while (!empty($this->paramsArray)) {
$newParam = array_pop($this->paramsArray);
@ -69,11 +69,3 @@ class UrlManipulator
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$urlManipulator = new UrlManipulator();
$url = $_POST['url'];
$result = $urlManipulator->manipulateUrl($url);
header('Content-Type: application/json');
echo json_encode($result);
}

View file

@ -3,7 +3,7 @@ function manipulateUrl() {
$.ajax({
type: 'POST',
url: '../server/process.php',
url: '../server/index.php',
data: { url: url },
dataType: 'json',
success: function (result) {