kalessil / phpinspectionsea

A Static Code Analyzer for PHP (a PhpStorm/Idea Plugin)
https://plugins.jetbrains.com/plugin/7622?pr=phpStorm
Other
1.45k stars 118 forks source link

Flexible heredoc not recognized #1543

Open tacovandenbroek opened 4 years ago

tacovandenbroek commented 4 years ago
Subject Details
Plugin Php Inspections (EA Extended) version 4.0.3
Language level PHP 7.3

Current behaviour

2020-04-09_10-48

Expected behaviour

I'd expect no warning for this valid regular expression.

Environment details

PhpStorm 2019.3

kalessil commented 4 years ago

Thank you for reporting @tacovandenbroek, I'll look into it.

kalessil commented 4 years ago

@tacovandenbroek : unfortunately I was not able to reproduce the issue. Would you please share an isolated code fragment where the issue appears?

tacovandenbroek commented 4 years ago

Sure! It seems to depend on the context. I couldn't trigger the inspection without wrapping the code in a function:

<?php
function doesMatch(string $subject): bool {
    $regex = <<< REGEX
            (foo)
            REGEX;
    return (bool)preg_match($regex, $subject);
}
ausi commented 2 years ago

I think this issue is caused by leading white space (even though the heredoc example does not have the whitespace in the resulting string).

I was able to reproduce it with this simple test case:

preg_match(' /.+/', '');

Bildschirmfoto 2022-02-24 um 12 44 44
PhpStorm 2021.3.2, PHP Inspections (EA Extended) 4.0.7.1

Leading and trailing whitespace is supported in PCRE, see https://3v4l.org/Kvcqa

ausi commented 2 years ago

Maybe changing the lines from here https://github.com/kalessil/phpinspectionsea/blob/9bd52620388ca5f8f0d894d49ad5e921a6adf533/src/main/java/com/kalessil/phpStorm/phpInspectionsEA/inspectors/regularExpressions/NotOptimalRegularExpressionsInspector.java#L67-L71 to something like this (adding \s* to the beginning and end) could work?

matchers.add(Pattern.compile("^\\s*([^{<(\\[])(.*)(\\1)([a-zA-Z]+)?\\s*$", Pattern.DOTALL));
matchers.add(Pattern.compile("^\\s*(\\{)(.*)(\\})([a-zA-Z]+)?\\s*$", Pattern.DOTALL));
matchers.add(Pattern.compile("^\\s*(<)(.*)(>)([a-zA-Z]+)?\\s*$", Pattern.DOTALL));
matchers.add(Pattern.compile("^\\s*(\\()(.*)(\\))([a-zA-Z]+)?\\s*$", Pattern.DOTALL));
matchers.add(Pattern.compile("^\\s*(\\[)(.*)(\\])([a-zA-Z]+)?\\s*$", Pattern.DOTALL));