I am currently in the process of migrating a large, super-legacy codebase to PHP 8.x, and I am utilizing PHPStan to identify potential issues. However, I have encountered a challenge related to the inclusion of files using global variables, which PHPStan struggles to resolve.
The problematic code includes file inclusions with global variables using a structure like include(magicLogic());, leading to over 10,000 error messages such as "Variable $myvar might not be defined."
I am aware that adding /** @var mixed myvar */ in the file header resolves the issue. However, dealing with over 100 such scripts and more than a thousand reported variables makes this approach impractical.
I am also aware that I can disable the whole error message using ignoreErrors section in phpstan.neon. Which I would prefer to avoid to don't miss real undefined variables.
To address this, I have compiled a list of variables in a globals.stub.php file, intending to point PHPStan to it from the phpstan.neon configuration. Unfortunately, my attempts have not been successful.
Here's an overview of my configuration:
phpstan.neon:
parameters:
level: 2
paths:
- %rootDir%/../../../
scanFiles:
- globals.stub.php
stubFiles:
- globals.stub.php
bootstrapFiles:
- globals.stub.php
excludePaths:
- vendor
test.php:
<?php
echo $myvar;
?>
globals.stub.php:
<?php
global $myvar;
/** @var string $myvar */
$myvar = 'Hello World!';
$GLOBALS['myvar'] = $myvar;
?>
Despite these efforts, the error persists when running PHPStan:
Note: Using configuration file ./phpstan.neon.
1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
------ ---------------------------------------
Line test.php
------ ---------------------------------------
4 Variable $myvar might not be defined.
------ ---------------------------------------
It's important to note that:
- Modifying the PHP files being checked is not an option.
- Manually adding PHPStan comments to hundreds of files is impractical.
- My job is to find the easiest and fastest way how to run the scripts on PHP8.
- The same issue is with constants.
I am seeking a solution to incorporate the list of variables into a stub file and have PHPStan recognize it.