- Notifications
You must be signed in to change notification settings - Fork25
ZF2 module for automated input validation
License
zfcampus/zf-content-validation
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This repository has moved tolaminas-api-tools/api-tools-content-validation.
Zend Framework module for automating validation of incoming input.
Allows the following:
- Defining named input filters.
- Mapping named input filters to named controller services.
- Returning an
ApiProblemResponsewith validation error messages on invalid input.
Please see thecomposer.json file.
Run the followingcomposer command:
$composer require zfcampus/zf-content-validationAlternately, manually add the following to yourcomposer.json, in therequire section:
"require":{"zfcampus/zf-content-validation":"^1.4"}
And then runcomposer update to ensure the module is installed.
Finally, add the module name to your project'sconfig/application.config.php under themoduleskey:
return [/* ... */'modules' => [/* ... */'ZF\ContentValidation', ],/* ... */];
This module utilizes two user level configuration keyszf-content-validation and alsoinput_filter_specs (named such that this functionality can be moved into ZF2 in the future).
Thezf-content-validation key is a mapping between controller service names as the key, and thevalue being an array of mappings that determine which HTTP method to respond to and what inputfilter to map to for the given request. The keys for the mapping can either be an HTTP method thataccepts a request body (i.e.,POST,PUT,PATCH, orDELETE), or it can be the wordinput_filter. The value assigned for theinput_filter key will be used in the case that no inputfilter is configured for the current HTTP request method.
Example where there is a default as well as a POST filter:
'zf-content-validation' => ['Application\Controller\HelloWorld' => ['input_filter' =>'Application\Controller\HelloWorld\Validator','POST' =>'Application\Controller\HelloWorld\CreationValidator', ],],
In the above example, theApplication\Controller\HelloWorld\Validator service will be selected forPATCH,PUT, orDELETE requests, while theApplication\Controller\HelloWorld\CreationValidatorwill be selected forPOST requests.
Starting in version 1.1.0, two additional keys can be defined to affect application validationbehavior:
use_raw_data: if NOT present, raw data is ALWAYS injected into the "BodyParams" container (definedby zf-content-negotiation). If this key is present and a boolean false, then the validated,filtered data from the input filter will be used instead.allows_only_fields_in_filter: if present, anduse_raw_datais boolean false, the value of thisflag will define whether or not additional fields present in the payload will be merged with thefiltered data.remove_empty_data: Should we remove empty data from received data?- If no
remove_empty_dataflag is present, do nothing - use data as is - If
remove_empty_dataflag is present AND is boolean true, then removeempty data from current data array - Does not remove empty data if keys matched received data
- If no
- Since 1.3.0.
Starting in 1.3.0, you may also specify
GETas an HTTP method, mapping it toan input filter in order to validate your query parameters. Configuration isexactly as described in the above section.This feature is only available when manually configuring your API; it is notexposed in the Admin UI.
- Since 1.5.0
Starting in 1.5.0, you may specify any of:
POST_COLLECTIONPUT_COLLECTIONPATCH_COLLECTIONas keys. These will then be used specifically with the given HTTP method, butonly on requests matching the collection endpoint.
- Since 1.6.0
Starting in 1.6.0, you may specify each of the following keys for inputfilters:
DELETEDELETE_COLLECTIONThe input filter associated with the key will be used to validate data sent inthe request body.
input_filter_spec is for configuration-driven creation of input filters. The keys for this arraywill be a unique name, but more often based off the service name it is mapped to under thezf-content-validation key. The values will be an input filter configuration array, as isdescribed in the ZF2 manualsection on inputfilters.
Example:
'input_filter_specs' => ['Application\Controller\HelloWorldGet' => [0 => ['name' =>'name','required' =>true,'filters' => [0 => ['name' =>'Zend\Filter\StringTrim','options' => [], ], ],'validators' => [],'description' =>'Hello to name','allow_empty' =>false,'continue_if_empty' =>false, ], ],
The following configuration is defined by the module in order to function within a ZF2 application.
namespaceZF\ContentValidation;useZend\InputFiler\InputFilterAbstractServiceFactory;useZend\ServiceManager\Factory\InvokableFactory;return ['controller_plugins' => ['aliases' => ['getinputfilter' =>InputFilter\InputFilterPlugin::class,'getInputfilter' =>InputFilter\InputFilterPlugin::class,'getInputFilter' =>InputFilter\InputFilterPlugin::class, ],'factories' => [InputFilter\InputFilterPlugin::class => InvokableFactory::class, ], ],'input_filters' => ['abstract_factories' => [ InputFilterAbstractServiceFactory::class, ], ],'service_manager' => ['factories' => [ ContentValidationListener::class => ContentValidationListenerFactory::class, ], ],'validators' => ['factories' => ['ZF\ContentValidation\Validator\DbRecordExists' =>Validator\Db\RecordExistsFactory::class,'ZF\ContentValidation\Validator\DbNoRecordExists' =>Validator\Db\NoRecordExistsFactory::class, ], ],];
This listener is attached to theMvcEvent::EVENT_ROUTE event at priority-650. Its purpose isto utilize thezf-content-validation configuration in order to determine if the current request'sselected controller service name has a configured input filter. If it does, it will traverse themappings from the configuration file to create the appropriate input filter (from configuration orthe Zend Framework 2 input filter plugin manager) in order to validate the incoming data. Thisparticular listener utilizes the data from thezf-content-negotiation data container in order toget the deserialized content body parameters.
This event is emitted byZF\ContentValidation\ContentValidationListener::onRoute()(described above) in between aggregating data to validate and determining theinput filter, and the actual validation of data. Its purpose is to allow users:
- the ability to manipulate input filters.
- to modify the data set to validate (available since 1.4.0).
As an example, you might want to validate an identifier provided via the URI,and matched during routing. You may do this as follows:
$events->listen(ContentValidationListener::EVENT_BEFORE_VALIDATE,function ($e) {if ($e->getController() !== MyRestController::class) {return; }$matches =$e->getRouteMatch();$data =$e->getParam('ZF\ContentValidation\ParameterData') ?: [];$data['id'] =$matches->getParam('id');$e->setParam('ZF\ContentValidation\ParameterData',$data);});
This plugin is available to Zend Framework 2 controllers. When invoked ($this->getInputFilter() or$this->plugin('getinputfilter')->__invoke()), it returns whatever is in the MVC event parameterZF\ContentValidation\InputFilter, returning null for any value that is not an implementation ofZend\InputFilter\InputFilter.
This abstract factory is responsible for creating and returning an appropriate input filter givena name and the configuration from the top-level keyinput_filter_specs. It is registered withZend\InputFilter\InputFilterPluginManager.
About
ZF2 module for automated input validation
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.