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
60 changes: 47 additions & 13 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -2186,6 +2186,33 @@ public function withClosureBindScopeClasses(array $scopeClasses): self
);
}

public function withoutThis(): self

@staabm staabm Sep 10, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this method will drop $this but might leave other expressions like $this->xy? could this be a problem?

in other places we use expression invalidation for '$this' like $scope->invalidateExpression(new Variable('this'), ...)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@staabm, please take a look at this discussion---it might be a better solution than this PR provides: phpstan/phpstan#15082

{
$expressionTypes = $this->expressionTypes;
$nativeExpressionTypes = $this->nativeExpressionTypes;
unset($expressionTypes['$this']);
unset($nativeExpressionTypes['$this']);

return $this->scopeFactory->create(
$this->context,
$this->isDeclareStrictTypes(),
$this->getFunction(),
$this->getNamespace(),
$expressionTypes,
$nativeExpressionTypes,
$this->conditionalExpressions,
$this->inClosureBindScopeClasses,
$this->anonymousFunctionReflection,
$this->isInFirstLevelStatement(),
$this->currentlyAssignedExpressions,
$this->currentlyAllowedUndefinedExpressions,
$this->inFunctionCallsStack,
$this->afterExtractCall,
$this->parentScope,
$this->nativeTypesPromoted,
);
}

/**
* @api
* @param ParameterReflection[]|null $callableParameters
Expand Down Expand Up @@ -2302,25 +2329,32 @@ public function enterAnonymousFunctionWithoutReflection(
$expressionTypes[$exprString] = $typeHolder;
}

if ($this->hasVariableType('this')->yes() && !$closure->static) {
if (isset($this->expressionTypes['$this']) && !$closure->static) {
$node = new Variable('this');
$expressionTypes['$this'] = ExpressionTypeHolder::createYes($node, $this->getType($node));
$nativeTypes['$this'] = ExpressionTypeHolder::createYes($node, $this->getNativeType($node));
$thisType = $this->getType($node);
$thisCertainty = $this->expressionTypes['$this']->getCertainty();
if ($thisCertainty->yes()) {
$expressionTypes['$this'] = ExpressionTypeHolder::createYes($node, $thisType);
$nativeTypes['$this'] = ExpressionTypeHolder::createYes($node, $this->getNativeType($node));

if ($this->phpVersion->supportsReadOnlyProperties()) {
foreach ($nonStaticExpressions as $exprString => $typeHolder) {
$expr = $typeHolder->getExpr();
if ($this->phpVersion->supportsReadOnlyProperties()) {
foreach ($nonStaticExpressions as $exprString => $typeHolder) {
$expr = $typeHolder->getExpr();

if (!$expr instanceof PropertyFetch) {
continue;
}
if (!$expr instanceof PropertyFetch) {
continue;
}

if (!$this->isReadonlyPropertyFetch($expr, true)) {
continue;
}
if (!$this->isReadonlyPropertyFetch($expr, true)) {
continue;
}

$expressionTypes[$exprString] = $typeHolder;
$expressionTypes[$exprString] = $typeHolder;
}
}
} else {
$expressionTypes['$this'] = ExpressionTypeHolder::createMaybe($node, $thisType);
$nativeTypes['$this'] = ExpressionTypeHolder::createMaybe($node, $this->getNativeType($node));
}
}

Expand Down
11 changes: 9 additions & 2 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -2044,8 +2044,15 @@ public function processArgs(
$closureThisType = $this->resolveClosureThisType($callLike, $calleeReflection, $parameter, $scopeToPass);
if ($closureThisType !== null) {
$restoreThisScope = $scopeToPass;
$scopeToPass = $scopeToPass->assignVariable('this', $closureThisType, new ObjectWithoutClassType(), TrinaryLogic::createYes())
->withClosureBindScopeClasses($closureThisType->getObjectClassNames());
if ($closureThisType->isNull()->yes()) {
$scopeToPass = $scopeToPass->withoutThis()
->withClosureBindScopeClasses([]);
} else {
$isOptionalBinding = $closureThisType->isNull()->maybe();
$objectThisType = TypeCombinator::removeNull($closureThisType);
$scopeToPass = $scopeToPass->assignVariable('this', $objectThisType, new ObjectWithoutClassType(), $isOptionalBinding ? TrinaryLogic::createMaybe() : TrinaryLogic::createYes())
->withClosureBindScopeClasses($objectThisType->getObjectClassNames());
}
}
}

Expand Down
12 changes: 8 additions & 4 deletions src/PhpDoc/PhpDocNodeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
use PHPStan\Type\Generic\TemplateTypeScope;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
Expand Down Expand Up @@ -412,11 +413,14 @@ public function resolveParamClosureThisTags(PhpDocNode $phpDocNode, NameScope $n
foreach (['@param-closure-this', '@phpstan-param-closure-this'] as $tagName) {
foreach ($phpDocNode->getParamClosureThisTagValues($tagName) as $tagValue) {
$parameterName = substr($tagValue->parameterName, 1);
$resolvedType = $this->typeNodeResolver->resolve($tagValue->type, $nameScope);
$isOptionalBinding = $resolvedType->isNull()->maybe();
$objectType = TypeCombinator::intersect(
TypeCombinator::removeNull($resolvedType),
new ObjectWithoutClassType(),
);
$closureThisTypes[$parameterName] = new ParamClosureThisTag(
TypeCombinator::intersect(
$this->typeNodeResolver->resolve($tagValue->type, $nameScope),
new ObjectWithoutClassType(),
),
$isOptionalBinding ? TypeCombinator::union($objectType, new NullType()) : $objectType,
);
}
}
Expand Down
37 changes: 37 additions & 0 deletions tests/PHPStan/Analyser/nsrt/param-closure-this.php
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,43 @@ public function doFoo(): void

}

class WithOptionalThis
{

/**
* @param-closure-this ?Foo $cb
*/
public function runOptional(callable $cb): void
{

}

/**
* @param-closure-this never $cb
*/
public function runUnbound(callable $cb): void
{

}

}

function testOptionalClosureThis(WithOptionalThis $o): void
{
$o->runOptional(function () {
if (isset($this)) {
assertType(Foo::class, $this);
}
});
}

function testUnboundClosureThis(WithOptionalThis $o): void
{
$o->runUnbound(function () {
assertType('never', $this);
});
}

class FooParent
{

Expand Down
14 changes: 14 additions & 0 deletions tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1701,6 +1701,20 @@ public function testBug10090(): void
]);
}

public function testParamClosureThisOptional(): void
{
$this->cliArgumentsVariablesRegistered = false;
$this->checkMaybeUndefinedVariables = true;
$this->polluteScopeWithLoopInitialAssignments = false;
$this->polluteScopeWithAlwaysIterableForeach = false;
$this->analyse([__DIR__ . '/data/param-closure-this-optional.php'], [
[
'Variable $this might not be defined.',
29,
],
]);
}

public function testBug2032(): void
{
$this->cliArgumentsVariablesRegistered = true;
Expand Down
34 changes: 34 additions & 0 deletions tests/PHPStan/Rules/Variables/data/param-closure-this-optional.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php declare(strict_types = 1);

namespace ParamClosureThisOptional;

class Foo
{

public function method(): void
{
}

}

class Bar
{

/**
* @param-closure-this ?Foo $cb
*/
public function runOptional(callable $cb): void
{
}

}

function test(Bar $b): void
{
$b->runOptional(function () {
$this->method(); // Variable $this might not be defined.
if (isset($this)) {
$this->method(); // no error
}
});
}
Loading