eureka/component-validation

PHP validation library.

5.3.0 2024-02-06 16:57 UTC

This package is auto-updated.

Last update: 2024-04-06 17:18:06 UTC


README

Current version Supported PHP version CI Quality Gate Status Coverage

Validation Component

Usage

Validator Factory

Validation component use php native filter_var() to validate contents. Please refer to Validate filters and filter_var() for more information about options & flags.

<?php

use Eureka\Component\Validation\ValidatorFactory;

$factory = new ValidatorFactory();

$string = 'message';

$validatedString = $factory->getValidator('string')->validate($string);
$validatedEmail  = $factory->getValidator('email')->validate('test@example.com');
//...

Generic Entity

Validation component could be used to validate form. But to avoid set an invalid domain entity (a domain Entity should always be complete and valid), you can use generic entity factory.

This factory can create a pseudo entity with auto validation, and create or update a domain Entity only if the generic entity is valid.

<?php

use Eureka\Component\Validation\Entity\ValidatorEntityFactory;
use Eureka\Component\Validation\ValidatorFactory;
use Eureka\Component\Validation\Validator\IntegerValidator;

//~ Key as formatted in PascalCase in generic entity
$formData = [
    'userId'     => 1,
    'userName'   => 'Romain',
    'user_email' => 'test@example.com',
    'IsEnabled'  => true,
];

//~ Key as formatted in PascalCase in generic entity also for the config 
$validatorConfig = [
    'user_id'   => ['type' => 'integer', 'options' => IntegerValidator::INT_UNSIGNED],
    'UserEmail' => ['type' => 'email'],
];

$entityFactory = new ValidatorEntityFactory(new ValidatorFactory());
$formEntity = $entityFactory->createGeneric($validatorConfig, $formData);

if (!$formEntity->isValid()) {
    throw new \RuntimeException(implode("\n", $formEntity->getErrors()));
}

$user = new User();
$user->setId($formEntity->getUserId());
$user->setName($formEntity->getUserName());
$user->setEmail($formEntity->getUserEmail());
$user->setIsEnabled($formEntity->isEnabled());

// and persist user in database

Composer

composer require "eureka/component-validation"

Installation

You can install the component (for testing) with the following command:

make install

Update

You can update the component (for testing) with the following command:

make update

Testing

You can test the component with the following commands:

make phpcs
make tests
make testdox