11# Validation
22
3- A validation library for PHP that uses the [ notification pattern] ( https://martinfowler.com/articles/replaceThrowWithNotification.html ) .
3+ A validation library for PHP that uses
4+ the [ notification pattern] ( https://martinfowler.com/articles/replaceThrowWithNotification.html ) .
45
56[ ![ Latest Version on Packagist] ( https://img.shields.io/github/release/selective-php/validation.svg )] ( https://packagist.org/packages/selective/validation )
67[ ![ Software License] ( https://img.shields.io/badge/license-MIT-brightgreen.svg )] ( LICENSE )
@@ -14,11 +15,11 @@ A validation library for PHP that uses the [notification pattern](https://martin
1415* [ Requirements] ( #requirements )
1516* [ Installation] ( #installation )
1617* [ Usage] ( #usage )
17- * [ Validating form data] ( #validating-form-data )
18- * [ Validating JSON] ( #validating-json )
18+ * [ Validating form data] ( #validating-form-data )
19+ * [ Validating JSON] ( #validating-json )
1920* [ Validators] ( #validators )
20- * [ CakePHP Validator] ( #cakephp-validator )
21- * [ Symfony Validator] ( #symfony-validator )
21+ * [ CakePHP Validator] ( #cakephp-validator )
22+ * [ Symfony Validator] ( #symfony-validator )
2223* [ Transformer] ( #transformer )
2324* [ License] ( #license )
2425
@@ -36,8 +37,8 @@ composer require selective/validation
3637
3738> A notification is a collection of errors
3839
39- In order to use a notification, you have to create the ` ValidationResult ` object.
40- A ` ValidationResult ` can be really simple:
40+ In order to use a notification, you have to create the ` ValidationResult ` object. A ` ValidationResult ` can be really
41+ simple:
4142
4243``` php
4344<?php
@@ -97,8 +98,7 @@ if ($validation->fails()) {
9798
9899### Validating JSON
99100
100- Validating a JSON request works like validating form data,
101- because in PHP it's just an array from the request object.
101+ Validating a JSON request works like validating form data, because in PHP it's just an array from the request object.
102102
103103``` php
104104<?php
@@ -128,8 +128,7 @@ $jsonData = (array)json_decode(file_get_contents('php://input'), true);
128128
129129### Middleware
130130
131- The ` ValidationExceptionMiddleware ` PSR-15 middleware catches all exceptions and converts
132- it into a nice JSON response.
131+ The ` ValidationExceptionMiddleware ` PSR-15 middleware catches all exceptions and converts it into a nice JSON response.
133132
134133#### Slim 4 integration
135134
@@ -222,20 +221,19 @@ if ($validation->fails()) {
222221
223222You can combine this library with a validator that is doing the actual validation of your input data.
224223
225- The [ converter pattern] ( https://java-design-patterns.com/patterns/converter/ ) makes it easy to map
226- instances of one class into instances of another class.
224+ The [ converter pattern] ( https://java-design-patterns.com/patterns/converter/ ) makes it easy to map instances of one
225+ class into instances of another class.
227226
228227### CakePHP Validator
229228
230- The [ cakephp/validation] ( https://github.com/cakephp/validation ) library provides features to
231- build validators that can validate arbitrary arrays of data with ease.
229+ The [ cakephp/validation] ( https://github.com/cakephp/validation ) library provides features to build validators that can
230+ validate arbitrary arrays of data with ease.
232231
233- The ` $validator->validate() ` method will return a non-empty array when there are validation failures.
234- The returned array of errors then can be converted into a ` ValidationResult `
232+ The ` $validator->validate() ` method will return a non-empty array when there are validation failures. The returned array
233+ of errors then can be converted into a ` ValidationResult `
235234using the ` CakeValidationErrorCollector ` .
236235
237- For example, if you wanted to validate a contact form before creating and sending
238- an email you could do the following.
236+ For example, if you wanted to validate a contact form before creating and sending an email you could do the following.
239237
240238** Installation**
241239
@@ -245,35 +243,33 @@ composer require cakephp/validation
245243
246244** Usage**
247245
246+ The ` CakeValidationFactory ` class to simplifies the validation handling.
247+ Please note: In real life the ` CakeValidationFactory ` should be injected via constructor.
248+
249+ ** Factory usage**
250+
248251``` php
249- <?php
252+ use Selective\Validation\Factory\CakeValidationFactory;
253+ use Selective\Validation\Exception\ValidationException;
254+ // ...
250255
251- use Cake\Validation\Validator;
252- use Selective\Validation\Converter\CakeValidationConverter ;
256+ // Within the Action class: fetch the request data, e.g. from a JSON request
257+ $data = (array)$request->getParsedBody() ;
253258
254- // Note: This is just an example. Don't use the $request object within the domain layer.
255- $formData = (array)$request->getParsedBody();
259+ // Within the Application Service class: Do the validation
260+ $validationFactory = new CakeValidationFactory();
261+ $validator = $validationFactory->createValidator();
256262
257- // Basic form or json validation
258- $validator = new Validator();
259263$validator
260- ->requirePresence('email')
261- ->email('email', 'E-mail must be valid')
262- ->requirePresence('name')
263- ->notEmpty('name', 'We need your name.')
264- ->requirePresence('comment')
265- ->notEmpty('comment', 'You need to give a comment.');
266-
267- // Convert Cake validator errors to ValidationResult
268- $validationResult = CakeValidationConverter::createValidationResult($validator->validate($formData));
264+ ->notEmptyString('username', 'Input required')
265+ ->notEmptyString('password', 'Input required');
269266
270- // Optional: Do more complex validation and append it to the validation result
271- if ($this->existsUsername($formData['username'])) {
272- $validationResult->addError('username', 'Username is already taken');
273- }
267+ $validationResult = $validationFactory->createValidationResult(
268+ $validator->validate($data)
269+ );
274270
275271if ($validationResult->fails()) {
276- throw new ValidationException('Validation failed. Please check your input. ', $validationResult);
272+ throw new ValidationException('Please check your input', $validationResult);
277273}
278274```
279275
@@ -292,7 +288,6 @@ composer require symfony/validator
292288``` php
293289<?php
294290
295- use Cake\Validation\Validator;
296291use Selective\Validation\Converter\SymfonyValidationConverter;
297292use Selective\Validation\Exception\ValidationException;
298293use Selective\Validation\Regex\ValidationRegex;
@@ -302,7 +297,9 @@ use Symfony\Component\Validator\Validation;
302297// Note: This is just an example. Don't use the $request object within the domain layer.
303298$formData = (array)$request->getParsedBody();
304299
305- // Create a symfony validator instance
300+ // ...
301+
302+ // Create a Symfony validator instance
306303$validator = Validation::createValidator();
307304
308305// Add rules
@@ -356,7 +353,7 @@ if ($validationResult->fails()) {
356353## Transformer
357354
358355If you want to implement a custom response data structure,
359- you can implement a custom transformer against the
356+ you can implement a custom transformer against the
360357` \Selective\Validation\Transformer\ResultTransformerInterface ` interface.
361358
362359** Example**
0 commit comments