As well as assertions within tests, you can also check within implementation code that things are in an expected state or contain a certain value.
In PHP, this is done by throwing an Exception if a condition is met.
For example:
if (!is_array(false)) {
throw new \Exception('Not an array');
}
There's also the assert construct which, since PHP 8.0, throws an Exception by default:
assert(is_array(false));
You can also use an assertion library, such as webmozart/assert or beberlei/assert which provide assertions and guard methods:
use Webmozart\Assert\Assert;
Assert::isArray(false);
Similarly, if the condition fails, it throws an Exception that can be caught elsewhere.
As well as basic assertions such as the item is the expected type or don't match the condition, there are more complex assertions, such as all items within an array are a certain type or that an integer is positive.
Here's the thing
I use guard conditions a lot within my code. If something is not as I'd expect, I like for an error to be thrown. This makes is easy to test and to debug any failures compared to failing silently.
- Oliver
Was this interesting?
About me
I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.