From 40ff4dd17ed0fd1ba3932ae9c2d9ace89831b17c Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Mon, 21 Aug 2023 20:54:27 +0100 Subject: [PATCH] daily-email: add 2023-08-20 PHP types and assertions --- src/content/daily-email/2023-08-20.md | 57 +++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/content/daily-email/2023-08-20.md diff --git a/src/content/daily-email/2023-08-20.md b/src/content/daily-email/2023-08-20.md new file mode 100644 index 00000000..8b787b71 --- /dev/null +++ b/src/content/daily-email/2023-08-20.md @@ -0,0 +1,57 @@ +--- +title: > + PHP types and assertions +pubDate: 2023-08-20 +permalink: > + archive/2023/08/20/php-types-and-assertions +tags: + - php +--- + +Following yesterday's email about input validation, guard clauses and assertion libraries, these can be used to compliment PHP's native types and checking. + +For example: + +```php +function createJourney(string $from, string $to, int $duration): void { + var_dump($from, $to, $duration); +} +``` + +In this code, each parameter has a type, but there's no validation on the values. + +If I run this: + +```plain +createJourney('', '', -10); +``` + +I would get this output: + +```plain +string(0) "" +string(0) "" +int(-10) +``` + +This is probably not what you want. + +I expect `$to` and `$from` to be not empty and the duration to be greater than zero. + +## Here's the thing + +I can use an assertion library or throw my own Exceptions if the values pass the type checks but aren't what I need. + +For example: + +```php +function createJourney(string $from, string $to, int $duration): void { + Assert::stringNotEmpty($from); + Assert::stringNotEmpty($to); + Assert::positiveInteger($duration); + + var_dump($from, $to, $duration); +} +``` + +Now, if an empty string or negative duration is passed - in my implementation or test code - an Exception will be thrown.