generated from ghostwriter/wip
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_docs.php
99 lines (74 loc) · 2.68 KB
/
generate_docs.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
declare(strict_types=1);
require __DIR__ . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
final class DocsGenerator
{
private const string NAMESPACE_PREFIX = 'Ghostwriter\\PsrPhpunitAssertions';
/**
* @throws \Throwable
*/
public static function generate(string $sourceDirectory, string $outputFile): void
{
$traits = self::getTraitClasses($sourceDirectory);
$markdown = "# Psr Phpunit Assertions Docs\n\n";
foreach ($traits as $trait) {
$markdown .= self::generateTraitDocs($trait);
}
$markdown .= "\n";
\file_put_contents($outputFile, $markdown);
}
private static function extractClassName(string $file, string $sourceDirectory): string
{
return \sprintf('%s\\%s', self::NAMESPACE_PREFIX, \basename(\str_replace($sourceDirectory, '', $file), '.php'));
}
private static function formatMethodSignature(\ReflectionMethod $method): string
{
$params = \array_map(
static fn ($param) => \mb_trim(
($param->hasType() ? $param->getType() . ' ' : '') . '$' . $param->getName()
),
$method->getParameters()
);
return \sprintf(
'public%s function %s(%s): %s',
$method->isStatic() ? ' static' : '',
$method->getName(),
\implode(', ', $params),
$method->hasReturnType() ? $method->getReturnType() : 'void'
);
}
/**
* @throws \Throwable
*/
private static function generateTraitDocs(string $trait): string
{
$reflection = new \ReflectionClass($trait);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if ([] === $methods) {
return '';
}
$trait = $reflection->getShortName();
$markdown = \sprintf('## `%s`', $trait);
$markdown .= \sprintf("\n\n```php\n<?php\ntrait %s {\n", $trait);
$indent = \str_repeat(' ', 4);
foreach ($methods as $method) {
$markdown .= $indent . self::formatMethodSignature($method) . ";\n";
}
$markdown .= "}\n```\n\n";
return $markdown;
}
private static function getTraitClasses(string $sourceDirectory): array
{
$files = \glob($sourceDirectory . '/*Trait.php');
$traits = [];
foreach ($files as $file) {
$className = self::extractClassName($file, $sourceDirectory);
if (! \trait_exists($className)) {
continue;
}
$traits[] = $className;
}
return $traits;
}
}
\DocsGenerator::generate(__DIR__ . '/src', __DIR__ . '/docs/README.md');