Skip to content

Commit

Permalink
code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
KotsiosDimis committed Dec 27, 2024
1 parent df0f447 commit 919cc16
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 89 deletions.
91 changes: 2 additions & 89 deletions blokus.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,66 +19,13 @@
exit();
}




require_once "lib/dbconnect.php";
require_once "lib/accounts.php"; // Assuming you have user-related functions
require_once "lib/users.php";
require_once "lib/version.php";
//require_once "lib/router.php";
require_once "lib/router.php";
require_once "lib/lobbys.php";

class Router {
private $routes = [];

// Add routes dynamically
public function add($method, $path, $function) {
// Convert route placeholders to regex
$pattern = preg_replace('/\{[a-zA-Z0-9_]+\}/', '([^/]+)', $path);
// Store route with regex pattern and function
$this->routes[strtoupper($method)][] = [
'pattern' => "#^$pattern$#",
'function' => $function
];
}

// Handle the request
public function handle($method, $path, $input) {
$method = strtoupper($method);

// Check if the method has registered routes
if (!isset($this->routes[$method])) {
header("HTTP/1.1 404 Not Found");
echo json_encode(["error" => "Method not allowed"]);
return;
}

// Loop through registered routes for the method
foreach ($this->routes[$method] as $route) {
if (preg_match($route['pattern'], $path, $matches)) {
// Remove the full match and pass the rest as arguments
array_shift($matches);
call_user_func_array($route['function'], array_merge($matches, [$input]));
return;
}
}

// If no route matches, return 404
header("HTTP/1.1 404 Not Found");
echo json_encode(["error" => "Endpoint not found"]);
}

// Parse and handle the incoming request
public function routeRequest($input) {
$method = $_SERVER['REQUEST_METHOD'];
$path = trim($_SERVER['PATH_INFO'], '/'); // Clean the path
$input['token'] = $_SERVER['HTTP_X_TOKEN'] ?? '';

$this->handle($method, $path, $input);
}
}


// Initialize router
$router = new Router();
Expand All @@ -92,7 +39,7 @@ public function routeRequest($input) {

//user functions
$router->add('POST', 'users/register', function($input) {
registerUser($input['username'], $input['password'], $input['email']);
registerUser($input['username'], $input['password']);
});
$router->add('POST', 'users/login', function($input) {
loginUser($input['username'], $input['password']);
Expand All @@ -103,36 +50,11 @@ public function routeRequest($input) {
//lobby functions
$router->add('GET', 'lobbys', 'getLobbies');

//works
//$router->add('POST', 'lobbys/create', function() {
// createLobby(); // No parameters needed as the userId is hardcoded
//});

/*$userId = 2;
$gameType = 'middle';
$maxPlayers = 4;
$createdAt = date('Y-m-d H:i:s');*/

//Issue with parameters
/*$router->add('GET', 'lobbys/create', function($input) { //Figure out how we can test this one
if (isset($input['player1_id']) && is_numeric($input['player1_id'])) {
createLobby((int)$input['player1_id']);
} else {
echo json_encode(['error' => 'Invalid or missing userid parameter.']);
}
});*/

$router->add('POST', 'lobbys/create', function($input) { //Figure out how we can test this one too
createLobby((int)$input['userId'], $input['gameType'], (int)$input['maxPlayers'], $input['createdAt']);
});

/*$router->add('POST', 'lobbys/join', function($input) { //Figure out how we can test this one too
if (isset($input['userId']) && isset($input['lobbyId'])) {
joinLobby((int)$input['userId'], (int)$input['lobbyId']);
} else {
echo json_encode(['error' => 'Missing userId or lobbyId parameters']);
}
});*/



Expand All @@ -141,15 +63,6 @@ public function routeRequest($input) {
leaveLobby();
});

//Issue with parameters
// $router->add('POST', 'lobbys/leave', function($input) {
// if (isset($input['id'])) {
// leaveLobby((int)$input['id']);
// } else {
// echo json_encode(['error' => 'Missing lobbyId parameter']);
// }
// });

//games functions


Expand Down
53 changes: 53 additions & 0 deletions lib/rooter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

class Router {
private $routes = [];

// Add routes dynamically
public function add($method, $path, $function) {
// Convert route placeholders to regex
$pattern = preg_replace('/\{[a-zA-Z0-9_]+\}/', '([^/]+)', $path);
// Store route with regex pattern and function
$this->routes[strtoupper($method)][] = [
'pattern' => "#^$pattern$#",
'function' => $function
];
}

// Handle the request
public function handle($method, $path, $input) {
$method = strtoupper($method);

// Check if the method has registered routes
if (!isset($this->routes[$method])) {
header("HTTP/1.1 404 Not Found");
echo json_encode(["error" => "Method not allowed"]);
return;
}

// Loop through registered routes for the method
foreach ($this->routes[$method] as $route) {
if (preg_match($route['pattern'], $path, $matches)) {
// Remove the full match and pass the rest as arguments
array_shift($matches);
call_user_func_array($route['function'], array_merge($matches, [$input]));
return;
}
}

// If no route matches, return 404
header("HTTP/1.1 404 Not Found");
echo json_encode(["error" => "Endpoint not found"]);
}

// Parse and handle the incoming request
public function routeRequest($input) {
$method = $_SERVER['REQUEST_METHOD'];
$path = trim($_SERVER['PATH_INFO'], '/'); // Clean the path
$input['token'] = $_SERVER['HTTP_X_TOKEN'] ?? ''; // Optional token for security

$this->handle($method, $path, $input);
}
}

?>

0 comments on commit 919cc16

Please sign in to comment.