Skip to content

Commit

Permalink
InstantiationRule - test new static() in cases where it's possible
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Aug 17, 2019
1 parent 3ebf508 commit 3e5cd7f
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Rules/Classes/InstantiationRule.php
Expand Up @@ -7,6 +7,7 @@
use PHPStan\Analyser\Scope;
use PHPStan\Broker\Broker;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\Php\PhpMethodReflection;
use PHPStan\Rules\ClassCaseSensitivityCheck;
use PHPStan\Rules\ClassNameNodePair;
use PHPStan\Rules\FunctionCallParametersCheck;
Expand Down Expand Up @@ -72,7 +73,21 @@ private function checkClassName(string $class, Node $node, Scope $scope): array
sprintf('Using %s outside of class scope.', $class),
];
}
return [];

$classReflection = $scope->getClassReflection();
if (!$classReflection->isFinal()) {
if (!$classReflection->hasConstructor()) {
return [];
}

$constructor = $classReflection->getConstructor();
if (!$constructor->getPrototype()->getDeclaringClass()->isInterface()) {
$isFinal = $constructor instanceof PhpMethodReflection && $constructor->isFinal();
if (!$isFinal) {
return [];
}
}
}
} elseif ($lowercasedClass === 'self') {
if (!$scope->isInClass()) {
return [
Expand Down
12 changes: 12 additions & 0 deletions tests/PHPStan/Rules/Classes/InstantiationRuleTest.php
Expand Up @@ -155,6 +155,18 @@ public function testInstantiation(): void
'Instantiated class UndefinedClass3 not found.',
176,
],
[
'Class TestInstantiation\FinalClass does not have a constructor and must be instantiated without any parameters.',
187,
],
[
'Class TestInstantiation\ClassWithFinalConstructor constructor invoked with 0 parameters, 1 required.',
203,
],
[
'Class TestInstantiation\ConstructorComingFromAnInterface constructor invoked with 0 parameters, 1 required.',
226,
],
]
);
}
Expand Down
50 changes: 50 additions & 0 deletions tests/PHPStan/Rules/Classes/data/instantiation.php
Expand Up @@ -177,3 +177,53 @@ public static function doFoo(string $key): void
}

}

final class FinalClass
{

public function doFoo()
{
new static();
new static(1);
}

}

class ClassWithFinalConstructor
{

final public function __construct(int $i)
{

}

public function doFoo()
{
new static(1);
new static();
}

}

interface InterfaceWithConstructor
{

public function __construct(int $i);

}

class ConstructorComingFromAnInterface implements InterfaceWithConstructor
{

public function __construct(int $i)
{

}

public function doFoo()
{
new static(1);
new static();
}

}

0 comments on commit 3e5cd7f

Please sign in to comment.