Skip to content

Conversation

@mtarld
Copy link
Contributor

@mtarld mtarld commented Feb 24, 2025

Q A
Branch? 7.3
Bug fix? no
New feature? yes
Deprecations? no
Issues
License MIT

Add Type::traverse() method, that'll help a lot in terms of DX. Indeed, instead of writing the following:

// [deal with the main type]

foreach ($type instanceof CompositeTypeInterface ? $type->getTypes() : [$type] as $t) {

    // [deal with composite part type]
   
    while($t instanceof WrappingTypeInterface) {
        $t = $t->getWrappedType();
    }
    
    // [deal with wrapped type]
}

it'll only be needed to write:

foreach ($type->traverse() as $t) {
    // [deal with the main type]
    // [deal with composite part type]
    // [deal with wrapped type]
}

Traversable can be configured with $traverseComposite and $traverseWrapped parameters.

@stof
Copy link
Member

stof commented Feb 24, 2025

how often do you deal with types without distinguishing whether it is a union type, an intersection type, a nullable type, etc... ?

@mtarld
Copy link
Contributor Author

mtarld commented Feb 24, 2025

I'm currently migrating PropertyInfo's type to TypeInfo's type in API Platform, and such use cases occur quite often:

// retrieve all class names of a type
foreach ($type instanceof CompositeTypeInterface ? $type->getTypes() : [$type] as $t) {
     while ($t instanceof WrappingTypeInterface) {
        $t = $t->getWrappedType();
    }

    if ($t instanceof ObjectType) {
        $classNames[] = $t->getClassName();
    }
}

This involves either composite, wrapped and regular types.

Using the traverse method, it could be written like:

// retrieve all class names of a type
foreach ($type->traverse() as $t) {
    if ($t instanceof ObjectType) {
        $classNames[] = $t->getClassName();
    }
}

@mtarld mtarld force-pushed the feat/type-info-traverse branch from 1855ec1 to 6d6d8b0 Compare March 3, 2025 11:18
Copy link
Member

@chalasr chalasr left a comment

Choose a reason for hiding this comment

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

Fine by me as we have a legit use case in API Platform

@fabpot fabpot closed this Mar 24, 2025
@fabpot fabpot force-pushed the feat/type-info-traverse branch from 6d6d8b0 to 6872336 Compare March 24, 2025 08:22
@fabpot
Copy link
Member

fabpot commented Mar 24, 2025

Cherry-picked by hand, not sure what happened during merge.

@mtarld mtarld deleted the feat/type-info-traverse branch March 24, 2025 08:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants