PHP code example of bugarinov / chain-validation

1. Go to this page and download the library: Download bugarinov/chain-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/ */

    

bugarinov / chain-validation example snippets


class ValidationOne extends AbstractLink
{
    public function evaluate(?array $data): EvaluationResult
    {
        /*
        * Run your validation process here which will
        * set the value of $validationFailed whether
        * the validation failed (true) or not (false)
        */
        if ($validationFailed) {
            return new ResultFailed('your error message here', 400);
        }

        /*
        * If the validation did not fail, return an
        * evaluation result which contains the data
        */
        return new ResultSuccess($data);
    }
}

$chain = new ChainValidation();

$chain->add(new ValidationOne());
$chain->add(new ValidationTwo());
$chain->add(new ValidationThree());
$chain->add(new ValidationFour());

$validatedData = $chain->execute($data);

$validatedData = $chain->execute($data);

if ($chain->hasError()) {
    throw new Exception($chain->getErrorMessage()); // or your preferred way of handling errors e.g. returing a response
}

// Some processes here if the validation succeeds e.g. committing of data to the database
commitToDatabase($validatedData);

    $errorBody = [
        'items_with_error' => [
            [
                'item_uid' => '100012',
                'reason' => 'something went wrong'
            ]
        ]
    ];

    return new ResultFailed('Some items have errors!', 400, $errorBody);

// Example of returning an error response using PSR's ResponseInterface

$validatedData = $chain->execute($data);

if ($chain->hasError()) {

    $payload = [
        'statusCode' => $chain->getErrorCode(),
        'error' => $chain->getErrorMessage(),
        'body' => $chain->getErrorBody()
    ];

    $response->getBody()
        ->write(json_encode($payload));

    return $response->withStatus($error_code)
        ->withHeader('Content-type', 'application/json');
}

class ValidationOne extends AbstractLink
{
    public function execute(?array $data): ?array
    {
        if ($validationFailed) {
            return $this->throwError('your error message here', 400);
        }

        return $this->executeNext($data);
    }
}

class ValidationOne extends AbstractLink
{
    public function evaluate(?array $data): EvaluationResult
    {
        if ($validationFailed) {
            return new ResultFailed('your error message here', 400);
        }

        return new ResultSuccess($data);
    }
}