phpstan-strict-rules icon indicating copy to clipboard operation
phpstan-strict-rules copied to clipboard

Rules to only allow loose comparison with numeric operands

Open jasny opened this issue 6 years ago • 7 comments

strictly and strongly typed code with no loose casting for those who want additional safety in extremely defensive programming.

Loose comparison does loose casting with unexpected result. To achieve the purpose of this library, this has to be dealth with.


Similar to arithmetic operators (+/-/*///**/%), loose comparison operators should only be used for numeric (and DateTimeInterface) values. This is true for ==, !=, <, >, <=, >= and <=>.

Using any of these operators for non-numeric values may lead to unexpected results.

See issue #40 for more info.

jasny avatar Oct 20 '18 15:10 jasny

@carusogabriel Please take a look

jasny avatar Nov 05 '18 21:11 jasny

@ondrejmirtes Fixed and updated. If anything more is needed for this to be merged, please let me know.

jasny avatar Sep 20 '19 09:09 jasny

<, >, <=, >= and <=> should be allowed for DateTimeInterface values.

enumag avatar Sep 26 '19 08:09 enumag

@enumag It is; see https://github.com/phpstan/phpstan-strict-rules/pull/41/files#diff-04c6e90faac2675aa89e2176d2eec7d8R12

jasny avatar Sep 27 '19 04:09 jasny

Hi, I tried out this rule and when I get this message:

Only int|float|DateTimeInterface is allowed in ==, null given on the left side.

It's not obvious to the user what they should do instead. So what would probably be better is to center the wording about "you need to use === instead of ==" rather than that something is not allowed...

Can you bring some ideas about the rule positioning and wording with regard to this? Thanks.

ondrejmirtes avatar Aug 02 '20 12:08 ondrejmirtes

@ondrejmirtes I'm happy to change the text. However, I'm unsure about the wording.

The current messages are copied from the existing rules for arithmetic operators and boolean conditions. Do you want something completely different? What is a good example that I might copy?e

Note that what you should do isn't always clear for other operators than == and != (similar to the arithmetic operator rules). What does [object] > 99 mean? I don't know, but it's probably not correct.

jasny avatar Aug 18 '20 22:08 jasny

IMHO, the rule should only apply to <, >, <=, >= and <=>.

== and != should be handle (or maybe is already) differently, because === and !== should always be preferred.

VincentLanglet avatar Jun 29 '21 17:06 VincentLanglet