Skip to content

Instantly share code, notes, and snippets.

@BenMorel
Last active December 28, 2020 21:42
Show Gist options
  • Save BenMorel/5d67c2bb829759c09168a101ca8e41ef to your computer and use it in GitHub Desktop.
Save BenMorel/5d67c2bb829759c09168a101ca8e41ef to your computer and use it in GitHub Desktop.
Generates entries for Psalm's CallMap from Reflection
<?php
// Configure here the classes to export. Example:
$classes = [
'GEOSGeometry',
'GEOSWKBReader',
'GEOSWKBWriter',
'GEOSWKTReader',
'GEOSWKTWriter'
];
// Sample output:
//
// 'GEOSGeometry::__construct' => ['void'],
// 'GEOSGeometry::__toString' => ['string'],
// 'GEOSGeometry::project' => ['float', 'other'=>'GEOSGeometry', 'normalized'=>'bool'],
// ...
$result = [];
foreach ($classes as $class) {
$c = new ReflectionClass($class);
$methods = $c->getMethods();
foreach ($methods as $method) {
$key = $class . '::' . $method->getName();
if ($method->getName() === '__construct') {
$returnType = 'void';
} else {
$returnType = reflectionTypeToString($method->getReturnType());
}
$value = [$returnType];
foreach ($method->getParameters() as $parameter) {
$value[$parameter->getName()] = reflectionTypeToString($parameter->getType());
}
$result[$key] = $value;
}
}
foreach ($result as $method => $signature) {
echo "'$method' => ['{$signature[0]}'";
foreach ($signature as $name => $type) {
if ($name !== 0) {
echo ", '$name'=>'$type'";
}
}
echo "],\n";
}
function reflectionTypeToString(?ReflectionType $reflectionType): string
{
if ($reflectionType instanceof ReflectionNamedType) {
$name = $reflectionType->getName();
if ($reflectionType->allowsNull()) {
$name .= '|null';
}
return $name;
}
if ($reflectionType instanceof ReflectionUnionType) {
$types = array_map(fn(ReflectionNamedType $r) => $r->getName(), $reflectionType->getTypes());
return implode('|', $types);
}
return 'mixed';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment