Skip to content

Instantly share code, notes, and snippets.

@tehbeard
Created January 19, 2023 21:07
Show Gist options
  • Save tehbeard/09c2e196790bf3f749e5c0380b05b0c9 to your computer and use it in GitHub Desktop.
Save tehbeard/09c2e196790bf3f749e5c0380b05b0c9 to your computer and use it in GitHub Desktop.
Testing classes against complex types
<?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