|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Functions; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Node\InArrowFunctionNode; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\Rules\RuleErrorBuilder; |
| 10 | +use PHPStan\ShouldNotHappenException; |
| 11 | +use PHPStan\Type\Generic\TemplateTypeHelper; |
| 12 | +use PHPStan\Type\VerbosityLevel; |
| 13 | +use function is_string; |
| 14 | +use function sprintf; |
| 15 | + |
| 16 | +/** |
| 17 | + * @implements Rule<InArrowFunctionNode> |
| 18 | + */ |
| 19 | +class IncompatibleArrowFunctionDefaultParameterTypeRule implements Rule |
| 20 | +{ |
| 21 | + |
| 22 | + public function getNodeType(): string |
| 23 | + { |
| 24 | + return InArrowFunctionNode::class; |
| 25 | + } |
| 26 | + |
| 27 | + public function processNode(Node $node, Scope $scope): array |
| 28 | + { |
| 29 | + $parameters = $node->getClosureType()->getParameters(); |
| 30 | + |
| 31 | + $errors = []; |
| 32 | + foreach ($node->getOriginalNode()->getParams() as $paramI => $param) { |
| 33 | + if ($param->default === null) { |
| 34 | + continue; |
| 35 | + } |
| 36 | + if ( |
| 37 | + $param->var instanceof Node\Expr\Error |
| 38 | + || !is_string($param->var->name) |
| 39 | + ) { |
| 40 | + throw new ShouldNotHappenException(); |
| 41 | + } |
| 42 | + |
| 43 | + $defaultValueType = $scope->getType($param->default); |
| 44 | + $parameterType = $parameters[$paramI]->getType(); |
| 45 | + $parameterType = TemplateTypeHelper::resolveToBounds($parameterType); |
| 46 | + |
| 47 | + if ($parameterType->accepts($defaultValueType, true)->yes()) { |
| 48 | + continue; |
| 49 | + } |
| 50 | + |
| 51 | + $verbosityLevel = VerbosityLevel::getRecommendedLevelByType($parameterType, $defaultValueType); |
| 52 | + |
| 53 | + $errors[] = RuleErrorBuilder::message(sprintf( |
| 54 | + 'Default value of the parameter #%d $%s (%s) of anonymous function is incompatible with type %s.', |
| 55 | + $paramI + 1, |
| 56 | + $param->var->name, |
| 57 | + $defaultValueType->describe($verbosityLevel), |
| 58 | + $parameterType->describe($verbosityLevel), |
| 59 | + ))->line($param->getLine())->build(); |
| 60 | + } |
| 61 | + |
| 62 | + return $errors; |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments