Skip to content

MissingTraversableTypeHintSpecification false positive when using $this in generic type parameters #1801

@alies-dev

Description

@alies-dev

The SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification sniff incorrectly reports an error when $this is used as a template type parameter in generic annotations, even though the type specification is complete.

The SlevomatCodingStandard.TypeHints.ReturnTypeHint sniff incorrectly reports an MissingTraversableTypeHintSpecification error when $this is used as a template type parameter in generic annotations, even though the type specification is complete. This is particularly annoying when Larastan (PHPStan for Laravel) is used on the project and requires $this in some generics.

error:

 @return annotation of method \App\Modules\Course\Models\Course::coreLessons() does not specify type hint
     |       | for items of its traversable return value.
     |       | (SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification)

original code:

    /** @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Modules\Course\Models\Lesson, $this> */
    public function coreLessons(): HasMany
    {
        return $this->hasMany(Lesson::class);
    }

Expected Behavior: No error should be reported, as Generic<Bar, $this> fully specifies both template parameters.

Root Cause

The PHPDoc parser represents $this as a ThisTypeNode, which was not handled in the AnnotationTypeHelper::containsItemsSpecificationForTraversable() method. While self and static are handled as IdentifierTypeNode strings, $this requires separate handling.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions