Skip to content

Commit 73d74a6

Browse files
initial commit of PHP Validator
0 parents  commit 73d74a6

20 files changed

+1336
-0
lines changed

Diff for: .gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/vendor/
2+
/.idea/

Diff for: LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2022 F. Michel
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

Diff for: README.md

+287
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
1+
2+
# PHP Validator
3+
4+
PHP Validator is a fast, extensible, and simple PHP validation library that allows you to easily validate various types of data.
5+
6+
## Installation
7+
8+
You can install this library via [Composer](https://getcomposer.org/). Ensure your project meets the minimum PHP version requirement of 7.4.
9+
10+
```bash
11+
composer require phpdevcommunity/php-validator
12+
```
13+
14+
## Requirements
15+
16+
- PHP version 7.4 or higher
17+
- Required package for PSR-7 HTTP Message (e.g., `guzzlehttp/psr7`)
18+
19+
## Usage
20+
21+
The PHP Validator library enables you to validate data in a simple and flexible manner using pre-configured validation rules. Here are some usage examples:
22+
23+
### Example 1: Email Address Validation
24+
25+
Validate an email address to ensure it is not null and matches the standard email format.
26+
27+
```php
28+
use PhpDevCommunity\Validator\Validation;
29+
use PhpDevCommunity\Validator\Rules\NotNull;
30+
use PhpDevCommunity\Validator\Rules\Email;
31+
32+
// Instantiate Validation object for email validation
33+
$validation = new Validation([
34+
'email' => [new NotNull(), new Email()]
35+
]);
36+
37+
// Example data array
38+
$data = ['email' => '[email protected]'];
39+
40+
// Validate the data
41+
if ($validation->validateArray($data) === true) {
42+
echo "Email is valid!";
43+
} else {
44+
$errors = $validation->getErrors();
45+
echo "Validation errors: " . implode(", ", $errors['email']);
46+
}
47+
```
48+
49+
### Example 2: Age Validation
50+
51+
Validate the age to ensure it is a non-null integer and is 18 or older.
52+
53+
```php
54+
use PhpDevCommunity\Validator\Validation;
55+
use PhpDevCommunity\Validator\Rules\NotNull;
56+
use PhpDevCommunity\Validator\Rules\Integer;
57+
58+
// Instantiate Validation object for age validation
59+
$validation = new Validation([
60+
'age' => [new NotNull(), new Integer(['min' => 18])]
61+
]);
62+
63+
// Example data array
64+
$data = ['age' => 25];
65+
66+
// Validate the data
67+
if ($validation->validateArray($data) === true) {
68+
echo "Age is valid!";
69+
} else {
70+
$errors = $validation->getErrors();
71+
echo "Validation errors: " . implode(", ", $errors['age']);
72+
}
73+
```
74+
75+
### Additional Examples
76+
77+
Let's explore more examples covering various validators:
78+
79+
#### Username Validation
80+
81+
Ensure that a username is not null, has a minimum length of 3 characters, and contains only alphanumeric characters.
82+
83+
```php
84+
use PhpDevCommunity\Validator\Validation;
85+
use PhpDevCommunity\Validator\Rules\NotNull;
86+
use PhpDevCommunity\Validator\Rules\Alphanumeric;
87+
use PhpDevCommunity\Validator\Rules\StringLength;
88+
89+
// Instantiate Validation object for username validation
90+
$validation = new Validation([
91+
'username' => [new NotNull(), new StringLength(['min' => 3]), new Alphanumeric()]
92+
]);
93+
94+
// Example data array
95+
$data = ['username' => 'john_doe123'];
96+
97+
// Validate the data
98+
if ($validation->validateArray($data) === true) {
99+
echo "Username is valid!";
100+
} else {
101+
$errors = $validation->getErrors();
102+
echo "Validation errors: " . implode(", ", $errors['username']);
103+
}
104+
```
105+
106+
#### URL Validation
107+
108+
Validate a URL to ensure it is not null and is a valid URL format.
109+
110+
```php
111+
use PhpDevCommunity\Validator\Validation;
112+
use PhpDevCommunity\Validator\Rules\NotNull;
113+
use PhpDevCommunity\Validator\Rules\Url;
114+
115+
// Instantiate Validation object for URL validation
116+
$validation = new Validation([
117+
'website' => [new NotNull(), new Url()]
118+
]);
119+
120+
// Example data array
121+
$data = ['website' => 'https://example.com'];
122+
123+
// Validate the data
124+
if ($validation->validateArray($data) === true) {
125+
echo "Website URL is valid!";
126+
} else {
127+
$errors = $validation->getErrors();
128+
echo "Validation errors: " . implode(", ", $errors['website']);
129+
}
130+
```
131+
132+
#### Numeric Value Validation
133+
134+
Validate a numeric value to ensure it is not null and represents a valid numeric value.
135+
136+
```php
137+
use PhpDevCommunity\Validator\Validation;
138+
use PhpDevCommunity\Validator\Rules\NotNull;
139+
use PhpDevCommunity\Validator\Rules\Numeric;
140+
141+
// Instantiate Validation object for numeric value validation
142+
$validation = new Validation([
143+
'price' => [new NotNull(), new Numeric()]
144+
]);
145+
146+
// Example data array
147+
$data = ['price' => 99.99];
148+
149+
// Validate the data
150+
if ($validation->validateArray($data) === true) {
151+
echo "Price is valid!";
152+
} else {
153+
$errors = $validation->getErrors();
154+
echo "Validation errors: " . implode(", ", $errors['price']);
155+
}
156+
```
157+
158+
#### Custom Validation Rule
159+
160+
Implement a custom validation rule using a callback function.
161+
162+
```php
163+
use PhpDevCommunity\Validator\Validation;
164+
use PhpDevCommunity\Validator\Rules\NotNull;
165+
use PhpDevCommunity\Validator\Rules\Custom;
166+
167+
// Custom validation function to check if the value is a boolean
168+
$isBoolean = function ($value) {
169+
return is_bool($value);
170+
};
171+
172+
// Instantiate Validation object with a custom validation rule
173+
$validation = new Validation([
174+
'active' => [new NotNull(), new Custom($isBoolean)]
175+
]);
176+
177+
// Example data array
178+
$data = ['active' => true];
179+
180+
// Validate the data
181+
if ($validation->validateArray($data) === true) {
182+
echo "Value is valid!";
183+
} else {
184+
$errors = $validation->getErrors();
185+
echo "Validation errors: " . implode(", ", $errors['active']);
186+
}
187+
```
188+
189+
Certainly! Below is a chapter you can add to your README specifically covering examples for using the `validate(ServerRequestInterface $request)` method from your `Validation` class.
190+
191+
## Using `validate(ServerRequestInterface $request)` Method
192+
193+
The `Validation` class provides a convenient method `validate(ServerRequestInterface $request)` to validate data extracted from a `\Psr\Http\Message\ServerRequestInterface` object. This method simplifies the process of validating request data typically received in a web application.
194+
195+
### Example 1: Validating User Registration Form
196+
197+
Suppose you have a user registration form with fields like `username`, `email`, `password`, and `age`. Here's how you can use the `validate` method to validate this form data:
198+
199+
```php
200+
use PhpDevCommunity\Validator\Validation;
201+
use PhpDevCommunity\Validator\Rules\NotNull;
202+
use PhpDevCommunity\Validator\Rules\Email;
203+
use PhpDevCommunity\Validator\Rules\Integer;
204+
205+
// Define validation rules for each field
206+
$validation = new Validation([
207+
'username' => [new NotNull()],
208+
'email' => [new NotNull(), new Email()],
209+
'password' => [new NotNull()],
210+
'age' => [new NotNull(), new Integer()]
211+
]);
212+
213+
// Assume $request is the \Psr\Http\Message\ServerRequestInterface object containing form data
214+
if ($validation->validate($request) === true) {
215+
// Validation passed, retrieve validated data
216+
$validatedData = $validation->getData();
217+
// Process registration logic here (e.g., save to database)
218+
// $username = $validatedData['username'];
219+
// $email = $validatedData['email'];
220+
// $password = $validatedData['password'];
221+
// $age = $validatedData['age'];
222+
echo "Registration successful!";
223+
} else {
224+
// Validation failed, retrieve validation errors
225+
$errors = $validation->getErrors();
226+
// Handle validation errors (e.g., display error messages to the user)
227+
echo "Validation errors: " . implode(", ", $errors);
228+
}
229+
```
230+
231+
In this example:
232+
- We instantiate a `Validation` object with validation rules defined for each field (`username`, `email`, `password`, `age`).
233+
- We call the `validate` method with the `$request` object containing form data.
234+
- If validation passes (`validate` method returns `true`), we retrieve the validated data using `$validation->getData()` and proceed with the registration logic.
235+
- If validation fails, we retrieve the validation errors using `$validation->getErrors()` and handle them accordingly.
236+
237+
### Example 2: Validating API Input Data
238+
239+
Consider validating input data received via an API endpoint. Here's how you can use the `validate` method in this context:
240+
241+
```php
242+
use PhpDevCommunity\Validator\Validation;
243+
use PhpDevCommunity\Validator\Rules\NotNull;
244+
use PhpDevCommunity\Validator\Rules\Numeric;
245+
246+
// Define validation rules for API input data
247+
$validation = new Validation([
248+
'product_id' => [new NotNull(), new Numeric()],
249+
'quantity' => [new NotNull(), new Numeric()]
250+
]);
251+
252+
// Assume $request is the \Psr\Http\Message\ServerRequestInterface object containing API input data
253+
if ($validation->validate($request) === true) {
254+
// Validation passed, proceed with processing API request
255+
$validatedData = $validation->getData();
256+
// Extract validated data
257+
$productId = $validatedData['product_id'];
258+
$quantity = $validatedData['quantity'];
259+
echo "API request validated successfully!";
260+
} else {
261+
// Validation failed, retrieve validation errors
262+
$errors = $validation->getErrors();
263+
// Handle validation errors (e.g., return error response to the client)
264+
echo "Validation errors: " . implode(", ", $errors);
265+
}
266+
```
267+
268+
In this example:
269+
- We define validation rules for `product_id` and `quantity`.
270+
- We call the `validate` method with the `$request` object containing API input data.
271+
- If validation passes, we retrieve the validated data using `$validation->getData()` and proceed with processing the API request.
272+
- If validation fails, we retrieve the validation errors using `$validation->getErrors()` and handle them appropriately.
273+
274+
---
275+
276+
### Additional Features
277+
278+
- **Simple Interface**: Easily define validation rules using a straightforward interface.
279+
- **Extensible**: Extend the library with custom validation rules by implementing the `RuleInterface`.
280+
- **Error Handling**: Retrieve detailed validation errors for each field.
281+
282+
---
283+
284+
## License
285+
286+
This library is open-source software licensed under the [MIT license](LICENSE).
287+

Diff for: composer.json

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"name": "phpdevcommunity/php-validator",
3+
"description": "PHP Validator is a fast, extensible, and simple PHP validation library that allows you to easily validate various types of data.",
4+
"type": "library",
5+
"license": "MIT",
6+
"authors": [
7+
{
8+
"name": "F. Michel",
9+
"homepage": "https://www.phpdevcommunity.com"
10+
}
11+
],
12+
"autoload": {
13+
"psr-4": {
14+
"PhpDevCommunity\\Validator\\": "src",
15+
"Test\\PhpDevCommunity\\Validator\\": "tests"
16+
}
17+
},
18+
"minimum-stability": "alpha",
19+
"require": {
20+
"php": ">=7.4",
21+
"psr/http-message": "^1.0|^2.0",
22+
"ext-json": "*",
23+
"ext-ctype": "*"
24+
},
25+
"require-dev": {
26+
"phpdevcommunity/unitester": "^0.1.0@alpha"
27+
}
28+
}

Diff for: src/Assert/AbstractValidator.php

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
namespace PhpDevCommunity\Validator\Assert;
4+
5+
/**
6+
* Class AbstractValidator
7+
*
8+
* This abstract class implements the ValidatorInterface and provides basic error handling functionality.
9+
*/
10+
abstract class AbstractValidator implements ValidatorInterface
11+
{
12+
protected ?string $error = null;
13+
14+
/**
15+
* Get the error message
16+
*
17+
* @return string|null
18+
*/
19+
public function getError(): ?string
20+
{
21+
return $this->error;
22+
}
23+
24+
25+
/**
26+
* Set the error message by replacing placeholders with values from the context array
27+
*
28+
* @param string $message The error message with placeholders
29+
* @param array $context An associative array containing values to replace the placeholders
30+
* @return void
31+
*/
32+
protected function error(string $message, array $context): void
33+
{
34+
$replace = [];
35+
foreach ($context as $key => $value) {
36+
if (is_object($value)) {
37+
$value = method_exists($value, '__toString') ? (string)$value : get_class($value);
38+
} elseif (is_array($value)) {
39+
$value = json_encode($value);
40+
} else {
41+
$value = (string)$value;
42+
}
43+
$replace['{{ ' . $key . ' }}'] = $value;
44+
}
45+
46+
$this->error = strtr($message, $replace);
47+
}
48+
}

0 commit comments

Comments
 (0)