Skip to content

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

Open
@calebdw

Description

@calebdw

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions