PHP Compatibility Code
PHPCompatibility.Miscellaneous.ValidIntegers.HexNumericStringFound
Recommendation
We manually go through all the occurrences and decide whether it's meant to be used as a simple string or as a number. Replace valid hex numbers with integers or hexdec
, add PHPCodeSniffer exceptions for the false positives.
Example with Integer Replacement
$value = '0xff';
if (is_numeric($value)) {
}
Because the hexadecimal value is hardcoded, it might be simplest to replace it with its hardcoded decimal counterpart.
$value = 255;
if (is_numeric($value)) {
}
Example With hexdec Conversion
$value = $data['hex'];
if (is_numeric($value)) {
}
Since we don't know what the value would be in advance, we would convert it to a decimal first.
$value = hexdec($data['hex']);
if (is_numeric($value)) {
}
However, since we have no guarantee that $data['hex']
is a valid hexadecimal string, a more complete example would look like this. Follow the guide PSR-0 Autoloading to load the Compatibility_Php56
into the legacy project.
final class Compatibility_Php56
{
public static function hexStringToDec($value)
{
if (!preg_match('/^0x[0-9a-fA-F]+$/', $value)) {
return 0;
}
return hexdec($value);
}
}
$value = Compatibility_Php56::hexStringToDec($data['hex']);
if (is_numeric($value)) {
echo $value;
}
We check whether it's a valid hexadecimal string. In PHP 5.6, a string that is not hexadecimal would be converted to zero, so that 1 + 'ff'
would produce 1. If it's a valid hexadecimal string, we convert it to a decimal, so that 1 + '0xff'
would produce 256.
Exclude False Positives
If a string starts with 0x
by pure coincidence, which is extremely rare, then we might just need to add an exception to the phpcs.xml
file that is used in generating the PHP Compatibility report.
<?xml version="1.0"?>
<ruleset>
<rule ref="PHPCompatibility.Miscellaneous.ValidIntegers.HexNumericStringFound">
<exclude-pattern>/path/to/file.php</exclude-pattern>
<exclude-pattern>/path/to/folder/*.php</exclude-pattern>
</rule>
</ruleset>
Migration Services
Increase security and cut risk by simplifying PHP application upgrades and migrations.
Get Long-Term Support With ZendPHP
Stay secure and compliant while migrating on your schedule with Zend PHP LTS.