Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
433bbb2
Report missing return types of functions and methods with a body on t…
ondrejmirtes Nov 30, 2026
0b8e403
Add projectType parameter
ondrejmirtes Nov 30, 2026
2c58363
Report too-wide types of overridable methods in a closed project with…
ondrejmirtes Nov 30, 2026
167cc12
Record the scope of yields in function and method return statements n…
ondrejmirtes Nov 30, 2026
0ee6476
Fix missing return types with the returned type under the fixMissingR…
ondrejmirtes Nov 30, 2026
e991e2d
Do not fix the return type of a function returning a value as never o…
ondrejmirtes Dec 1, 2026
532ef12
Fix the return type of a function returning an anonymous class with i…
ondrejmirtes Dec 1, 2026
9dc42c7
Generalize constant values and large array shapes in fixed return types
ondrejmirtes Dec 1, 2026
0e513fd
Pass the files changed by the previous rounds of --fix in a file
ondrejmirtes Dec 1, 2026
b921d48
Normalize the union of returned objects in fixed return types
ondrejmirtes Dec 1, 2026
d7ab25f
Test that fixed return types are written with self under fixer.prefer…
ondrejmirtes Dec 1, 2026
1232c1f
Keep fixed return types within the return types of the overridden met…
ondrejmirtes Dec 1, 2026
e4ccbe2
Update the @return tag left behind by a fixed native return type
ondrejmirtes Dec 1, 2026
89cb709
Do not fix the return type of a function returning an array of mixed …
ondrejmirtes Dec 1, 2026
cdf2c82
Make the fixes of MissingReturnTypeFixRule without parsing the files …
ondrejmirtes Dec 1, 2026
4292ca0
Keep fixed return types invariant across the class hierarchy before P…
ondrejmirtes Dec 1, 2026
eb1373e
Fix too-wide return types of functions and methods that cannot be ove…
ondrejmirtes Dec 1, 2026
bdd8f2f
Coordinate the fixes of too-wide return types across the class hierarchy
ondrejmirtes Dec 1, 2026
023d097
Narrow native return types only by the native types of the returned v…
ondrejmirtes Dec 1, 2026
ffd63c0
Do not fix too-wide return types the returned values are not a subtyp…
ondrejmirtes Dec 1, 2026
c51227f
Do not fix too-wide return types of methods incompatible with their p…
ondrejmirtes Dec 1, 2026
c7a5360
Report never-returned null of overriding methods in a closed project
ondrejmirtes Dec 1, 2026
a8edab3
Fix too-wide return types of methods whose parents accept what they r…
ondrejmirtes Dec 1, 2026
15add59
Run the native union type fixture of too-wide fixes only on PHP 8.0+
ondrejmirtes Dec 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ lint:
--exclude tests/PHPStan/Analyser/nsrt \
--exclude tests/PHPStan/Rules/Methods/data \
--exclude tests/PHPStan/Rules/Functions/data \
--exclude tests/PHPStan/Rules/data/fix-missing-return-type \
--exclude tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type \
--exclude tests/PHPStan/Rules/Names/data \
--exclude tests/PHPStan/Rules/Operators/data/invalid-inc-dec.php \
--exclude tests/PHPStan/Rules/Arrays/data/offset-access-without-dim-for-reading.php \
Expand Down
1 change: 1 addition & 0 deletions conf/bleedingEdge.neon
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ parameters:
checkExtensionsForComparisonOperators: true
checkGenericIterableClasses: true
reportTooWideBool: true
fixMissingReturnTypes: true
rawMessageInBaseline: true
reportNestedTooWideType: false # tmp
assignToByRefForeachExpr: true
Expand Down
2 changes: 2 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ parameters:
checkConditionalParameterTypes: false
checkMixedWitnessTypes: false
recursiveLoopTypes: false
fixMissingReturnTypes: false
fileExtensions:
- php
checkAdvancedIsset: false
Expand All @@ -97,6 +98,7 @@ parameters:
checkPhpDocMethodSignatures: false
checkExtraArguments: false
checkMissingTypehints: false
projectType: open
checkTooWideParameterOutInProtectedAndPublicMethods: false
checkTooWideReturnTypesInProtectedAndPublicMethods: false
checkTooWideThrowTypesInProtectedAndPublicMethods: false
Expand Down
2 changes: 2 additions & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ parametersSchema:
checkConditionalParameterTypes: bool()
checkMixedWitnessTypes: bool()
recursiveLoopTypes: bool()
fixMissingReturnTypes: bool()
])
fileExtensions: listOf(string())
checkAdvancedIsset: bool()
Expand All @@ -94,6 +95,7 @@ parametersSchema:
checkPhpDocMethodSignatures: bool()
checkExtraArguments: bool()
checkMissingTypehints: bool()
projectType: anyOf('open', 'closed')
checkTooWideParameterOutInProtectedAndPublicMethods: bool()
checkTooWideReturnTypesInProtectedAndPublicMethods: bool()
checkTooWideThrowTypesInProtectedAndPublicMethods: bool()
Expand Down
4 changes: 4 additions & 0 deletions e2e/fix-many-files/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/src
/tmp
/vendor
/composer.lock
7 changes: 7 additions & 0 deletions e2e/fix-many-files/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"autoload-dev": {
"classmap": [
"rules/"
]
}
}
28 changes: 28 additions & 0 deletions e2e/fix-many-files/fix-many-files_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# @tags result-cache

function set_up() {
e2e::set_up
}

function tear_down() {
e2e::tear_down
}

# the files changed by the previous rounds do not fit on the command line of the next round
function test_fix_many_files() {
composer install
rm -rf src tmp && mkdir -p src
printf '<?php\n\nfunction step1(): void {}\nfunction step2(): void {}\nfunction step3(): void {}\n' > src/functions.php
for i in $(seq 1 2000); do
printf '<?php\n\nstep1();\n' > "src/a-file-with-a-name-long-enough-to-fill-the-command-line-of-the-next-round-$i.php"
done
OUTPUT=$(../../bin/phpstan analyse --fix 2>&1) && CODE=0 || CODE=$?
echo "$OUTPUT" | tail -20
assert_same "0" "$CODE"
assert_contains 'Round 2: fixed 2000 errors in 2000 files' "$OUTPUT"
assert_contains '[OK] 4000 errors fixed in 2000 files' "$OUTPUT"
assert_same "step3();" "$(tail -1 src/a-file-with-a-name-long-enough-to-fill-the-command-line-of-the-next-round-1.php)"
# the list of the changed files is removed after the rounds
assert_same "" "$(find tmp -name 'fixed-files-*')"
}
8 changes: 8 additions & 0 deletions e2e/fix-many-files/phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
parameters:
level: 0
paths:
- src
tmpDir: tmp

rules:
- FixManyFilesE2E\StepRule
43 changes: 43 additions & 0 deletions e2e/fix-many-files/rules/StepRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php declare(strict_types = 1);

namespace FixManyFilesE2E;

use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;

/**
* Renames step1() to step2() and step2() to step3(), so every file changed in the first round is changed in the second one too.
*
* @implements Rule<FuncCall>
*/
final class StepRule implements Rule
{

public function getNodeType(): string
{
return FuncCall::class;
}

public function processNode(Node $node, Scope $scope): array
{
if (!$node->name instanceof Node\Name || preg_match('~^step([1-2])$~', $node->name->toString(), $matches) !== 1) {
return [];
}

$next = 'step' . ((int) $matches[1] + 1);

return [
RuleErrorBuilder::message(sprintf('Call %s() instead.', $next))
->identifier('fixManyFilesE2E.step')
->fixNode($node, static function (FuncCall $node) use ($next): FuncCall {
$node->name = new Node\Name($next);
return $node;
})
->build(),
];
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PHPStan\Analyser\IgnoreErrorExtension;
use PHPStan\Analyser\Scope;
use PHPStan\Node\InClassMethodNode;
use PHPStan\Node\MethodReturnStatementsNode;

// This extension will ignore "missingType.iterableValue" errors for public Action methods inside Controller classes.
final class ControllerActionReturnTypeIgnoreExtension implements IgnoreErrorExtension
Expand All @@ -19,8 +20,10 @@ public function shouldIgnore(Error $error, Node $node, Scope $scope) : bool
return false;
}

// @phpstan-ignore phpstanApi.instanceofAssumption
if (! $node instanceof InClassMethodNode) {
// Methods with a body report missing return types on MethodReturnStatementsNode,
// abstract methods and methods in interfaces on InClassMethodNode.
// @phpstan-ignore phpstanApi.instanceofAssumption, phpstanApi.instanceofAssumption
if (! $node instanceof InClassMethodNode && ! $node instanceof MethodReturnStatementsNode) {
return false;
}

Expand Down
3 changes: 2 additions & 1 deletion src/Analyser/StmtHandler/ClassMethodHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use PHPStan\Node\PropertyAssignNode;
use PHPStan\Node\ReturnAfterFinallyNode;
use PHPStan\Node\ReturnStatement;
use PHPStan\Node\YieldStatement;
use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
Expand Down Expand Up @@ -228,7 +229,7 @@ public function processStmt(
return;
}
if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) {
$gatheredYieldStatements[] = $node;
$gatheredYieldStatements[] = new YieldStatement($scope, $node);
}
if (!$node instanceof Return_) {
return;
Expand Down
3 changes: 2 additions & 1 deletion src/Analyser/StmtHandler/FunctionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use PHPStan\Node\PropertyAssignNode;
use PHPStan\Node\ReturnAfterFinallyNode;
use PHPStan\Node\ReturnStatement;
use PHPStan\Node\YieldStatement;
use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
Expand Down Expand Up @@ -143,7 +144,7 @@ public function processStmt(
return;
}
if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) {
$gatheredYieldStatements[] = $node;
$gatheredYieldStatements[] = new YieldStatement($scope, $node);
}
if (!$node instanceof Return_) {
return;
Expand Down
35 changes: 24 additions & 11 deletions src/Command/AnalyseCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
use function strlen;
use function substr;
use function trim;
use function uniqid;
use function unlink;
use const PATHINFO_BASENAME;
use const PATHINFO_EXTENSION;

Expand Down Expand Up @@ -102,7 +104,7 @@ final class AnalyseCommand extends Command

private const OPTION_FIX_ROUND = 'fix-round';

private const OPTION_FIXED_IGNORED_IN = 'fixed-ignored-in';
private const OPTION_FIXED_FILES = 'fixed-files';

/**
* @param string[] $composerAutoloaderProjectPaths
Expand Down Expand Up @@ -137,7 +139,7 @@ protected function configure(): void
new InputOption('fix', mode: InputOption::VALUE_NONE, description: 'Fix auto-fixable errors (experimental)'),
new InputOption('fix-ignored', mode: InputOption::VALUE_NONE, description: 'Fix auto-fixable ignored errors, can be combined with --fix (experimental)'),
new InputOption(self::OPTION_FIX_ROUND, mode: InputOption::VALUE_NONE, description: '(Internal) Run one round of --fix and print its counts as JSON'),
new InputOption(self::OPTION_FIXED_IGNORED_IN, mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, description: '(Internal) Files changed by the previous rounds of --fix-ignored'),
new InputOption(self::OPTION_FIXED_FILES, mode: InputOption::VALUE_REQUIRED, description: '(Internal) JSON file with the list of the files changed by the previous rounds of --fix'),
new InputOption('watch', mode: InputOption::VALUE_NONE, description: 'Launch PHPStan Pro'),
new InputOption('pro', mode: InputOption::VALUE_NONE, description: 'Launch PHPStan Pro'),
new InputOption('fail-without-result-cache', mode: InputOption::VALUE_NONE, description: 'Return non-zero exit code when result cache is not used'),
Expand Down Expand Up @@ -588,7 +590,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if (!$fixReported) {
// a fixed ignored error leaves behind the ignore that matched it, like an unmatched baseline entry
// or a count that is too high, those are reported in the files the previous rounds changed
$fixedIgnoredIn = array_fill_keys($input->getOption(self::OPTION_FIXED_IGNORED_IN), true);
$fixedFilesFile = $input->getOption(self::OPTION_FIXED_FILES);
/** @var list<string> $fixedFiles */
$fixedFiles = is_string($fixedFilesFile) ? Json::decode(FileReader::read($fixedFilesFile), Json::FORCE_ARRAY) : [];
$fixedIgnoredIn = array_fill_keys($fixedFiles, true);
foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) {
if (
!$fileSpecificError->isFixable()
Expand Down Expand Up @@ -688,6 +693,7 @@ private function fixInRounds(
{
$errorOutput = $inceptionResult->getErrorOutput();
$stdOutput = $inceptionResult->getStdOutput();
$tmpDir = $inceptionResult->getContainer()->getParameter('tmpDir');
$appliedCount = count($fixResult->getFixedErrors());
$roundChangedFiles = $fixResult->getChangedFiles();
$fixedCount = 0;
Expand Down Expand Up @@ -716,6 +722,9 @@ private function fixInRounds(
$round++;
$errorOutput->writeLineFormatted('');
$errorOutput->writeLineFormatted(sprintf('Analysing fixed code (round %d)...', $round));
// thousands of changed files do not fit on the command line
$fixedFilesFile = sprintf('%s/%s.json', $tmpDir, uniqid('fixed-files-', true));
FileWriter::write($fixedFilesFile, Json::encode(array_keys($changedFiles)));
$command = ProcessHelper::getWorkerCommand(
$_SERVER['argv'][0],
self::NAME,
Expand All @@ -725,19 +734,23 @@ private function fixInRounds(
(bool) $input->getOption(ErrorsConsoleStyle::OPTION_NO_PROGRESS) ? ['--' . ErrorsConsoleStyle::OPTION_NO_PROGRESS] : [],
(bool) $input->getOption('fix') ? ['--fix'] : [],
(bool) $input->getOption('fix-ignored') ? ['--fix-ignored'] : [],
array_map(static fn (string $file): string => '--' . self::OPTION_FIXED_IGNORED_IN . '=' . escapeshellarg($file), array_keys($changedFiles)),
['--' . self::OPTION_FIXED_FILES . '=' . escapeshellarg($fixedFilesFile)],
),
$input,
);
$process = Process::fromShellCommandline($command, timeout: null);
// the progress bar of the analysis is on stderr, the result of the round on stdout
$process->run(static function (string $type, string $buffer) use ($errorOutput): void {
if ($type !== Process::ERR) {
return;
}
try {
// the progress bar of the analysis is on stderr, the result of the round on stdout
$process->run(static function (string $type, string $buffer) use ($errorOutput): void {
if ($type !== Process::ERR) {
return;
}

$errorOutput->writeRaw($buffer);
});
$errorOutput->writeRaw($buffer);
});
} finally {
@unlink($fixedFilesFile);
}
try {
/** @var array{fixable: int, applied: int, changedFiles: list<string>} $roundResult */
$roundResult = Json::decode($process->getOutput(), Json::FORCE_ARRAY);
Expand Down
13 changes: 12 additions & 1 deletion src/Node/FunctionReturnStatementsNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PHPStan\Analyser\StatementResult;
use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection;
use PHPStan\Turbo\ReferencedByTurboExtension;
use function array_map;
use function count;

/**
Expand All @@ -24,7 +25,7 @@ final class FunctionReturnStatementsNode extends NodeAbstract implements ReturnS
/**
* @param list<ReturnStatement> $returnStatements
* @param list<ReturnStatement> $returnStatementsAfterFinally
* @param list<Yield_|YieldFrom> $yieldStatements
* @param list<YieldStatement> $yieldStatements
* @param list<ExecutionEndNode> $executionEnds
* @param ImpurePoint[] $impurePoints
*/
Expand Down Expand Up @@ -83,6 +84,16 @@ public function hasNativeReturnTypehint(): bool
}

public function getYieldStatements(): array
{
return array_map(static fn (YieldStatement $statement): Yield_|YieldFrom => $statement->getYieldNode(), $this->yieldStatements);
}

/**
* The yields with the scopes they are in.
*
* @return list<YieldStatement>
*/
public function getYieldStatementsWithScope(): array
{
return $this->yieldStatements;
}
Expand Down
13 changes: 12 additions & 1 deletion src/Node/MethodReturnStatementsNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
use PHPStan\Turbo\ReferencedByTurboExtension;
use function array_map;
use function count;

/**
Expand All @@ -27,7 +28,7 @@ final class MethodReturnStatementsNode extends NodeAbstract implements ReturnSta
/**
* @param list<ReturnStatement> $returnStatements
* @param list<ReturnStatement> $returnStatementsAfterFinally
* @param list<Yield_|YieldFrom> $yieldStatements
* @param list<YieldStatement> $yieldStatements
* @param list<ExecutionEndNode> $executionEnds
* @param ImpurePoint[] $impurePoints
*/
Expand Down Expand Up @@ -93,6 +94,16 @@ public function getMethodName(): string
}

public function getYieldStatements(): array
{
return array_map(static fn (YieldStatement $statement): Yield_|YieldFrom => $statement->getYieldNode(), $this->yieldStatements);
}

/**
* The yields with the scopes they are in.
*
* @return list<YieldStatement>
*/
public function getYieldStatementsWithScope(): array
{
return $this->yieldStatements;
}
Expand Down
33 changes: 33 additions & 0 deletions src/Node/YieldStatement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php declare(strict_types = 1);

namespace PHPStan\Node;

use PhpParser\Node\Expr\Yield_;
use PhpParser\Node\Expr\YieldFrom;
use PHPStan\Analyser\Scope;
use PHPStan\Turbo\ReferencedByTurboExtension;

/**
* A yield in the body of a function or a method, with the scope it is in.
*
* @api
*/
#[ReferencedByTurboExtension(key: 'yieldStatement')]
final class YieldStatement
{

public function __construct(private Scope $scope, private Yield_|YieldFrom $yieldNode)
{
}

public function getScope(): Scope
{
return $this->scope;
}

public function getYieldNode(): Yield_|YieldFrom
{
return $this->yieldNode;
}

}
Loading
Loading