Skip to content

Representing custom restricted hierarchies #7493

@jiripudil

Description

@jiripudil

Feature request

Sorry the title sounds so convoluted, I couldn't come up with a better one. I'm currently picking up on #4768, flagging sealed classes using an attribute:

#[Sealed(permits: [Bar::class, Baz::class])]
abstract class Foo {}

class Bar extends Foo {}
class Baz extends Foo {}
class Qux extends Foo {}

This works nicely and Qux is reported as an error. But sealed classes are only half as beneficial as they could be if PHPStan knew about how they restrict the class hierarchy:

function (Foo $foo) {
    if ($foo instanceof Bar) {
        // ...
    } else {
        // here, $foo can only be Baz, but PHPStan doesn't know that
    }
}

It's essentially the same logic that is applied for enums in ObjectType::changeSubtractedType. Would you be open to providing an extension point to customize object type subtraction? Besides sealed classes, I believe pre-PHP8.1 implementations of enumerations could also benefit from this.

Would that even be viable? It seems that type manipulation is quite isolated from any infrastructure code, so I'm not sure what the best place would be to inject a list of configured extensions 🤔

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