-
Notifications
You must be signed in to change notification settings - Fork 0
Description
Summary
Lets quote the php.net documentation
By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.
It is possible to enable strict mode on a per-file basis. In strict mode, only a value corresponding exactly to the type declaration will be accepted, otherwise a TypeError will be thrown. The only exception to this rule is that an int value will pass a float type declaration.
Here i propose to enforce declare(strict_types=1); declaration for every php file under phpcs inspection in projects.
Details about type coercision are explained in the php doc linked below and article at the end of this description.
But here a short example about changes
Code Example
<?php
declare(strict_types=1);
function sum(int $a, int $b): int
{
return $a + $b;
}
# Valid
sum(3, 3);
# Invalid
sum(3, '3'); // Uncaught TypeError: add(): Argument #2 ($b) must be of type int, string given
sum(3, 3.0); // Uncaught TypeError: add(): Argument #2 ($b) must be of type int, float given
sum(3, true); // Uncaught TypeError: add(): Argument #2 ($b) must be of type int, bool givenMigration
The PHPCS rule is shipped with an autofix code that inject the declaration in files (tested and thats ok).
Beside that, many PHPUnit test are broken after the upgrade because of non strict typing, and it will need to spend some time to review and fix (any volunteers ? π )
I'm convinced it worse the try because strict type may help us to write more consistent code and catch bugs early.
It's also a good dropin replacement for static analyzed types by PHPStan.
Rule declaration
<rule ref="SlevomatCodingStandard.TypeHints.DeclareStrictTypes"/>
Resources
Article where the code example came from: https://barryvanveen.nl/blog/50-enforce-strict-type-checking-in-php-with-php-code-sniffer
The rule documentation: https://github.com/slevomat/coding-standard#slevomatcodingstandardtypehintsdeclarestricttypes-