Created
January 19, 2023 21:07
-
-
Save tehbeard/09c2e196790bf3f749e5c0380b05b0c9 to your computer and use it in GitHub Desktop.
Testing classes against complex types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Function to test a class type against a potentially complex type | |
Should handle Disjunctive Normal Form Types as well (A&B)|C|null | |
*/ | |
function matchesType(string $class, ReflectionNamedType|ReflectionIntersectionType|ReflectionUnionType $type): bool | |
{ | |
if ($type instanceof ReflectionNamedType) { | |
return is_a($class, $type->getName(), true); | |
} else if ($type instanceof ReflectionIntersectionType) { | |
foreach($type->getTypes() as $subType) | |
{ | |
if(!matchesType($class, $subType)) | |
{ | |
return false; | |
} | |
} | |
return true; | |
} else if ($type instanceof ReflectionUnionType) { | |
foreach($type->getTypes() as $subType) | |
{ | |
if(matchesType($class, $subType)) | |
{ | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment