diff --git a/src/content/daily-email/2023-08-19.md b/src/content/daily-email/2023-08-19.md new file mode 100644 index 00000000..ba451fa7 --- /dev/null +++ b/src/content/daily-email/2023-08-19.md @@ -0,0 +1,43 @@ +--- +title: > + Asserting all the things +pubDate: 2023-08-19 +permalink: > + archive/2023/08/19/asserting-all-the-things +tags: + - php +--- + +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: + +```php +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: + +```php +assert(is_array(false)); +``` + +You can also use an assertion library, such as `webmozart/assert` or `beberlei/assert` which provide assertions and guard methods: + +```php +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.