misantron/bricks

Flexible form builder with data validation and pre processing

v1.0.0 2018-01-29 20:36 UTC

This package is auto-updated.

Last update: 2024-11-29 05:09:44 UTC


README

Build Status Code Coverage Scrutinizer Code Quality Packagist PHP 7 Support

Flexible form builder with data validation and pre processing.

Installation

Run Composer from command line:

composer require misantron/bricks

Or add dependency to composer.json:

{
    "require": {
        "misantron/bricks": "dev-master"
    }
}

Usage

Create a new form by inheriting \Bricks\AbstractForm. Abstract method fields() must be implemented with configuration array:

class SomeForm extends \Bricks\AbstractForm
{
    protected funtion fields(): array
    {
        return [
            'foo' => [
                'type' => 'string', // using for data type cast
                'validators' => [
                    'required' => true,
                    'lengthMax' => 64,
                ],
            ],
            'bar' => [
                'type' => 'integer', // using for data type cast
                'validators' => [
                    'required' => true,
                    'in' => function () {
                        return [1, 2];
                    }
                ],
                'cleanup' => true, // flag that field will be deleted from getData() method call response
            ],
        ];
    }
}

Form workflow inside application controller/service/etc.:

$request = Request::fromGlobals(); // must implements \Psr\Http\Message\RequestInterface

$default = [
    'foo' => 'test',
];

$form = \SomeForm::create()
    ->setData($default) // allows to pass an initial data before handling the request
    ->handleRequest($request) // get data from the request and data processing
    ->validate(); // data validation

$data = $form->getData(); // extracting processed and validated data from form

Built-in field types

string, integer, float, boolean, array (contains elements of different types), dateTime (transform datetime string or timestamp to Carbon object) , intArray, strArray, floatArray

Custom user type can be easily added:

class MyTransducer extends \Bricks\Data\Transducer
{
    private funtion myType($value)
    {
        // your custom logic here
    }
}

Built-in field validation rules

See Valitron documentation. If form data is not valid - \Bricks\Exception\ValidationException will be thrown:

try {
    $form->validate();
} catch (\Bricks\Exception\ValidationException $e) {
    var_dump($e->getData()); // getting fields error data
}