`closureUsesThis` should not be reported when `@param-closure-this` is used to change the `$this`

Open
#272 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
php
Domain
tooling

Research direction

Start by reproducing the provided Macroable and SpecialScope example and inspect the closureUsesThis rule. The fix is done when @param-closure-this changing the closure's $this type prevents this diagnostic for the captured outer $this, while the existing warning remains for matching types.

Written by the indexing model from the issue text.

Description

Hello!

When using macros, the $this parameter inside the provided closure is overridden using @param-closure-this:

trait Macroable
{
    /**
     * Register a custom macro.
     *
     * @param-closure-this $this $macro
     */
    public static function macro(string $name, Closure $macro): void;
}
class Builder
{
    use Macroable;
}

However, in some cases, the original class $this needs to be referenced inside the closure:

class SpecialScope
{
    protected function addOnlyConfidential(Builder $query): void
    {
        $scope = $this;

        $query->macro('onlyConfidential', function (Builder $query) use ($scope) {
            $query->withoutGlobalScope($scope);

            return $query->where($scope->column, $scope->invert ? false : true);
        });
    }
}

But this triggers the closureUsesThis rule:

Anonymous function uses $this assigned to variable $scope. Use $this directly in the function body.  
         🪪  closure.useThis 

The rule probably shouldn't be triggered if the $this type outside the closure does not match the type inside the closure

Dominant language
PHP
Stars
709
Forks
62
Avg merge
5d 19h
Merged PRs (30d)
3

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from phpstan/phpstan-strict-rules

All issues in phpstan/phpstan-strict-rules

Similar issues

More PHP issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.