PHP code example of chubbyphp / chubbyphp-validation

1. Go to this page and download the library: Download chubbyphp/chubbyphp-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chubbyphp / chubbyphp-validation example snippets




namespace MyProject\Model;

final class Model
{
    /**
     * @var array<\DateTime>
     */
    private $dates;
}



namespace MyProject\Mapping\Validation;

use Chubbyphp\Validation\Constraint\AllConstraint;
use Chubbyphp\Validation\Constraint\DateTimeConstraint;
use Chubbyphp\Validation\Constraint\NotBlankConstraint;
use Chubbyphp\Validation\Constraint\NotNullConstraint;
use Chubbyphp\Validation\Mapping\ValidationClassMappingBuilder;
use Chubbyphp\Validation\Mapping\ValidationClassMappingInterface;
use Chubbyphp\Validation\Mapping\ValidationMappingProviderInterface;
use Chubbyphp\Validation\Mapping\ValidationPropertyMappingBuilder;
use Chubbyphp\Validation\Mapping\ValidationPropertyMappingInterface;
use MyProject\Model\Model;

final class ModelValidationMappingProvider implements ValidationMappingProviderInterface
{
    /**
     * @return string
     */
    public function getClass(): string
    {
        return Model::class;
    }

    /**
     * @param string $path
     *
     * @return ValidationClassMappingInterface
     */
    public function getValidationClassMapping(string $path): ValidationClassMappingInterface
    {
        return ValidationClassMappingBuilder::create([])->getMapping();
    }

    /**
     * @param string      $path
     * @param string|null $type
     *
     * @return ValidationPropertyMappingInterface[]
     */
    public function getValidationPropertyMappings(string $path, string $type = null): array
    {
        return [
            ValidationPropertyMappingBuilder::create('dates', [
                new AllConstraint([
                    new NotNullConstraint(),
                    new NotBlankConstraint(),
                    new DateTimeConstraint('d.m.Y'),
                ]),
            ])->getMapping(),
        ];
    }
}



namespace MyProject;

use Chubbyphp\Validation\Mapping\ValidationMappingProviderRegistry;
use Chubbyphp\Validation\ValidatorContextInterface;
use Chubbyphp\Validation\Validator;
use MyProject\Mapping\Validation\ModelValidationMappingProvider;
use MyProject\Model\Model;

$logger = ...;

$validator = new Validator(
    new ValidationMappingProviderRegistry([
        new ModelValidationMappingProvider()
    ]),
    $logger
);

$model = new Model;

/** @var ValidatorContextInterface $context */
$context = ...;

$errors = $validator->validate(
    $model,
    $context
);