PHPackages                             bugarinov/chain-validation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. bugarinov/chain-validation

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

bugarinov/chain-validation
==========================

Classes which implements the Chain of Responsibility pattern in validating data. Intended primary use is for handling complex validations.

v0.2.2(1y ago)035MITPHPPHP ^7.2 || ^8.0

Since Feb 20Pushed 1y ago1 watchersCompare

[ Source](https://github.com/bugarinov/chain-validation)[ Packagist](https://packagist.org/packages/bugarinov/chain-validation)[ RSS](/packages/bugarinov-chain-validation/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (1)Versions (6)Used By (0)

Chain Validation
================

[](#chain-validation)

Notice:
-------

[](#notice)

The latest build is 0.2.x and **is not backwards compatible** with 0.1.x versions. See *Migration* for details.
Alternatively, you can read [0.1.x-README.md](https://github.com/bugarinov/chain-validation/blob/master/0.1.x-README.md) for versions 0.1.x.

**Chain Validation** is a simple PHP library for handling very complex validations that goes beyond checking of data types, format and values of a given data. It uses the *Chain of Responsibility* design pattern in order to execute each validation in a consecutive manner. The execution will stop once an error occured during the validation process within a link. You can alter the data as it goes through the chain, depending on your requirements.

Usage
=====

[](#usage)

### Defining and executing validations

[](#defining-and-executing-validations)

Usage is simple. First, group your validations by purpose/relevance and create a new class for each validation group which extends the `AbstractLink` class.

```
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);
    }
}
```

You can run the validations using the `ChainValidation` class. The chain process each validation in exact order or in *First in, First out* manner.

```
$chain = new ChainValidation();

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

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

### Catching errors

[](#catching-errors)

To know whether an error occured or not, you can use the `hasError()` function of the `ChainValidation` class and get the error message using the `getErrorMessage()` function after the validation execution. You can get the corresponding error code using the `getErrorCode()` function.

```
$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);
```

If the chain validation succeeds, it will return the **validated data**, otherwise it will return `null`.

### Errors with a body

[](#errors-with-a-body)

There are instances where errors messages are not enough, especially on front-end applications that highlight specific errors on their UI. Hence, a new parameter was added to the constructor of the `ResultFailed` class in order to pass the this data to the chain.

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

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

The error data can be obtained through the `getErrorBody()` function of the `ChainValidation` class and `LinkInterface` implementations.

```
// 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');
}
```

Migration from 0.1.x to 0.2.x
=============================

[](#migration-from-01x-to-02x)

In order to migrate from 0.1.x to 0.2.x, you just need to replace the `execute` function on each link with the `evaluate` function.

From **v0.1.x**

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

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

to **v0.2.x**

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

        return new ResultSuccess($data);
    }
}
```

Tests
=====

[](#tests)

Run the tests using `composer test`.

[Tests](https://github.com/bugarinov/chain-validation/blob/master/tests/WithMockingTest.php) with mocking of `Link`'s `evaluate` function are added.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~330 days

Total

5

Last Release

594d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/889ffd57550d82fc27966cc2df89932cf7e80c4d2f91c2ed80e79078bca7f81a?d=identicon)[bugarinov](/maintainers/bugarinov)

---

Top Contributors

[![bugarinov](https://avatars.githubusercontent.com/u/31126082?v=4)](https://github.com/bugarinov "bugarinov (52 commits)")

---

Tags

complex-validationvalidation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/bugarinov-chain-validation/health.svg)

```
[![Health](https://phpackages.com/badges/bugarinov-chain-validation/health.svg)](https://phpackages.com/packages/bugarinov-chain-validation)
```

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
