/
MethodDocBlockGenerator.php
77 lines (60 loc) · 2.4 KB
/
MethodDocBlockGenerator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
namespace PiedWeb\MethodDocBlockGenerator;
class MethodDocBlockGenerator
{
public function __construct(private readonly bool $addLink = true)
{
}
public function run(string $extensionClassName): string
{
if (! class_exists($extensionClassName)) {
throw new \Exception();
}
$reflectionClass = new \ReflectionClass($extensionClassName);
$methods = $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC);
$phpDoc = '';
foreach ($methods as $method) {
if (\in_array($method->getName(), ['__construct', 'register'])) {
continue;
}
$paramStrings = [];
foreach ($method->getParameters() as $parameter) {
$paramString = $this->formatType($parameter->getType()).' $'.$parameter->getName();
if ($parameter->isDefaultValueAvailable()) {
$defaultValue = $parameter->getDefaultValue();
$paramString .= ' = '.str_replace("\n", '', var_export($defaultValue, true));
}
$paramStrings[] = $paramString;
}
$returnType = $this->formatType($method->getReturnType());
$phpDoc .= ' * @method '.('' === $returnType ? '' : $returnType.' ').$method->getName().'('.implode(', ', $paramStrings).')';
if ($this->addLink) {
$phpDoc .= "\n".' * '
.ltrim(str_replace(\Safe\preg_replace('#/vendor/.+$#', '', __DIR__), '', $reflectionClass->getFileName() ?: ''), '/')
.':'.$method->getStartLine()
."\n".' * ';
}
$phpDoc .= "\n";
}
return $phpDoc;
}
private function formatType(\ReflectionType|null $returnType): string
{
if (null === $returnType) {
return '';
}
if ($returnType instanceof \ReflectionNamedType) {
return false === $returnType->isBuiltin() ?
(($returnType->allowsNull() ? '?' : '').'\\'.$returnType->getName())
: $returnType;
}
if ($returnType instanceof \ReflectionUnionType) {
$toReturn = [];
foreach ($returnType->getTypes() as $type) {
$toReturn[] = $this->formatType($type);
}
return implode('|', $toReturn);
}
throw new \Exception();
}
}