Skip to content

Commit 09aa75d

Browse files
author
DevT045T
committed
Errors will be shown now
1 parent 86f1ec8 commit 09aa75d

File tree

2 files changed

+109
-6
lines changed

2 files changed

+109
-6
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ The response will be wrapped in the custom format:
124124
- `getPOSTParameters()`: Returns all given POST parameters as an array.
125125
- `__get(string $property)`: ✨Magic✨ getter method for accessing properties dynamically through the `$parameters` array. Returns the property’s value or null if not found.
126126
- `addParameter(APIParameter $parameter)`: Adds an allowed API parameter to the API instance. This defines the name, required status, and data type of the parameter.
127+
- `validate()`: Validates that all required data is correct and in the expected format. If any errors are found, an appropriate error message is returned.
128+
- `sendErrorResponse(int $responseCode, string $errorMessage, array $errorDetails = [])`: Sends a generic error response to the client, including a status code, an error message, and optional additional details about the error cause.
127129

128130
## API Parameter Management
129131

src/API.php

Lines changed: 107 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,14 @@ class API
2020
*
2121
* @var string
2222
*/
23-
public string $requesMethod;
23+
public string $requestMethod;
24+
25+
/**
26+
* The allowed HTTP request methods (e.g., GET, POST, PUT, DELETE).
27+
*
28+
* @var array
29+
*/
30+
private array $allowedRequestMethods;
2431

2532
/**
2633
* The response data that the API returns to the user
@@ -97,14 +104,32 @@ class API
97104
private array $customWrapper;
98105

99106
/**
100-
* @var APIParameter[] An array of allowed API parameters.
101-
*
102107
* This property holds an array of `APIParameter` objects that define the allowed
103108
* parameters for the API request. Each `APIParameter` object includes information
104109
* such as the parameter name, whether it is required, and its expected data type.
110+
*
111+
* @var APIParameter[] An array of allowed API parameters.
105112
*/
106113
private array $allowedParameters = [];
107114

115+
/**
116+
* The error message that will be included in the error response.
117+
* This message provides a brief description of the error encountered.
118+
*
119+
* @var string Default is a empty message
120+
*/
121+
private string $errorMessage;
122+
123+
/**
124+
* The additional details related to the error.
125+
* This attribute may include further information, such as specific validation errors
126+
* or any relevant data that can help the user or developer understand the cause
127+
* of the error more clearly.
128+
*
129+
* @var mixed
130+
*/
131+
private mixed $errorDetails;
132+
108133
/**
109134
* Constructor that initializes the request method by retrieving it from the server.
110135
*
@@ -117,8 +142,11 @@ public function __construct()
117142
$this->GETParameters = $_GET;
118143
$this->POSTParameters = [...(array)json_decode(file_get_contents('php://input')), ...$_POST];
119144

145+
$this->errorDetails = [];
146+
$this->errorMessage = "";
147+
120148
$this->scriptStartTime = microtime(true);
121-
$this->requesMethod = $_SERVER["REQUEST_METHOD"];
149+
$this->requestMethod = $_SERVER["REQUEST_METHOD"];
122150
}
123151

124152
/**
@@ -131,9 +159,28 @@ public function __construct()
131159
*/
132160
public function getRequestMethod(): string
133161
{
134-
return $this->requesMethod;
162+
return $this->requestMethod;
163+
}
164+
165+
/**
166+
* Sets the allowed request methods for the API.
167+
*
168+
* This method allows you to define which HTTP request methods (e.g., GET, POST, PUT, DELETE)
169+
* are allowed for the current API endpoint. By passing an array, you can allow multiple
170+
* request methods for a single endpoint. This is useful for defining flexible API behavior
171+
* where more than one HTTP method can be used for the same resource.
172+
*
173+
* @param array $requestMethods An array of allowed HTTP request methods (e.g., ['GET', 'POST', 'PUT']).
174+
*
175+
* @return self Returns the current instance for method chaining.
176+
*/
177+
public function setAllowedRequestMethod(array $requestMethods): self
178+
{
179+
$this->allowedRequestMethods = $requestMethods;
180+
return $this;
135181
}
136182

183+
137184
/**
138185
* Sets the response data for the API.
139186
*
@@ -283,6 +330,47 @@ public function addParameter(APIParameter $parameter): self
283330
return $this;
284331
}
285332

333+
/**
334+
* Validates the request method against the allowed methods.
335+
*
336+
* This method checks if the current request method is one of the allowed methods defined for
337+
* the API endpoint. If the request method is not allowed, an error response will be sent
338+
* with a 400 Bad Request status code.
339+
*
340+
* @return void
341+
*/
342+
public function validate(): void
343+
{
344+
if (!in_array($this->requestMethod, $this->allowedRequestMethods)) {
345+
$this->sendErrorResponse(HTTPStatusCodes::BAD_REQUEST, "The request method is not allowed for this resource.", [$this->requestMethod]);
346+
}
347+
}
348+
349+
/**
350+
* Sends an error response with the given status code and error message.
351+
*
352+
* This method prepares an error response with the specified HTTP status code and error message.
353+
* It then sends the response to the client.
354+
*
355+
* @param int $responseCode The HTTP status code for the error response.
356+
* @param string $errorMessage The error message to be included in the response.
357+
* @param mixed $errorDetails Default is an empty array. The error details to describe the error in detail.
358+
*
359+
* @return void
360+
*/
361+
public function sendErrorResponse(int $responseCode, string $errorMessage, mixed $errorDetails = []): void
362+
{
363+
$this->response = null;
364+
$this->responseCode = $responseCode;
365+
366+
$this->response = [
367+
"error_message" => $errorMessage,
368+
"error_details" => $errorDetails
369+
];
370+
371+
$this->send();
372+
}
373+
286374
/**
287375
* Prepares the response wrapper by wrapping the response with metadata.
288376
*
@@ -301,7 +389,7 @@ protected function prepareResponseWrapper(): self
301389
"count" => "{{ count }}",
302390
"runtime" => "{{ runtime }}"
303391
],
304-
"data" => "{{ data }}"
392+
"data" => "{{ data }}",
305393
];
306394

307395
$wrapper = $defaultWrapper;
@@ -340,11 +428,24 @@ private function parseWrapperTemplate(mixed $templateItem): mixed
340428
"{{ response_code }}" => $this->responseCode,
341429
"{{ host }}" => isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on" ? "https://" : "http://" . $_SERVER["HTTP_HOST"],
342430
"{{ count }}" => is_array($this->response) || is_object($this->response) ? count($this->response) : 0,
431+
/**
432+
* @TODO => Fix in future, it makes me cry 😭
433+
* Errors will be part in data for now :c
434+
*/
435+
// "{{ error_details }}" => $this->errorDetails,
436+
// "{{ error_message }}" => $this->errorMessage,
343437
"{{ runtime }}" => microtime(true) - $this->scriptStartTime,
344438
"{{ data }}" => $this->response,
345439
];
346440

441+
if (!is_string($templateItem)) {
442+
return $templateItem;
443+
}
444+
347445
foreach ($placeholders as $placeholder => $replacement) {
446+
if (is_null($placeholder)) {
447+
return $templateItem;
448+
}
348449
if (strpos($templateItem, $placeholder) !== false) {
349450
if (is_string($replacement)) {
350451
$templateItem = str_replace($placeholder, $replacement, $templateItem);

0 commit comments

Comments
 (0)