Issue summary generated with the help of an LLM.

Problem/Motivation

PHPStan currently flags several redundant variable guard errors across Drupal core under the isset.variable and empty.variable identifiers—for example, when isset($var) or empty($var) is called on a variable that is guaranteed to exist and is non-nullable (or is never defined in the current scope). These errors are currently ignored in core/.phpstan-baseline.php.

Above code is the theory. However there are cases where this is actually a false positive flagged by PHPStan.

An example is the following code, currently in our baseline.

  Line   core/lib/Drupal/Core/Config/Entity/Query/Condition.php         
  168    Variable $value in isset() always exists and is not nullable.

Looking at that code part, this is the following.

  /**
   * Perform the actual matching.
   *
   * @param array $condition
   *   The condition array as created by the condition() method.
   * @param string $value
   *   The value to match against.
   *
   * @return bool
   *   TRUE when matches else FALSE.
   */
  protected function match(array $condition, $value) {
    // "IS NULL" and "IS NOT NULL" conditions can also deal with array values,
    // so we return early for them to avoid problems.
    if (in_array($condition['operator'], ['IS NULL', 'IS NOT NULL'], TRUE)) {
      $should_be_set = $condition['operator'] === 'IS NOT NULL';
      return $should_be_set === isset($value);
    }

... REST OF FUNCTION...
}

What we see here, is that PHPStan trusts the PHPDoc comment for the value, and therefore assumes only strings are passed. This is not the case, so the issue phpstan flags is actually incorrect. (In this case there are places where we pass NULL)

If there is only a phpdoc type, and no native php typing, PHPStan should not assume the PHPDoc is correct. Luckily phpstan has an options for that.
treatPhpDocTypesAsCertain (https://phpstan.org/config-reference#treatphpdoctypesascertain)

This makes sure phpstan does not follow blindly phpdoc type hinting. Setting this to false (default is true), removes those false positives like above from our baseline, but does introduce new errors, fixing those is also in scope here.

Proposed resolution

  • Set Set treatPhpDocTypesAsCertain: false in phpstan config.
  • Remove now false positives from baseline, fix the new phpstan issues that popped up.

Remaining tasks

  • Verify PHPStan passes in GitLab CI.

User interface changes

None.

API changes

None.

Data model changes

None.

Issue fork drupal-3641549

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

mallezie created an issue. See original summary.

mallezie’s picture

Title: Fix PHPStan L3 error: isset.variable and empty.variable » PHPStan: Set treatPhpDocTypesAsCertain: false
Issue summary: View changes
Status: Active » Needs review