Skip to content

Commit

Permalink
Merge pull request #55 from NikolayAleshin/display_of_all_errors_in_t…
Browse files Browse the repository at this point in the history
…he_console

Improved error display system
  • Loading branch information
shcherbanich authored Oct 25, 2023
2 parents 9348970 + eacb90c commit 8136dcb
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 25 deletions.
57 changes: 57 additions & 0 deletions src/Core/Logger/Handler/GenerationErrorsHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

namespace BumbleDocGen\Core\Logger\Handler;

use BumbleDocGen\Core\Renderer\Context\RendererContext;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;

final class GenerationErrorsHandler extends AbstractProcessingHandler
{
private array $records = [];

public function __construct(
private RendererContext $rendererContext,
$level = Logger::WARNING,
bool $bubble = true
) {
parent::__construct($level, $bubble);
}

protected function write(array $record): void
{
$initiator = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)[3] ?? [];
$fileName = str_replace([
dirname(__DIR__, 4),
getcwd()
], '', $initiator['file'] ?? '');
$line = $initiator['line'] ?? '';

$initiator = "{$fileName}#{$line}";
$entityDocUrl = $this->rendererContext->getCurrentDocumentedEntityWrapper()?->getDocUrl();
if ($entityDocUrl) {
$initiator .= "\n{$entityDocUrl}";
} elseif ($this->rendererContext->getCurrentTemplateFilePatch()) {
$initiator .= "\n{$this->rendererContext->getCurrentTemplateFilePatch()}";
}

$this->records[] = [
"type" => $record['level_name'],
"msg" => $record['message'],
'initiator' => $initiator,
'isRenderingError' => boolval($this->rendererContext->getCurrentTemplateFilePatch())
];
}

public function getRecords(): array
{
return $this->records;
}

public function addRecords(array $records): void
{
$this->records = array_merge($this->records, $records);
}
}
57 changes: 35 additions & 22 deletions src/Core/Renderer/RendererIteratorFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use BumbleDocGen\Core\Configuration\Configuration;
use BumbleDocGen\Core\Configuration\ConfigurationParameterBag;
use BumbleDocGen\Core\Configuration\Exception\InvalidConfigurationParameterException;
use BumbleDocGen\Core\Logger\Handler\GenerationErrorsHandler;
use BumbleDocGen\Core\Parser\Entity\RootEntityCollectionsGroup;
use BumbleDocGen\Core\Plugin\Event\Renderer\OnGetProjectTemplatesDirs;
use BumbleDocGen\Core\Plugin\PluginEventDispatcher;
Expand Down Expand Up @@ -42,6 +43,7 @@ public function __construct(
private PluginEventDispatcher $pluginEventDispatcher,
private OutputStyle $io,
private Logger $logger,
private GenerationErrorsHandler $generationErrorsHandler,
) {
}

Expand Down Expand Up @@ -73,12 +75,22 @@ public function getTemplatesWithOutdatedCache(): \Generator
);
$pb->setStepDescription("Processing {$templateFile->getRelativeDocPath()} file");

$errorsBeforeGenerationCount = count($this->generationErrorsHandler->getRecords());

$relativeTemplateName = $templateFile->getRelativeTemplatePath() ?: $templateFile->getRelativeDocPath();
$file = $this->prepareDocFileForRendering($templateFile);
if (!$file) {
++$skippedCount;
$this->moveCachedDataToCurrentData($relativeTemplateName);
$this->logger->info("Use cached version `{$templateFile->getRealPath()}`");
continue;
}
yield $file;

$errorsCount = count($this->generationErrorsHandler->getRecords());
if ($errorsBeforeGenerationCount === $errorsCount) {
$this->saveContextCacheForSingleDocument($relativeTemplateName);
}
}

$processed = $finder->count() - $skippedCount;
Expand Down Expand Up @@ -121,19 +133,8 @@ private function prepareDocFileForRendering(TemplateFile $templateFile): ?Templa
filePath: $templateFile->getRealPath()
);
$this->rendererContext->addDependency($fileDependency);
$this->sharedCompressedDocumentFileCache->set(
$this->getOperationsLogCacheKey($relativeTemplateName),
$this->rootEntityCollectionsGroup->getOperationsLogWithoutDuplicates()
);

$this->sharedCompressedDocumentFileCache->set(
$this->getFilesDependenciesCacheKey($relativeTemplateName),
$this->rendererContext->getDependencies()
);
return $templateFile;
}
$this->moveCachedDataToCurrentData($relativeTemplateName);
$this->logger->info("Use cached version `{$templateFile->getRealPath()}`");
return null;
}

Expand All @@ -156,10 +157,10 @@ public function getDocumentedEntityWrappersWithOutdatedCache(): \Generator
$this->rendererContext->clearDependencies();
$this->rootEntityCollectionsGroup->clearOperationsLog();

$this->rendererContext->setCurrentDocumentedEntityWrapper($entityWrapper);
$errorsBeforeGenerationCount = count($this->generationErrorsHandler->getRecords());

$this->rendererContext->setCurrentDocumentedEntityWrapper($entityWrapper);
$this->markFileNameAsRendered($entityWrapper->getDocUrl());

$filesDependenciesKey = "{$entityWrapper->getEntityName()}_{$entityWrapper->getParentDocFilePath()}";
if (
!$this->configuration->useSharedCache() ||
Expand All @@ -181,15 +182,13 @@ public function getDocumentedEntityWrappersWithOutdatedCache(): \Generator
continue;
}

$this->sharedCompressedDocumentFileCache->set(
$this->getOperationsLogCacheKey($entityWrapper->getEntityName()),
$this->rootEntityCollectionsGroup->getOperationsLogWithoutDuplicates()
);

$this->sharedCompressedDocumentFileCache->set(
$this->getFilesDependenciesCacheKey($filesDependenciesKey),
$this->rendererContext->getDependencies()
);
$errorsCount = count($this->generationErrorsHandler->getRecords());
if ($errorsBeforeGenerationCount === $errorsCount) {
$this->saveContextCacheForSingleDocument(
$entityWrapper->getEntityName(),
$entityWrapper->getParentDocFilePath()
);
}
$this->rendererContext->clearDependencies();
$this->rootEntityCollectionsGroup->clearOperationsLog();
}
Expand Down Expand Up @@ -371,6 +370,20 @@ private function moveCachedDataToCurrentData(string $templateFileName, ?string $
}
}

private function saveContextCacheForSingleDocument(string $docKey, ?string $namespace = null): void
{
$this->sharedCompressedDocumentFileCache->set(
$this->getOperationsLogCacheKey($docKey),
$this->rootEntityCollectionsGroup->getOperationsLogWithoutDuplicates()
);

$filesDependenciesKey = $namespace ? "{$docKey}_{$namespace}" : $docKey;
$this->sharedCompressedDocumentFileCache->set(
$this->getFilesDependenciesCacheKey($filesDependenciesKey),
$this->rendererContext->getDependencies()
);
}

private function getOperationsLogCacheKey(string $key): string
{
return "operations_log_{$key}";
Expand Down
38 changes: 37 additions & 1 deletion src/DocGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use BumbleDocGen\Core\Configuration\Configuration;
use BumbleDocGen\Core\Configuration\Exception\InvalidConfigurationParameterException;
use BumbleDocGen\Core\Logger\Handler\GenerationErrorsHandler;
use BumbleDocGen\Core\Parser\Entity\RootEntityCollectionsGroup;
use BumbleDocGen\Core\Parser\ProjectParser;
use BumbleDocGen\Core\Plugin\PluginEventDispatcher;
Expand All @@ -22,7 +23,9 @@
use DI\NotFoundException;
use Monolog\Logger;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Helper\TableSeparator;
use Symfony\Component\Console\Style\OutputStyle;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
Expand All @@ -44,6 +47,7 @@ public function __construct(
private ProjectParser $parser,
private ParserHelper $parserHelper,
private Renderer $renderer,
private GenerationErrorsHandler $generationErrorsHandler,
private RootEntityCollectionsGroup $rootEntityCollectionsGroup,
private Logger $logger
) {
Expand Down Expand Up @@ -325,8 +329,40 @@ public function generate(): void
$time = microtime(true) - $start;
$memory = memory_get_usage(true) - $memory;

$warningMessages = $this->generationErrorsHandler->getRecords();

if (empty($warningMessages)) {
$this->io->writeln("<info>Documentation successfully generated</>");
} else {
$this->io->writeln("<comment>Generation completed with errors</>");

$this->io->getFormatter()->setStyle('warning', new OutputFormatterStyle('yellow'));
$badErrorStyle = new OutputFormatterStyle('red', '#ff0', ['bold']);
$this->io->getFormatter()->setStyle('critical', $badErrorStyle);
$this->io->getFormatter()->setStyle('alert', $badErrorStyle);
$this->io->getFormatter()->setStyle('emergency', $badErrorStyle);
$table = $this->io->createTable();

$rows = [];
$warningMessagesCount = count($warningMessages);
foreach ($warningMessages as $i => $warningMessage) {
$tag = strtolower($warningMessage['type']);
$rows[] = ["<{$tag}>{$warningMessage['type']}</>", "<{$tag}>{$warningMessage['msg']}</>"];
if ($warningMessage['isRenderingError']) {
$rows[] = ['', '<options=conceal,underscore>This error occurs during the document rendering process</>'];
}
$rows[] = ['', $warningMessage['initiator']];
if ($warningMessagesCount - $i !== 1) {
$rows[] = new TableSeparator();
}
}
$table->setStyle('box');
$table->addRows($rows);
$table->render();
$this->io->newLine();
}

$this->io->writeln("<info>Documentation successfully generated</>");
$this->io->writeln("<info>Performance</>");
$this->io->table([], [
['Execution time:', "<options=bold,underscore>{$time} sec.</>"],
['Allocated memory:', '<options=bold,underscore>' . Helper::formatMemory(memory_get_usage(true)) . '</>'],
Expand Down
7 changes: 5 additions & 2 deletions src/di-config.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

use Bramus\Monolog\Formatter\ColoredLineFormatter;
use BumbleDocGen\Core\Configuration\ConfigurationParameterBag;
use BumbleDocGen\Core\Configuration\ValueResolver\ArgvValueResolver;
use BumbleDocGen\Core\Configuration\ValueResolver\InternalValueResolver;
use BumbleDocGen\Core\Configuration\ValueResolver\RefValueResolver;
use BumbleDocGen\Core\Configuration\ValueResolver\ArgvValueResolver;
use BumbleDocGen\Core\Logger\Handler\GenerationErrorsHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
Expand All @@ -16,6 +17,7 @@
use Symfony\Component\Console\Style\SymfonyStyle;

return [
GenerationErrorsHandler::class => \DI\autowire(GenerationErrorsHandler::class),
Logger::class => \DI\autowire(Logger::class)
->constructor(
name: 'Bumble doc gen',
Expand Down Expand Up @@ -45,7 +47,8 @@
dateFormat: 'Y-m-d H:i:s',
format: "[%datetime%] > %level_name% > %message%\n",
)
)
),
\DI\get(GenerationErrorsHandler::class)
]
),
LoggerInterface::class => \DI\get(Logger::class),
Expand Down

0 comments on commit 8136dcb

Please sign in to comment.