Skip to content

Commit 86f1ec8

Browse files
author
DevT045T
committed
DataTypes class for constants and addParameter method
1 parent 35ffeb2 commit 86f1ec8

File tree

4 files changed

+272
-90
lines changed

4 files changed

+272
-90
lines changed

README.md

Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,58 @@
22

33
## Description
44

5-
This is a lightweight and extendable **PHP-API Framework** designed to help developers quickly build RESTful APIs. It supports common HTTP methods (GET, POST, PUT, DELETE) and provides a standardized JSON response structure. You can also customize the framework’s response wrapper to meet your specific needs.
5+
This is a lightweight and extendable **PHP-API Framework** designed to help developers quickly build RESTful APIs. It provides easy management of API parameters (GET, POST) with support for defining allowed parameters, their required status, and data types. It also allows for flexible response formatting, making it easy to create custom APIs.
66

77
This framework can be easily integrated into any PHP project using Composer.
88

99
## Features
1010

11-
- **Standardized JSON Response**: All responses are returned in JSON format.
12-
- **Custom Response Wrapper**: Allows you to define a custom response structure using a flexible wrapper.
13-
- **Easy API Integration**: Very easy to use and integrate into any PHP project.
11+
- **Standardized API Parameter Handling**: Easily manage allowed API parameters, including data types and required status.
12+
- **Custom Response Wrapper**: Define a custom response structure using a flexible wrapper.
1413
- **Flexible HTTP Method Support**: Supports GET, POST, PUT, DELETE HTTP methods.
1514
- **Meta Data**: The response includes metadata such as response code, server host, number of results, and script execution time.
15+
- **Data Type Management**: Support for defining and managing data types for each parameter.
1616

1717
## Usage
1818

19-
Here is how you can use the `API` class in your project.
19+
Here is how you can use the `API` class along with `APIParameter` in your project.
2020

21-
### Example: Simple API Request
21+
### Example: Define Allowed Parameters and Handle API Request
2222

2323
```php
2424
use devt045t\API;
25+
use devt045t\APIParameter;
26+
use devt045t\DataTypes;
27+
use devt045t\HTTPStatusCodes;
2528

2629
$api = new API();
2730

31+
// Define allowed parameters
32+
$param1 = new APIParameter();
33+
$param1
34+
->setName('username')
35+
->required(true)
36+
->type(DataTypes::STRING);
37+
38+
$param2 = new APIParameter();
39+
$param2
40+
->setName('password')
41+
->required(true)
42+
->type(DataTypes::INT);
43+
44+
// Add parameters to API instance
45+
$api
46+
->addParameter($param1)
47+
->addParameter($param2);
48+
49+
// Retrieve all parameters
50+
$parameters = $api->getAllParameters();
51+
2852
// Set the response data
29-
$api->setResponse(['message' => 'Hello, World!']);
53+
$api->setResponse(['message' => 'Parameters received successfully']);
3054

3155
// Set the custom response code (optional)
32-
$api->setResponseCode(200);
56+
$api->setResponseCode(HTTPStatusCodes::OK);
3357

3458
// Send the response
3559
$api->send();
@@ -48,7 +72,7 @@ The default response wrapper looks like this:
4872
"runtime": 0.02
4973
},
5074
"data": {
51-
"message": "Hello, World!"
75+
"message": "Parameters received successfully"
5276
}
5377
}
5478
```
@@ -67,7 +91,7 @@ $customWrapper = [
6791
];
6892

6993
$api->setCustomWrapper($customWrapper);
70-
$api->setResponse(['message' => 'Hello, World!']);
94+
$api->setResponse(['message' => 'Parameters received successfully']);
7195
$api->send();
7296
```
7397

@@ -82,7 +106,7 @@ The response will be wrapped in the custom format:
82106
"execution_time": 0.02
83107
},
84108
"content": {
85-
"message": "Hello, World!"
109+
"message": "Parameters received successfully"
86110
}
87111
}
88112
```
@@ -98,7 +122,25 @@ The response will be wrapped in the custom format:
98122
- `getAllParameters()`: Returns all given GET and POST parameters as an array.
99123
- `getGETParameters()`: Returns all given GET parameters as an array.
100124
- `getPOSTParameters()`: Returns all given POST parameters as an array.
101-
- `__get(string $property)`: ✨Magic✨ getter method for accessing properties dynamically through the $parameters array. Returns the property’s value or null if not found.
125+
- `__get(string $property)`: ✨Magic✨ getter method for accessing properties dynamically through the `$parameters` array. Returns the property’s value or null if not found.
126+
- `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+
128+
## API Parameter Management
129+
130+
The `APIParameter` class helps you define the parameters for your API. Each parameter can be configured with the following properties:
131+
132+
- **Name**: The name of the parameter (e.g., `username`, `age`).
133+
- **Required**: Whether the parameter is required for the request. Default is `false`.
134+
- **Data Type**: The data type for the parameter (e.g., `string`, `integer`, `boolean`).
135+
136+
### Example of `APIParameter`:
137+
138+
```php
139+
use devt045t\APIParameter;
140+
141+
$param = new APIParameter();
142+
$param->setName('username')->required(true)->type('string');
143+
```
102144

103145
## Configuration Options
104146

@@ -113,8 +155,6 @@ Example of custom wrapper placeholders:
113155

114156
You can use these placeholders to customize the structure of the API response.
115157

116-
---
117-
118158
## License
119159

120160
This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.
@@ -125,4 +165,4 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE)
125165

126166
Feel free to fork this project, make improvements, and submit pull requests. Contributions are always welcome!
127167

128-
---
168+
---

src/API.php

Lines changed: 99 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ class API
2929
*/
3030
public mixed $response;
3131

32-
3332
/**
3433
* The response code that the API returns to the user
3534
* Default is `OK - 200`
@@ -97,6 +96,14 @@ class API
9796
*/
9897
private array $customWrapper;
9998

99+
/**
100+
* @var APIParameter[] An array of allowed API parameters.
101+
*
102+
* This property holds an array of `APIParameter` objects that define the allowed
103+
* parameters for the API request. Each `APIParameter` object includes information
104+
* such as the parameter name, whether it is required, and its expected data type.
105+
*/
106+
private array $allowedParameters = [];
100107

101108
/**
102109
* Constructor that initializes the request method by retrieving it from the server.
@@ -184,79 +191,6 @@ public function send(): void
184191
exit;
185192
}
186193

187-
/**
188-
* Prepares the response wrapper by wrapping the response with metadata.
189-
*
190-
* This method checks if there is any customization for the response wrapper,
191-
* and if not, it uses the default wrapper. It then processes each item in the
192-
* wrapper template, replacing placeholders with actual values.
193-
*
194-
* @return self
195-
*/
196-
protected function prepareResponseWrapper(): self
197-
{
198-
$defaultWrapper = [
199-
"meta" => [
200-
"response_code" => "{{ response_code }}",
201-
"host" => "{{ host }}",
202-
"count" => "{{ count }}",
203-
"runtime" => "{{ runtime }}"
204-
],
205-
"data" => "{{ data }}"
206-
];
207-
208-
$wrapper = $defaultWrapper;
209-
if (isset($this->customWrapper)) {
210-
$wrapper = $this->customWrapper;
211-
}
212-
213-
foreach ($wrapper as $key => $wrappedChild) {
214-
if (is_array($wrappedChild)) {
215-
foreach ($wrappedChild as $childKey => $child) {
216-
$wrapper[$key][$childKey] = $this->parseWrapperTemplate($child);
217-
}
218-
} else {
219-
$wrapper[$key] = $this->parseWrapperTemplate($wrappedChild);
220-
}
221-
}
222-
223-
$this->finalResponse = $wrapper;
224-
225-
return $this;
226-
}
227-
228-
/**
229-
* Parses the wrapper template and replaces placeholders with actual values.
230-
*
231-
* This function replaces placeholders like {{ response_code }}, {{ host }},
232-
* {{ count }}, and {{ runtime }} with their corresponding values from the
233-
* current class context, such as response code, host, count of data, and script runtime.
234-
*
235-
* @param mixed $templateItem The template string containing placeholders.
236-
* @return mixed The parsed string with placeholders replaced by actual values.
237-
*/
238-
private function parseWrapperTemplate(mixed $templateItem): mixed
239-
{
240-
$placeholders = [
241-
"{{ response_code }}" => $this->responseCode,
242-
"{{ host }}" => isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on" ? "https://" : "http://" . $_SERVER["HTTP_HOST"],
243-
"{{ count }}" => is_array($this->response) || is_object($this->response) ? count($this->response) : 0,
244-
"{{ runtime }}" => microtime(true) - $this->scriptStartTime,
245-
"{{ data }}" => $this->response,
246-
];
247-
248-
foreach ($placeholders as $placeholder => $replacement) {
249-
if (strpos($templateItem, $placeholder) !== false) {
250-
if (is_string($replacement)) {
251-
$templateItem = str_replace($placeholder, $replacement, $templateItem);
252-
}
253-
$templateItem = $replacement;
254-
}
255-
}
256-
257-
return $templateItem;
258-
}
259-
260194
/**
261195
* Set the custom wrapper for the response.
262196
*
@@ -330,4 +264,95 @@ public function __get(string $property): mixed
330264
{
331265
return $this->parameters["$property"];
332266
}
267+
268+
/**
269+
* Adds an allowed parameter to the list of allowed API parameters.
270+
*
271+
* This method accepts an `APIParameter` object, which defines the name,
272+
* required status, and data type of a parameter. It adds this parameter
273+
* to the `allowedParameters` array, which is later used to validate incoming
274+
* API requests.
275+
*
276+
* @param APIParameter $parameter The `APIParameter` object to add.
277+
*
278+
* @return self Returns the current instance of the class, allowing for method chaining.
279+
*/
280+
public function addParameter(APIParameter $parameter): self
281+
{
282+
$this->allowedParameters[] = $parameter;
283+
return $this;
284+
}
285+
286+
/**
287+
* Prepares the response wrapper by wrapping the response with metadata.
288+
*
289+
* This method checks if there is any customization for the response wrapper,
290+
* and if not, it uses the default wrapper. It then processes each item in the
291+
* wrapper template, replacing placeholders with actual values.
292+
*
293+
* @return self
294+
*/
295+
protected function prepareResponseWrapper(): self
296+
{
297+
$defaultWrapper = [
298+
"meta" => [
299+
"response_code" => "{{ response_code }}",
300+
"host" => "{{ host }}",
301+
"count" => "{{ count }}",
302+
"runtime" => "{{ runtime }}"
303+
],
304+
"data" => "{{ data }}"
305+
];
306+
307+
$wrapper = $defaultWrapper;
308+
if (isset($this->customWrapper)) {
309+
$wrapper = $this->customWrapper;
310+
}
311+
312+
foreach ($wrapper as $key => $wrappedChild) {
313+
if (is_array($wrappedChild)) {
314+
foreach ($wrappedChild as $childKey => $child) {
315+
$wrapper[$key][$childKey] = $this->parseWrapperTemplate($child);
316+
}
317+
} else {
318+
$wrapper[$key] = $this->parseWrapperTemplate($wrappedChild);
319+
}
320+
}
321+
322+
$this->finalResponse = $wrapper;
323+
324+
return $this;
325+
}
326+
327+
/**
328+
* Parses the wrapper template and replaces placeholders with actual values.
329+
*
330+
* This function replaces placeholders like {{ response_code }}, {{ host }},
331+
* {{ count }}, and {{ runtime }} with their corresponding values from the
332+
* current class context, such as response code, host, count of data, and script runtime.
333+
*
334+
* @param mixed $templateItem The template string containing placeholders.
335+
* @return mixed The parsed string with placeholders replaced by actual values.
336+
*/
337+
private function parseWrapperTemplate(mixed $templateItem): mixed
338+
{
339+
$placeholders = [
340+
"{{ response_code }}" => $this->responseCode,
341+
"{{ host }}" => isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on" ? "https://" : "http://" . $_SERVER["HTTP_HOST"],
342+
"{{ count }}" => is_array($this->response) || is_object($this->response) ? count($this->response) : 0,
343+
"{{ runtime }}" => microtime(true) - $this->scriptStartTime,
344+
"{{ data }}" => $this->response,
345+
];
346+
347+
foreach ($placeholders as $placeholder => $replacement) {
348+
if (strpos($templateItem, $placeholder) !== false) {
349+
if (is_string($replacement)) {
350+
$templateItem = str_replace($placeholder, $replacement, $templateItem);
351+
}
352+
$templateItem = $replacement;
353+
}
354+
}
355+
356+
return $templateItem;
357+
}
333358
}

src/APIParameter.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public function returnMeta(): array
6464
* @param string $property The name of the parameter (e.g., 'user_id', 'email').
6565
* @return self Returns the current instance of the class to allow method chaining.
6666
*/
67-
public function setName(string $property): self
67+
public function name(string $property): self
6868
{
6969
$this->parameterName = $property;
7070
return $this;

0 commit comments

Comments
 (0)