Myzwer / foothillschurch

Bootcamp II is a wordpress theme (as well as an inside joke) designed to suit the needs of foothillschurch.com. It makes use of webpack, Babel, Sass, Tailwind, Browsersync, PostCSS, ESLint, Stylelint, Prettier and more. It is meant for that site, but if you can use it by all means go for it.
1 stars 1 forks source link

Type safety #57

Closed rain2o closed 2 weeks ago

rain2o commented 1 month ago

This is an example of having to write a bit more code in order to ensure type safety.

https://github.com/Myzwer/foothillschurch/blob/effc5bbf81497ae99f0561ab7849412fe9272bfd/outreach.php#L66-L67

That code reveals a potential error. Technically, the return type of get_field is mixed, which means it could be anything. And count only accepts either Countable or an array. So, while we know that this particular field should be an array, the error in the screenshot below indicates that it's not safe to assume that.

Screenshot 2024-07-18 at 21 32 28

The safer option would be something like this

// Count how many rows there are, if its more than 1, set it up to use columns.
$count = 1; // we know it's at least 1 since we're in the loop already
$categories = get_field('outreach_category');
if (is_array($categories)) {
    $count = count($categories);
}
$mobile = $count > 1 ? "md:col-span-6" : '';