Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
46 changes: 46 additions & 0 deletions src/Rules/Classes/InstantiationRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,15 @@
use PHPStan\Rules\RestrictedUsage\RewrittenDeclaringClassMethodReflection;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
use PHPStan\Type\VerbosityLevel;
use function array_filter;
use function array_map;
use function array_merge;
Expand All @@ -48,6 +55,7 @@ public function __construct(
private ReflectionProvider $reflectionProvider,
private FunctionCallParametersCheck $check,
private ClassNameCheck $classCheck,
private RuleLevelHelper $ruleLevelHelper,
private ConsistentConstructorHelper $consistentConstructorHelper,
#[AutowiredParameter(ref: '%tips.discoveringSymbols%')]
private bool $discoveringSymbolsTip,
Expand All @@ -62,13 +70,51 @@ public function getNodeType(): string

public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array
{
if ($node->class instanceof Node\Expr) {
$errors = $this->checkClassNameExprType($node->class, $scope);
if ($errors !== []) {
return $errors;
}
}

$errors = [];
foreach ($this->getClassNames($node, $scope) as [$class, $isName]) {
$errors = array_merge($errors, $this->checkClassName($class, $isName, $node, $scope));
}
return $errors;
}

/**
* @return list<IdentifierRuleError>
*/
private function checkClassNameExprType(Node\Expr $class, Scope $scope): array
{
$acceptedType = new UnionType([new StringType(), new ObjectWithoutClassType()]);
$typeResult = $this->ruleLevelHelper->findTypeToCheck(
$scope,
$class,
'',
static fn (Type $type): bool => $acceptedType->isSuperTypeOf($type)->yes(),
);

$foundType = $typeResult->getType();
if ($foundType instanceof ErrorType) {
// Unknown classes and mixed are reported elsewhere (e.g. "Instantiated class X not found.").
return [];
}

if ($acceptedType->isSuperTypeOf($foundType)->yes()) {
return [];
}

return [
RuleErrorBuilder::message(sprintf(
'Cannot instantiate class using %s.',
$foundType->describe(VerbosityLevel::typeOnly()),
))->identifier('new.nonObject')->build(),
];
}

/**
* @param Node\Expr\New_ $node
* @return list<IdentifierRuleError>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ protected function getRule(): Rule
$reflectionProvider,
$container,
),
new RuleLevelHelper(
$reflectionProvider,
checkNullables: true,
checkThisOnly: false,
checkUnionTypes: true,
checkExplicitMixed: false,
checkImplicitMixed: false,
checkBenevolentUnionTypes: false,
discoveringSymbolsTip: true,
),
new ConsistentConstructorHelper(),
discoveringSymbolsTip: true,
);
Expand Down
40 changes: 40 additions & 0 deletions tests/PHPStan/Rules/Classes/InstantiationRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ protected function getRule(): Rule
$reflectionProvider,
$container,
),
new RuleLevelHelper(
$reflectionProvider,
checkNullables: true,
checkThisOnly: false,
checkUnionTypes: true,
checkExplicitMixed: $this->checkExplicitMixed,
checkImplicitMixed: false,
checkBenevolentUnionTypes: false,
discoveringSymbolsTip: true,
),
new ConsistentConstructorHelper(),
discoveringSymbolsTip: true,
);
Expand Down Expand Up @@ -682,4 +692,34 @@ public function testBug14499(): void
$this->analyse([__DIR__ . '/data/bug-14499.php'], []);
}

public function testInstantiationWithNonObjectType(): void
{
$this->analyse([__DIR__ . '/data/instantiation-non-object.php'], [
[
'Cannot instantiate class using int.',
31,
],
[
'Cannot instantiate class using int.',
35,
],
[
'Cannot instantiate class using float.',
36,
],
[
'Cannot instantiate class using bool.',
37,
],
[
'Cannot instantiate class using int|string.',
38,
],
[
'Cannot instantiate class using array<int, string>.',
44,
],
]);
}

}
45 changes: 45 additions & 0 deletions tests/PHPStan/Rules/Classes/data/instantiation-non-object.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php declare(strict_types = 1);

namespace InstantiationNonObject;

function get_class_name(): int
{
return 123;
}

class Foo
{
}

/**
* @param class-string $classString
* @param class-string<Foo> $classStringOfFoo
*/
function doFoo(
string $string,
object $object,
int $int,
float $float,
bool $bool,
int|string $intOrString,
string $classString,
string $classStringOfFoo,
Foo $foo
): void
{
$class = get_class_name();
new $class;

new $string;
new $object;
new $int;
new $float;
new $bool;
new $intOrString;
new $classString;
new $classStringOfFoo;
new $foo;

$array = ['a'];
new $array;
}
Loading