An extensible assertion library for PHP using the Composite pattern.
This library provides a simple and extensible way to perform assertions in your PHP projects. It is designed with a focus on extensibility, allowing you to create your own custom assertion logic with minimal effort.
You can install the package via Composer:
composer require esposimo/assertionThe library is designed to be intuitive and flexible. Here are some examples of how to use it.
Each assertion is a class that can be instantiated and then validated.
use Esposimo\Assertion\Compare\EqualAssertion;
use Esposimo\Assertion\Types\IsStringAssertion;
$assertion = new EqualAssertion(5, 5);
var_dump($assertion->isValid()); // bool(true)
$assertion = new IsStringAssertion("hello");
var_dump($assertion->isValid()); // bool(true)You can combine multiple assertions using AndConjunction and OrConjunction.
use Esposimo\Assertion\AndConjunction;
use Esposimo\Assertion\Compare\GreaterThanAssertion;
use Esposimo\Assertion\Types\IsIntAssertion;
$value = 10;
$assertion = new AndConjunction([
new IsIntAssertion($value),
new GreaterThanAssertion($value, 5)
]);
var_dump($assertion->isValid()); // bool(true)You can negate any assertion using the NotAssertion class.
use Esposimo\Assertion\NotAssertion;
use Esposimo\Assertion\Types\IsNullAssertion;
$assertion = new NotAssertion(new IsNullAssertion(null));
var_dump($assertion->isValid()); // bool(false)Creating a new assertion is as simple as extending the ´AbstractAssert´ class and implementing the `assert() method.
use Esposimo\Assertion\AbstractAssert;
class IsPositiveNumberAssertion extends AbstractAssert
{
protected function assert(): void
{
$this->check = is_numeric($this->firstOperand) && $this->firstOperand > 0;
}
}
$assertion = new IsPositiveNumberAssertion(10);
var_dump($assertion->isValid()); // bool(true)
$assertion = new IsPositiveNumberAssertion(-5);
var_dump($assertion->isValid()); // bool(false)Here is a list of the assertions available out of the box:
Contributions are welcome! Please feel free to submit a pull request or open an issue.
The MIT License (MIT). Please see LICENSE for more information.