Коммит 43599f61 создал по автору Коротков Данила's avatar Коротков Данила
Просмотр файлов

Разбил сложную логику

владелец 71d09c20
......@@ -58,6 +58,10 @@
| public | `createDocs(string $outputPath): void`<br> |
| public | `createHeaderString(string $fullClassName): string`<br> |
| public | `createBodyString(string $fullClassName): string`<br> |
| private | `buildMethodSignature(ReflectionMethod $method): string`<br>Builds the method signature with parameters and return type. |
| private | `extractDocBlockDescription(ReflectionMethod $method): string`<br>Extracts the description from the DocBlock of a method. |
| private | `getParameterTypeAndName(ReflectionParameter $param): string`<br>Gets the type and name of a parameter. |
| private | `getTypeAsString(ReflectionType $type): string`<br>Converts a ReflectionType to a string representation. |
| private | `getAnchorName(string $className): string`<br> |
<hr>
......
......@@ -24,7 +24,7 @@ class DocumentationCommand
$reflection = new \ReflectionClass(\Composer\Autoload\ClassLoader::class);
$dir = dirname(dirname(dirname($reflection->getFileName())));
Cli::printer("Enter source directory: ", "cyan");
Cli::printer("Enter source directory: ", "magneta");
$sourceDir = trim(fgets(fopen("php://stdin", "r")));
$inputPath = $dir . '/' . $sourceDir;
......@@ -32,16 +32,16 @@ class DocumentationCommand
throw new \InvalidArgumentException();
}
Cli::printer("Enter file name: ", "cyan");
Cli::printer("Enter file name: ", "magneta");
$fileName = trim(fgets(fopen("php://stdin", "r")));
Cli::printer("Enter output type: ", "magneta");
Cli::printer("(Html: html)[Markdowm: md]: ", "cyan");
Cli::printer("(Html: html)[Markdowm: md]: ", "magneta");
$fileType = trim(fgets(fopen("php://stdin", "r")));
if ($fileType === 'html') {
Cli::printer("Сhoose a framework: ", "magneta");
Cli::printer("(Foundation: f, Uikit: ui)[Bootstrap: bsp]: ", "cyan");
Cli::printer("(Foundation: f, Uikit: ui)[Bootstrap: bsp]: ", "magneta");
$frameworkType = trim(fgets(fopen("php://stdin", "r")));
$this->docCreator = new HtmlCreator($frameworkType);
$outputPath = $dir . '/' . $fileName . '.html';
......
......@@ -42,140 +42,120 @@ class MarkdownCreator implements DocumentationCreatorInterface
*/
public function createBodyString(string $fullClassName): string
{
// Create a ReflectionClass instance to analyze the class structure.
$class = new \ReflectionClass($fullClassName);
$methods = $class->getMethods();
// Generate the header section with an anchor link for navigation.
$header = "\n\n" . '<a id="' . $this->getAnchorName($fullClassName) . '"></a>';
$header .= "\n\n### Class: " . $fullClassName . "\n";
// Initialize the Markdown table structure with headers.
$table = "| Visibility | Function |\n|:-----------|:---------|\n";
// Loop through all methods of the class.
foreach ($methods as $method) {
// Get visibility modifiers (e.g., public, protected, static).
$modifiers = implode(' ', \Reflection::getModifierNames($method->getModifiers()));
$signature = $this->buildMethodSignature($method);
$docBlock = $this->extractDocBlockDescription($method);
// Start building the method signature.
$signature = '`' . $method->getName() . '(';
$params = [];
// Process each parameter of the method.
foreach ($method->getParameters() as $param) {
$type = '';
if ($param->getType()) {
$reflectionType = $param->getType();
// Handle union types (e.g., string|int|string|null).
if ($reflectionType instanceof \ReflectionUnionType) {
$types = [];
// Extract each type from the union and store it in an array.
foreach ($reflectionType->getTypes() as $typePart) {
$typeName = (string)$typePart;
$types[] = $typeName;
}
// Join the types with '|' (escaped later).
$type = implode('|', $types);
} else {
// Handle single types (e.g., string, ?callable).
$type = (string)$reflectionType;
// Add '?' prefix for nullable types if not already present.
if ($reflectionType->allowsNull() && !str_starts_with($type, '?')) {
$type = '?' . $type;
}
}
// Escape '|' characters for Markdown compatibility.
$type = str_replace('|', '\|', $type);
}
// Append the parameter type and name to the list of parameters.
$params[] = $type . ' $' . $param->getName();
}
// Combine the method signature and description.
$functionColumn = $signature . "<br>" . $docBlock;
// Join all parameters with commas and close the method signature.
$signature .= implode(', ', $params) . ')';
// Add the row to the Markdown table.
$table .= "| {$modifiers} | {$functionColumn} |\n";
}
// Handle return type of the method.
$returnType = $method->getReturnType();
$returnTypeName = '';
return $header . $table;
}
/**
* Builds the method signature with parameters and return type.
*
* @param \ReflectionMethod $method
* @return string
*/
private function buildMethodSignature(\ReflectionMethod $method): string
{
$signature = '`' . $method->getName() . '(';
$params = [];
if ($returnType) {
if ($returnType instanceof \ReflectionUnionType) {
$types = [];
foreach ($method->getParameters() as $param) {
$params[] = $this->getParameterTypeAndName($param);
}
// Extract each type from the union return type.
foreach ($returnType->getTypes() as $typePart) {
$types[] = (string)$typePart;
}
$signature .= implode(', ', $params) . ')';
$returnType = $method->getReturnType();
if ($returnType) {
$returnTypeName = $this->getTypeAsString($returnType);
$signature .= ': ' . $returnTypeName;
}
// Join the types with '|' (escaped later).
$returnTypeName = implode('|', $types);
} else {
// Handle single return types (e.g., string, ?int).
$returnTypeName = (string)$returnType;
return $signature . '`';
}
// Add '?' prefix for nullable return types if not already present.
if ($returnType->allowsNull() && !str_starts_with($returnTypeName, '?')) {
$returnTypeName = '?' . $returnTypeName;
}
}
/**
* @param \ReflectionMethod $method
* @return string
*/
private function extractDocBlockDescription(\ReflectionMethod $method): string
{
if (!$method->getDocComment()) {
return '';
}
// Escape '|' characters for Markdown compatibility.
$returnTypeName = str_replace('|', '\|', $returnTypeName);
$docBlockRaw = substr($method->getDocComment(), 3, -2); // Убираем /**
$lines = explode("\n", $docBlockRaw);
$descriptionLines = [];
// Append the return type to the method signature.
$signature .= ': ' . $returnTypeName;
foreach ($lines as $line) {
$cleanLine = trim(str_replace(['*', ' '], '', $line));
if (str_starts_with($cleanLine, '@')) {
break;
}
// Close the method signature with backticks.
$signature .= '`';
// Extract the description from the DocBlock comment.
$docBlock = '';
if ($method->getDocComment()) {
// Remove the leading /** and trailing */ from the DocBlock.
$docBlockRaw = substr($method->getDocComment(), 3, -2);
$lines = explode("\n", $docBlockRaw);
$descriptionLines = [];
foreach ($lines as $line) {
// Clean up the line by removing unnecessary characters (*, -, spaces).
$cleanLine = trim(str_replace(['*', '-', ' '], '', $line));
// Stop processing if we encounter a tag (e.g., @param, @return).
if (str_starts_with($cleanLine, '@')) {
break;
}
// Collect non-empty lines as part of the description.
if (!empty($cleanLine)) {
$descriptionLines[] = $cleanLine;
}
}
// Combine the description lines into a single string.
if (!empty($descriptionLines)) {
$docBlock = implode(' ', $descriptionLines);
}
if (!empty($cleanLine)) {
$descriptionLines[] = $cleanLine;
}
}
// Combine the method signature and description into one column.
$functionColumn = $signature . "<br>" . $docBlock;
return !empty($descriptionLines) ? implode('<br>', $descriptionLines) : '';
}
// Add the row to the Markdown table.
$table .= "| {$modifiers} | {$functionColumn} |\n";
/**
* @param \ReflectionParameter $param
* @return string
*/
private function getParameterTypeAndName(\ReflectionParameter $param): string
{
$type = '';
if ($param->getType()) {
$type = $this->getTypeAsString($param->getType());
}
// Return the full Markdown output (header + table).
return $header . $table;
return $type . ' $' . $param->getName();
}
/**
* Converts a ReflectionType to a string representation.
*
* @param \ReflectionType $type
* @return string
*/
private function getTypeAsString(\ReflectionType $type): string
{
if ($type instanceof \ReflectionUnionType) {
$types = array_map(fn($typePart) => (string)$typePart, $type->getTypes());
$typeString = implode('|', $types);
} else {
$typeString = (string)$type;
// Add '?' prefix for nullable types if not already present.
if ($type->allowsNull() && !str_starts_with($typeString, '?')) {
$typeString = '?' . $typeString;
}
}
// Escape '|' characters for Markdown compatibility.
return str_replace('|', '\|', $typeString);
}
/**
......
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать