Assertion
The power of Respect\Validation into an assertion library with more than 1.5k assertions.
Install / Use
/learn @Respect/AssertionREADME
Respect\Assertion
The power of [Validation][] into an assertion library.
- More than 1.5k assertions
- Support for custom messages
- Support for custom exceptions
For a complete list of assertions, check all the [mixin interfaces][], and read [Validation][] to understand how each rule/assertion works.
Installation
This package is available on [Packagist][], and you can install it using [Composer][].
composer require respect/assertion
Works on PHP 8.1 or above.
Another assertion library
There are PHP assertion libraries that a lot of people in the PHP the community use:
- [beberlei/assert][]
- [webmozart/assert][]
They are both straightforward to use and have a lot of assertions, so there would be no reason to create yet another one. On the other hand, they have fewer assertions than [Validation][] does.
The main idea of [Validation][] is to make it easy to create chain of validations, but when it can get verbose when you want to make a simple assertion.
This library offers a more straightforward assertion API for [Validation][], which means that you can use all [Validation][]'s rules plus your own rules.
Usage
The examples in the document will assume that this library is available in the
autoload and that the class Respect\Assertion\Assert is imported.
The Assert class can use any rule from [Validation][] with the input as its
first argument:
// will throw an exception => 1 must be equals 5
Assert::equals(1, 5);
// will throw an exception => "string" must be of type integer
Assert::intType('string');
// will not throw an exception
Assert::odd(5);
By default, it throws exceptions that are instances of [ValidationException][], which means you can catch [InvalidArgumentException][] (or [LogicException][]).
Custom messages
The exceptions that Assert throws are the same that [Validation][] throws.
That allows you to customize the error messages using templates:
// will throw an exception => I was expecting 5, but you gave be 1
Assert::equals(1, 5, 'I was expecting {{compareTo}}, but you gave be {{input}}');
Custom exceptions
Instead of throwing [Validation][] exceptions, you can use your exceptions:
// will throw the defined DomainException
Assert::between(42, 1, 10, new DomainException('Something is not right'));
That can be very useful if you want to throw specific exceptions for your application. That was a great idea from [Malukenho][]!
Chained assertions (that())
You can chain assertions using Assert::that($input), which allows you to
perform multiple assertions to the same input with less duplication.
// will throw an exception => I expected a positive number
Assert::that(-1)
->intVal('The number {{input}} must be an integer')
->positive('The number must be positive')
->lessThan(4);
In the example above, as soon as any assertion fails, it will throw an exception. If you wish to chain validations and only check them all simultaneously, we suggest you use the API from [Validation][].
You can also customize a message or exception for the whole chain.
// will throw an exception => The number must be valid
Assert::that(0, new DomainException('The number must be valid'))
->positive()
->greaterThan(5);
// will throw an exception => But it is not greater than 5, though
Assert::that(3, 'The number must be valid')
->positive()
->greaterThan(5, 'But it is not greater than 5, though');
Note that the customization on a specific assertion will overwrite the customization on the whole chain.
You can also apply the effect of the prefixes listed below to the whole chain.
// will throw an exception => 3 (the length of the input) must equal 4
Assert::that(['names' => ['Respect', 'Assertion'], 'options' => [1, 2, 3]])
->all()->arrayType()
->key('names')->allStringType()
->key('options')->lengthEquals(4);
There are also some special methods that allow you to create a chain of assertions.
thatAll(): assert all elements in the input with the subsequent assertions.thatNot(): assert the input inverting the subsequent assertions.thatNullOr(): assert the input if it is notnullwith the subsequent assertions.thatKey(): assert a key from the input with the subsequent assertions.thatProperty(): assert a property from the input with the subsequent assertions.
Prefixes
With Assertion, you can use any [Validation][] rule, but it also allows you to use them with prefixes that simplify some operations.
all*(): asserting all elements in an input
Assertions can be executed with the all prefix which will assert all elements
in the input with the prefixed assertion:
// will throw an exception => "3" (like all items of the input) must be of type integer
Assert::allIntType([1, 2, '3']);
In some cases, you might want to perform multiple assertions to all elements. You
can use thatAll() chain of assertions that will assert all elements in the input
with the subsequent assertions:
// will throw an exception => 3 (like all items of the input) must be between 1 and 2
Assert::thatAll([1, 2, 2, 1, 3])
->intVal()
->between(1, 2);
If you want to perform multiple assertions to all elements, but you also want to
perform other assertions to the input, you can that()->all():
// will throw an exception => 5 (the length of the input) must be less than 4
Assert::that([1, 2, 2, 1, 3])
->arrayType()
->notEmpty()
->lengthGreaterThan(3)
->all()->intVal()->between(1, 2);
nullOr*(): asserting the value of an input or null
Assertions can be executed with the nullOr prefix which will assert only if
the value of the input it not null.
// will throw an exception => 42 must be negative
Assert::nullOrNegative(42);
// will not throw an exception
Assert::nullOrNegative(null);
// will throw an exception => 5 must be between 1 and 4
Assert::nullOrBetween(5, 1, 4);
// will not throw an exception
Assert::nullOrBetween(null, 1, 4);
In some cases, you might want to perform multiple assertions to a value in case
it is not null. In this case, you can use thatNullOr():
// will throw an exception => 6 must be a valid prime number
Assert::thatNullOr(6)
->positive()
->between(1, 10)
->primeNumber();
// will not throw an exception
Assert::thatNullOr(null)
->positive()
->between(1, 10)
->primeNumber();
For convenience, you might also use the that()->nullOr():
Assert::that(6)
->nullOr()->positive()->between(1, 10)->primeNumber();
not*(): inverting assertions
You can execute assertions with the not prefix, which will assert the opposite
of the prefixed assertion:
// will throw an exception => 2 must not be an even number
Assert::notEven(2);
// will throw an exception => 3 must not be in `{ 1, 2, 3, 4 }`
Assert::notIn(3, [1, 2, 3, 4]);
If you need to invert more than a few rules, it might be easier to use thatNot()
and that()->not():
// will throw an exception => "1" must not be positive
Assert::thatNot('1')
->intType()
->positive()
->between(1, 3);
// will throw an exception => "1" must not be positive
Assert::that('1')
->not()->intType()->positive()->between(1, 3);
key*(): asserting a key in an array
You can use keyPresent to check whether a key is present in an array.
// will throw an exception => bar must be present
Assert::keyPresent(['foo' => true], 'bar');
You can use keyNotPresent to check whether a key is present in an array.
// will throw an exception => bar must not be present
Assert::keyNotPresent(['bar' => 2], 'bar');
Also, with the key prefix it will assert the value of the array that contains
the specified key.
// will throw an exception => foo must equal 3
Assert::keyEquals(['foo' => 2], 'foo', 3);
// will throw an exception => bar must be negative
Assert::keyNegative(['bar' => 2], 'bar');
// will throw an exception => bar must not be of type integer
Assert::keyNotIntType(['bar' => 2], 'bar');
// will throw an exception => baz must be present
Assert::keyNegative(['foo' => 2], 'baz');
// will throw an exception => foo must exist
Assert::keyExists(['foo' => '/path/to/file.txt'], 'foo');
Not that keyExists assertion, will assert whether the value of key foo exists
in the Filesystem.
If you want to perform multiple assertions to the key of an input, you can use
thatKey():
// will throw an exception => 9 (the length of the input) must be less than 4
Assert::thatKey(['foo' => 'my-string'], 'foo')
->stringType()
->startsWith('my-')
->lengthLessThan(4);
If you want to perform multiple key assertions to the same input, you can use
that()->key():
// will throw an exception => bar must be less than 40
Assert::that(['foo' => 'my-string', 'bar' => 42])
->arrayType()
->key('foo')->stringType()->startsWith('my-')
->key('bar')->intType()->positive()->lessThan(40);
