Skip to content

If var equals empty string type elimination (second try) #7668

@thg2k

Description

@thg2k

Bug report

This is another attempt at issue #2727, I keep running into this problem as I often
use the shortcut if ($var == "") return; to catch both the empty string and false.

I understand it is fairly complicated to fully handle PHP's type coercion rules, but wouldn't it be possible and easy to code a special rule for this specific case? After all the if ($var) return; does work, the problem is that it also catches the string "0" which I usually find a bit disturbing.

Code snippet that reproduces the problem

<?php

/** @param string|false $a */
function f1($a): void {
  \PhpStan\DumpType($a);
  if (!$a) return;
  \PhpStan\DumpType($a);
}

/** @param string|false $a */
function f2($a): void {
  \PhpStan\DumpType($a);
  if ($a == "") return;
  \PhpStan\DumpType($a);
}

https://phpstan.org/r/a03da769-4d8e-41e0-a1eb-2d153c49792c

Expected output

  5      Dumped type: string|false
  7      Dumped type: non-empty-string
  12     Dumped type: string|false
  14     Dumped type: non-empty-string

Actual output

  5      Dumped type: string|false
  7      Dumped type: non-empty-string
  12     Dumped type: string|false
  14     Dumped type: string|false

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions