0

I have tons of old code that needs to be updated. Is there a way to create an inspection in PhpStorm that will add empty() and !empty() accordingly in if-clauses? The easy examples would be:

if ($foobar)

Would become:

if (!empty($foobar))

But it can be complex quite quickly:

if ($_GET["foo"] == "bar" && is_array($_GET["foobar"]))

Which would become something like:

if ((!empty($_GET["foo"]) && $_GET["foo"] == "bar") && (!empty($_GET["foobar"] && is_array($_GET["foobar"]))

Which makes it hard for me to do with a regexp script. I figure PhpStorm has better internal structure for detecting comparisons with variables and should be able to handle this, but then again, maybe not?

It would be fine with null coalescing operator as well in some cases, like:

if (($_GET["foo"] ?? false) == "bar" && (!empty($_GET["foobar"] && is_array($_GET["foobar"]))

Any ideas?

3
  • You could look into SSR -- Structured Search & Replace that can also work as an inspection/intention. But I think it can handle rather simple cases (def not 1 rule for both simple and complex).
    – LazyOne
    Commented May 16 at 11:03
  • What about using something like PHP_CodeSniffer or similar tool -- write a custom rule for this tool + a fix code as well? At least worth checking it out.
    – LazyOne
    Commented May 16 at 11:04
  • While it's a more complicated transformation, I suggest doing something like $foo = $_GET["foo"] ?? null; then use $foo in the rest of the code, rather than adding the !empty() checks around all uses of the variable.
    – Barmar
    Commented May 16 at 15:54

0

Browse other questions tagged or ask your own question.