phpredbeanphpstan

How to configure PHPStan to avoid false positives caused by specific classes and/or magic methods?


While using PHP RedBean on a project, PHPStan reports problems like this one:

87     Access to an undefined property RedBeanPHP\OODBBean::$token.

This is happening because RedBean's OODBBean class uses magic methods to logically bind class attributes with database table columns. AFAIK, there is nothing wrong with the way RedBean is implementing that feature.

Is there a way to configure PHPStan to ignore problems from RedBean (or any other class)? Or to ignore what might be being caused by magic methods?


Solution

  • You have several options depending on what you exactly need. For magic properties:

    1. If your class can dynamically contain any property, similarly to stdClass, you can put the class name into universalObjectCratesClasses config parameter. See README.
    2. If your class always contains the same magic properties, you can define them by adding @property annotations above the class.
    3. You can create a so-called class reflection extension that describes what your __get and __set method logic for the static analyser. This is a robust way to define what exact properties will exist on an object in every situation. This makes PHPStan very powerful by avoiding false negatives - it will still report accessed properties that are not defined even in a magic way. See README for more details.

    For magic methods, the same thing in 3. applies - you can write an extension that describes logic in __call for the static analyser. See README for more details.