PHP code example of marcosh / php-validation-dsl

1. Go to this page and download the library: Download marcosh/php-validation-dsl 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/ */

    

marcosh / php-validation-dsl example snippets


interface Validation
{
    public function validate($data): ValidationResult;
}

class CheckDuplicateExceptCurrentRecord
{
    private $recordRepository;
    
    public function __construct($recordRepository)
    {
        $this->recordRepository = $recordRepository;
    }

    public function validate($data, $context)
    {
        if ($recordRepository->containsDataExcludingRecord($data, $context['id'])) {
            return ValidationResult::errors(['DUPLICATE RECORD']);
        }
        
        return ValidationResult::valid($data);
    }
}

$validator = new CheckDuplicateExceptCurrentRecord($recordRepository);

$validator->validate($data, ['id' => $currentRecordId]);

public static function withClassNameAndFormatter(
    string $className,
    callable $errorFormatter
):

$myValidator = IsInstanceOf::withClassNameAndFormatter(
    Foo::class,
    function ($className, $data) {
        return [
            sprintf(
                'The data %s is not an instance of %s',
                json_encode($data),
                $className
            )
        ];
    }
);

[
    'name' => ... // non empty string
    'age' => ... // non-negative integer
]

Sequence::validations([
    new IsArray(),
    All::validations([
        Sequence::validations([
            HasKey::withKey('name'),
            Focus::on(
                function ($data) {
                    return $data['name'];
                },
                Sequence::validations([
                    new IsString(),
                    new NonEmpty()
                ])
            )
        ]),
        Sequence::validations([
            HasKey::withKey('age'),
            Focus::on(
                function ($data) {
                    return $data['age'];
                },
                Sequence::validations([
                    new IsInteger(),
                    IsGreaterThan::withBound(0)
                ])
            )
        ])
    ])
]);

Associative::validations([
    'name' => Sequence::validations([
        new IsString(),
        new NonEmpty()
    ]),
    'age' => Sequence::validations([
        new IsInteger(),
        IsGreaterThan::withBound(0)
    ])
]);