Best way to retrieve top level object of a variant


I have Products with variants, i would like to know what is the best/shortest way to get the top level Product in fact, given a Product object (that could be a variant or the top object iteself)
Thank you very much !
Best regards,

PS : what do you think about this snippet …?

 * @param AbstractObject $object
 * @return AbstractObject
public static function getTopLevelObject(AbstractObject $object): AbstractObject
    while ($object && $object->getType() == AbstractObject::OBJECT_TYPE_VARIANT) {
        $object = $object->getParent();

    return $object;

Hi @Fred,

Your code looks good to me. Maybe you could compare the type more strictly like $object->getType() === AbstractObject::OBJECT_TYPE_VARIANT, but other than that it should work.

sure ! thanks for your review ! :wink: