-
-
Notifications
You must be signed in to change notification settings - Fork 522
Description
I'm just now going through the handbook again to update the WP-Core ruleset documentation to be in line and noticed a code example which triggered me:
In the Space Usage section: https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#space-usage
When type casting, do it like so:
foreach ( (array) $foo as $bar ) { ...
$foo = (boolean) $bar;
I would have expected the second example to read: $foo = (bool) $bar;.
While it is not a formal rule, previous art in WordPress Core suggests that it is indeed a convention to always use the short form of type casts - i.e. (bool) not (boolean) and (int) not (integer) and to prefer (float) over (double) or (real).
Metrics based on WP Core trunk
Typecast encountered:
(int) => 862 ( 42.44%)
(array) => 673 ( 33.14%)
(object) => 220 ( 10.83%)
(bool) => 142 ( 6.99%)
(string) => 123 ( 6.06%)
(float) => 10 ( 0.49%)
(boolean) => 1 ( 0.05%)
-----------------------------
total => 2,031 (100.00%)
Handbook change proposal
I would like to suggest adding the following to the WP Core handbook:
"Type casts must be lowercase. Always prefer the short form of type casts, (int) instead of (integer) and (bool) rather than (boolean). For float casts use (float).".
Where necessary, example code, like shown above should be adjusted to comply.
/cc @pento
WPCS implications
As for sniffs, there are a few candidates which come close, but writing a WPCS native sniff for this shouldn't be difficult either.
PHPCS 3.3.0 introduced the Generic.PHP.LowerCaseType sniff which verifies the case used in type casts, but also for function declaration parameter and return types, including an auto-fixer.
PHPCS 3.3.0 also introduced the PSR12.Keywords.ShortFormTypeKeywords sniff which throws errors for the long form type casts and can auto-fix these, but does not handle the (float) vs (double)/(real) part.
In the external SlevomatCodingStandard, the SlevomatCodingStandard.PHP.TypeCast sniff does handle both, but it also forbids the use of the (unset) and the binary cast. This sniff also contains an auto-fixer for all, but the last two issues.
Open question
Should WPCS have an opinion on the use of the (unset) type cast and the binary cast ?
Refs:
- http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting
- https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#25-keywords-and-types
- https://github.com/squizlabs/PHP_CodeSniffer/releases/tag/3.3.0
Opinions (on any part of the proposal, not just the open question) ?