Using assert to fix PHPStan errors

A Web Developer based in Belgium, specialized in PHP & JS development
Search for a command to run...

A Web Developer based in Belgium, specialized in PHP & JS development
No comments yet. Be the first to comment.
I recently needed to collect all changes in one file for reporting purposes. Found this article: https://ratfactor.com/cards/git-diff-with-new-files In case you need something similar on Windows, here

Some projects start with a grand plan. Others start because you just need to read a file without thinking too much about it. That was the case for spread-compat. I needed a common interface for CSV, X

With modern css, you can almost get rid of sass. But there is one last pain point : media queries. Not being able to use variables or an easy, common syntax for typical breakpoints is really annoying. That is, until you meet Media Queries Level 5. I’...

This is a quick article to share this demo I just made. https://codepen.io/lekoalabe/pen/JoPNWpX

Modals are typical UI elements for many web apps. There are countless packages dedicated to that specific features, each framework creating its own variation. Popular frameworks like Bootstrap also have custom code to deal with it. But all this feels...

I’ve been using more and more PHPStan recently and it’s been a real pleasure to improve my codebases.
Being strict is nice, but sometimes it can also be inconvenient. A lot of built-in methods in php can return false. Or sometimes, you have a “mixed” result even though you know for sure it’s type.
Let’s say you have something like this:
<?php
function stringOrArray():string|array {
$v = someMethodThatReturnMixed();
return $v;
}
Of course, you can do this:
function stringOrArray():string|array {
$v = someMethodThatReturnMixed();
if(is_string($v) || is_array($v)) {
return $v;
}
throw new Exception("Invalid type");
}
But this means adding an if. Throwing an Exception. Not a big deal by itself, but if you have to fix hundreds of lines like this, it’s not great.
A quick(er) fix, is this:
function stringOrArray():string|array {
$v = someMethodThatReturnMixed();
assert(is_string($v)||is_array($v));
return $v;
}
Aaaaand… done! I really like using assert : it adds type checks during development, and is ignored at no performance cost in production. And if somehow, as a developer, you made a mistake, it’s very likely you are going to catch the AssertionException that gets thrown.
That’s all for today, I hope you liked my little tip :)