From 6e9a4cb97c3db88eb92b2c68c4b6ac750d359482 Mon Sep 17 00:00:00 2001 From: divyesh000 Date: Sat, 18 May 2024 15:49:24 +0400 Subject: [PATCH] implement api controller for district endpoint --- src/controllers/api/Districts.php | 111 ++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/controllers/api/Districts.php diff --git a/src/controllers/api/Districts.php b/src/controllers/api/Districts.php new file mode 100644 index 00000000..7d3ed3a4 --- /dev/null +++ b/src/controllers/api/Districts.php @@ -0,0 +1,111 @@ + $district->getID(), + 'name' => $district->getName() + ]; + } + + // Return JSON response + echo json_encode($result); + } + + /** + * Get the details of a specific district by its ID. + */ + private function getDistrictById(): void + { + $districtId = (int)Utility::splitURL()[3]; + + // Retrieve district details from the database + $district = District::getByID($districtId); + + // Check if district exists + if ($district === null) { + // District not found, return 404 + http_response_code(404); + echo json_encode(['error' => 'District not found']); + return; + } + + // Return JSON response + echo json_encode([ + 'district_id' => $district->getID(), + 'name' => $district->getName() + ]); + } + + private function getHandler($routes): ?string + { + foreach ($routes[$_SERVER['REQUEST_METHOD']] as $route => $handler) { + $pattern = str_replace('/', '\/', $route); // Convert to regex pattern + $pattern = preg_replace( + '/\{([a-zA-Z0-9_]+)\}/', + '(?P<$1>[^\/]+)', + $pattern + ); // Replace placeholders with regex capture groups + $pattern = '/^' . $pattern . '$/'; + + if (preg_match($pattern, '/' . Utility::getURL(), $matches)) { + return $handler; + } + } + return null; + } + + /** + * Main entry point for the Districts API. + */ + public function index(): void + { + $routes = [ + 'GET' => [ + '/api/v1/districts' => 'getAllDistricts', + '/api/v1/districts/{id}' => 'getDistrictById', + ] + ]; + + // Handle the request + $handler = $this->getHandler($routes); + + if ($handler !== null) { + $functionName = $handler; + if (method_exists($this, $functionName)) { + call_user_func(array($this, $functionName)); + } else { + // Handle function not found + http_response_code(404); + echo "Function Not Found"; + die(); + } + } else { + // Handle route not found + http_response_code(404); + echo "Route Not Found"; + die(); + } + } +}