-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
106 lines (91 loc) · 2.98 KB
/
Router.php
File metadata and controls
106 lines (91 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace PhpParser;
/**
* Router class for handling API requests
*
* This class handles routing of API requests to the appropriate handler methods
* and returns responses in the expected format.
*/
class Router
{
/**
* Handle incoming HTTP requests and route to appropriate handlers
*/
public function handleRequest()
{
// Set headers for JSON response
header('Content-Type: application/json');
// Get request URI and method
$requestUri = $_SERVER['REQUEST_URI'];
$requestMethod = $_SERVER['REQUEST_METHOD'];
// Parse URI - remove query string if present
$uri = parse_url($requestUri, PHP_URL_PATH);
// Route to appropriate handler
switch ($uri) {
case '/api/health':
$this->handleHealthCheck();
break;
case '/api/parse':
$this->handleParseRequest();
break;
default:
$this->handleNotFound();
break;
}
}
/**
* Handle health check endpoint
*/
private function handleHealthCheck()
{
http_response_code(200);
echo json_encode(['status' => 'hello from Php!', 'timestamp' => time()]);
}
/**
* Handle code parse request
*/
private function handleParseRequest()
{
// Only accept POST requests for this endpoint
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
return;
}
// Get request body
$requestBody = file_get_contents('php://input');
$requestData = json_decode($requestBody, true);
// Validate request data
if (!$requestData || !isset($requestData['code']) ||
!isset($requestData['fileType'])) {
http_response_code(400);
echo json_encode(['error' => 'Invalid request data']);
return;
}
// Create parser and process code
try {
$parser = new CodeParser();
// Set default empty string for modifiedLines if not provided
$modifiedLines = '';
$result = $parser->parseCode(
$requestData['code'],
$modifiedLines,
$requestData['fileType']
);
// Return result with optimized JSON encoding for large files
http_response_code(200);
echo json_encode($result, JSON_PARTIAL_OUTPUT_ON_ERROR);
} catch (\Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
}
/**
* Handle 404 Not Found response
*/
private function handleNotFound()
{
http_response_code(404);
echo json_encode(['error' => 'Not found']);
}
}