<commit_before>Easy & secure whitelist validation for PHP
==========================================

[![Build Status](https://travis-ci.org/lastzero/php-input-validation.png?branch=master)](https://travis-ci.org/lastzero/php-input-validation)
[![Latest Stable Version](https://poser.pugx.org/lastzero/php-input-validation/v/stable.svg)](https://packagist.org/packages/lastzero/php-input-validation)
[![License](https://poser.pugx.org/lastzero/php-input-validation/license.svg)](https://packagist.org/packages/lastzero/php-input-validation)

This library provides an **abstract form class** with built-in whitelist validation ("accept known good"). It uses **language independent** validation rules (plain array) that can be reused for client-side validation (JavaScript) or passed to template rendering engines such as Twig or Smarty (HTML). The library can be used with **any framework** and **input source** (HTML, REST, RPC, ...).

A major advantage of this modular approach is that developers can use **unit testing** to instantly find bugs and **tune validation rules** without an existing HTML frontend or storage backend. It's perfectly suited to build **REST services**. Use case specific input value validation is also more secure than general model validation, which often relies on a blacklist ("reject known bad").

Besides basic validation rules such as type or length, more advanced features are supported as well - for example **dependent fields**, **internationalization** and **multi-page forms**. Validated values can be fetched individually, as flat array, by tag or by page.

The architecture is **simple by design**: Form classes can inherit their definitions from each other. If needed, the validation behavior can be changed using standard object-oriented methodologies. You don't need to hold a PhD in design patterns to understand how it works.

Basic example
-------------

This example shows how to validate user input in a REST controller action. Note, how easy it is to avoid the deeply nested structures you often find in validation code. User model and form are injected as dependencies. 

```php
class UserController
{
    protected $user;
    protected $form;

    public function __construct(UserModel $user, UserForm $form)
    {
        $this->user = $user;
        $this->form = $form;
    }
    
    public function putAction($id, Request $request) // Update
    {
        $this->user->find($id); // Find entity (throws exception, if not found)
        
        $this->form->setDefinedValues($this->user->getValues()); // Initialization
        $this->form->setDefinedWritableValues($request->request->all()); // Input values
        $this->form->validate(); // Validation

        if($this->form->hasErrors()) {
            throw new FormInvalidException($this->form->getFirstError());
        }
        
        $this->user->update($this->form->getValues()); // Update values

        return $this->user->getValues(); // Return updated entity values
    }
    
    public function optionsAction($id) // Describe form fields for user resource
    {
        $this->user->find($id); // Find entity (throws exception, if not found)
        
        $this->form->setDefinedValues($this->user->getValues()); // Initialization
        
        return $this->form->getAsArray(); // Returns form as JSON compatible array incl all values
    }
}
```

See also [Doctrine ActiveRecord - Object-oriented CRUD for Doctrine DBAL](https://github.com/lastzero/doctrine-active-record)

Form field definition
---------------------
A detailed overview of field properties can be found in the documentation. `$_('label')` is used to translate field captions with `Symfony\Component\Translation\Translator` which supports a number of different translation file formats.

```php
use InputValidation\Form;

class UserForm extends Form
{
    protected function init(array $params = array())
    {
        $definition = [
            'username' => [
                'type' => 'string',
                'caption' => $this->_('username'),
                'required' => true,
                'min' => 3,
                'max' => 15
            ],
            'email' => [
                'type' => 'email',
                'caption' => $this->_('email_address'),
                'required' => true
            ],
            'gender' => [
                'type' => 'string',
                'caption' => $this->_('gender'),
                'required' => false,
                'options' => [
                    'm' => 'Male',
                    'f' => 'Female',
                    'o' => 'Other'<commit_msg>Updated documentation<commit_after>Easy & secure whitelist validation for PHP
==========================================

[![Build Status](https://travis-ci.org/lastzero/php-input-validation.png?branch=master)](https://travis-ci.org/lastzero/php-input-validation)
[![Latest Stable Version](https://poser.pugx.org/lastzero/php-input-validation/v/stable.svg)](https://packagist.org/packages/lastzero/php-input-validation)
[![License](https://poser.pugx.org/lastzero/php-input-validation/license.svg)](https://packagist.org/packages/lastzero/php-input-validation)

This library provides an **abstract form class** with built-in whitelist validation ("accept known good"). It uses **language independent** validation rules (plain array) that can be reused for client-side validation (JavaScript) or passed to template rendering engines such as Twig or Smarty (HTML). The library can be used with **any framework** and **input source** (HTML, REST, RPC, ...).

A major advantage of this modular approach is that developers can use **unit testing** to instantly find bugs and **tune validation rules** without an existing HTML frontend or storage backend. It's perfectly suited to build **REST services**. Use case specific input value validation is also more secure than general model validation, which often relies on a blacklist ("reject known bad").

Besides basic validation rules such as type or length, more advanced features are supported as well - for example **dependent fields**, **internationalization** and **multi-page forms**. Validated values can be fetched individually, as flat array, by tag or by page.

The architecture is **simple by design**: Form classes can inherit their definitions from each other. If needed, the validation behavior can be changed using standard object-oriented methodologies. You don't need to hold a PhD in design patterns to understand how it works.

Basic example
-------------

This example shows how to validate user input in a REST controller action. Note, how easy it is to avoid the deeply nested structures you often find in validation code. User model and form are injected as dependencies. 

```php
class UserController
{
    protected $user;
    protected $form;

    public function __construct(UserModel $user, UserForm $form)
    {
        $this->user = $user;
        $this->form = $form;
    }
    
    public function putAction($id, Request $request) // Update
    {
        $this->user->find($id); // Find entity (throws exception, if not found)
        
        $this->form->setDefinedValues($this->user->getValues()); // Initialization
        $this->form->setDefinedWritableValues($request->request->all()); // Input values
        $this->form->validate(); // Validation

        if($this->form->hasErrors()) {
            throw new FormInvalidException($this->form->getFirstError());
        }
        
        $this->user->update($this->form->getValues()); // Update values

        return $this->user->getValues(); // Return updated entity values
    }
    
    public function optionsAction($id) // Describe form fields for user resource
    {
        $this->user->find($id); // Find entity (throws exception, if not found)
        
        $this->form->setDefinedValues($this->user->getValues()); // Initialization
        
        return $this->form->getAsArray(); // Returns form as JSON compatible array incl all values
    }
}
```

See also [Doctrine ActiveRecord - Object-oriented CRUD for Doctrine DBAL](https://github.com/lastzero/doctrine-active-record)

Form field definition
---------------------
A detailed overview of field properties can be found bellow. `$_('label')` is used to translate field captions with `Symfony\Component\Translation\Translator` which supports a number of different translation file formats such as YAML.

```php
use InputValidation\Form;

class UserForm extends Form
{
    protected function init(array $params = array())
    {
        $definition = [
            'username' => [
                'type' => 'string',
                'caption' => $this->_('username'),
                'required' => true,
                'min' => 3,
                'max' => 15
            ],
            'email' => [
                'type' => 'email',
                'caption' => $this->_('email_address'),
                'required' => true
            ],
            'gender' => [
                'type' => 'string',
                'caption' => $this->_('gender'),
                'required' => false,
                'options' => [
                    'm' => 'Male',
                    'f' => 'Female',
                    'o' => 'Other'
{'fraction_non_alphanumeric': 0.13533672035455627, 'fraction_numerical': 0.0006485785320505892, 'mean_word_length': 2.827885808853951, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 109, 'https://': 14, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '993891', 'n_tokens_mistral': 2356, 'n_tokens_neox': 2257, 'n_words': 833}