Skip to content

Commit

Permalink
Explicitly disallow defining type parameters in constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
jiripudil committed Dec 10, 2022
1 parent 473c0f2 commit fb0faa4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
18 changes: 16 additions & 2 deletions src/Rules/Generics/VarianceCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,22 @@ public function checkParametersAcceptor(
$errors = [];

foreach ($parametersAcceptor->getTemplateTypeMap()->getTypes() as $templateType) {
if (!$templateType instanceof TemplateType
|| $templateType->getScope()->getFunctionName() === null
if (!$templateType instanceof TemplateType) {
continue;
}

if ($templateType->getScope()->getClassName() !== null
&& $templateType->getScope()->getFunctionName() === '__construct'
) {
$errors[] = RuleErrorBuilder::message(sprintf(
'Constructor is not allowed to define type parameters, but template type %s is defined %s.',
$templateType->getName(),
$generalMessage,
))->build();
continue;
}

if ($templateType->getScope()->getFunctionName() === null
|| $templateType->getVariance()->invariant()
) {
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,12 @@ public function testRule(): void
],
]);

$this->analyse([__DIR__ . '/data/method-signature-variance-constructor.php'], []);
$this->analyse([__DIR__ . '/data/method-signature-variance-constructor.php'], [
[
'Constructor is not allowed to define type parameters, but template type Y is defined in method MethodSignatureVariance\Constructor\D::__construct().',
79,
],
]);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,11 @@ class C {
*/
function __construct($a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k, $l) {}
}

/** @template X */
class D {
/**
* @template Y of X
*/
function __construct() {}
}

0 comments on commit fb0faa4

Please sign in to comment.