jin2chen/form-model

The package helps with implementing data entry forms.

dev-master / 1.0.x-dev 2021-06-16 08:38 UTC

This package is auto-updated.

Last update: 2024-04-10 13:31:17 UTC


README

The package helps with implementing data entry forms.

Build status static analysis Scrutinizer Code Quality Code Coverage

Installation

The package could be installed via composer:

composer require jin2chen/form-model --prefer-dist

Usage

You must create your form model by extending the abstract form class, defining all the private properties with their respective typehint.

Example: LoginForm.php

<?php

declare(strict_types=1);

namespace App\Form;

use jin2chen\FormModel\FormModel;
use Yiisoft\Validator\Rule\Email;
use Yiisoft\Validator\Rule\Required;
use Yiisoft\Validator\Rule\HasLength;
use Yiisoft\Validator\Validator;

class LoginForm extends FormModel
{
    public string $username = '';
    public string $password = '';
    public bool $rememberMe = false;

    /** Add rules */
    public function getRules(): array
    {
        return [
            'login' => $this->loginRules()
        ];
    }

    private function loginRules(): array
    {
        return [
            Required::rule(),
            HasLength::rule()
                ->min(4)
                ->max(40)
                ->tooShortMessage('Is too short.')
                ->tooLongMessage('Is too long.'),
            Email::rule()
        ];
    }
}

$form = new LoginForm();
$validator = new Validator();
$results = $validator->validate($form);
$results->isValid();

Unit testing

The package is tested with PHPUnit. To run tests:

./vendor/bin/phpunit

Static analysis

The code is statically analyzed with Psalm. To run static analysis:

./vendor/bin/psalm