Skip to content

Commit

Permalink
Forbid non-null defaults for callable parameters
Browse files Browse the repository at this point in the history
Fixes #3284
  • Loading branch information
weirdan committed Feb 16, 2023
1 parent f70f651 commit 1c2bc49
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Psalm/Internal/Analyzer/FunctionLikeAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -1256,6 +1256,21 @@ private function processParams(
),
);
}

if ($default_type
&& !$default_type->isNull()
&& $param_type->isSingleAndMaybeNullable()
&& $param_type->getCallableTypes()
) {
IssueBuffer::maybeAdd(
new InvalidParamDefault(
'Default value type for ' . $param_type->getId() . ' argument ' . ($offset + 1)
. ' of method ' . $cased_method_id
. ' can only be null, ' . $default_type->getId() . ' specified',
$function_param->type_location,
),
);
}
}

if ($has_template_types) {
Expand Down
6 changes: 6 additions & 0 deletions tests/FunctionCallTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2741,6 +2741,12 @@ function takesArrayShapeWithZeroOrPositiveInt(array $foo): void
',
'error_message' => 'RedundantFunctionCall',
],
'incorrectCallableParamDefault' => [
'code' => '<?php
function foo(callable $_a = "strlen"): void {}
',
'error_message' => 'InvalidParamDefault',
],
];
}

Expand Down
8 changes: 8 additions & 0 deletions tests/MethodCallTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1562,6 +1562,14 @@ public function foo(): string {
}',
'error_message' => 'UndefinedMethod',
],
'incorrectCallableParamDefault' => [
'code' => '<?php
class A {
public function foo(callable $_a = "strlen"): void {}
}
',
'error_message' => 'InvalidParamDefault',
],
];
}
}

0 comments on commit 1c2bc49

Please sign in to comment.