1.2.125. Check All Types

When checking for type, avoid using else. Mention explicitly all tested types, and raise an exception when all available options have been exhausted : after all, this is when the code doesn’t know how to handle the datatype.

PHP has a short list of scalar types : null, boolean, integer, real, strings, object, resource and array. When a variable is not holding one the the type, then it may be of any other type.

Most of the time, when using a simple is_string() / else test, this is relying on the conception of the code. By construction, the arguments may be one of two types : array or string.

What happens often is that in case of failure in the code (database not working, another class not checking its results), a third type is pushed to the structure, and it ends up breaking the execution.

The safe way is to check the various types all the time, and use the default case (here, the else) to throw exception() or test an assertion and handle the special case. Using is_callable(), is_iterable() with this structure is fine : when variable is callable or not, while a variable is an integer or else.

Using a type test without else is also accepted here. This is a special treatment for this test, and all others are ignored. This aspect may vary depending on situations and projects.

<?php

// hasty version
if (is_array($argument)) {
    $out = $argument;
} else {
    // Here, $argument is NOT an array. What if it is an object ? or a NULL ?
    $out = array($argument);
}

// Safe type checking : do not assume that 'not an array' means that it is the other expected type.
if (is_array($argument)) {
    $out = $argument;
} elseif (is_string($argument)) {
    $out = array($argument);
} else {
    assert(false, '$argument is not an array nor a string, as expected!');
}

?>

1.2.125.1. Suggestions

  • Include a default case to handle all unknown situations

  • Include and process explicit types as much as possible

1.2.125.2. Specs

Short name

Structures/CheckAllTypes

Rulesets

All, Analyze

Exakat since

0.10.6

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Medium

Examples

Zend-Config, Vanilla

Available in

Entreprise Edition, Exakat Cloud