Skip to content

[ErrorRenderer] Add DebugCommand for easy debugging and testing #32504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -194,5 +194,11 @@
<argument type="service" id="debug.file_link_formatter" on-invalid="null" />
<tag name="console.command" command="debug:form" />
</service>

<service id="console.command.error_renderer_debug" class="Symfony\Component\ErrorRenderer\Command\DebugCommand">
<argument type="collection" /> <!-- All error renderers are injected here by ErrorRendererPass -->
<argument type="service" id="debug.file_link_formatter" on-invalid="null" />
<tag name="console.command" command="debug:error-renderer" />
</service>
</services>
</container>
123 changes: 123 additions & 0 deletions src/Symfony/Component/ErrorRenderer/Command/DebugCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\ErrorRenderer\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\ErrorRenderer\ErrorRenderer\ErrorRendererInterface;
use Symfony\Component\ErrorRenderer\Exception\FlattenException;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;

/**
* A console command for retrieving information about error renderers.
*
* @author Yonel Ceruto <yonelceruto@gmail.com>
*
* @internal
*/
class DebugCommand extends Command
{
protected static $defaultName = 'debug:error-renderer';

private $renderers;
private $fileLinkFormatter;

/**
* @param ErrorRendererInterface[] $renderers
*/
public function __construct(array $renderers, FileLinkFormatter $fileLinkFormatter = null)
{
$this->renderers = $renderers;
$this->fileLinkFormatter = $fileLinkFormatter;

parent::__construct();
}

/**
* {@inheritdoc}
*/
protected function configure(): void
{
$this
->addArgument('format', InputArgument::OPTIONAL, sprintf('Outputs a sample in a specific format (one of %s)', implode(', ', array_keys($this->renderers))))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be an option to be consistent with other commands.

Copy link
Member Author

@yceruto yceruto Jul 12, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here "format" doesn't have the same meaning as in other commands. Other commands use the --format option to show the current information in another format, here the format argument shows a different information with a different meaning "Outputs an error sample in a specific format".

It could also be confusing because people would expect that with --format=json the list of available renderers in the specified format and that is not the case.

Do you think the description of the argument should be improved to make it clearer?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is rather "I want to see an output of the error renderer associated with this format".

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fabpot is this thread still a blocker?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think having this as argument makes sense in this case.

->setDescription('Displays all available error renderers and their formats.')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command displays all available error renderers and
their formats:

<info>php %command.full_name%</info>

Or output a sample in a specific format:

<info>php %command.full_name% json</info>

EOF
)
;
}

/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$renderers = $this->renderers;

if ($format = $input->getArgument('format')) {
if (!isset($renderers[$format])) {
throw new InvalidArgumentException(sprintf('No error renderer found for format "%s". Known format are %s.', $format, implode(', ', array_keys($this->renderers))));
}

$exception = FlattenException::createFromThrowable(new \Exception('This is a sample exception.'), 500, ['X-Debug' => false]);
$io->writeln($renderers[$format]->render($exception));
} else {
$tableRows = [];
foreach ($renderers as $format => $renderer) {
$tableRows[] = [sprintf('<fg=cyan>%s</fg=cyan>', $format), $this->formatClassLink(\get_class($renderer))];
}

$io->title('Error Renderers');
$io->text('The following error renderers are available:');
$io->newLine();
$io->table(['Format', 'Class'], $tableRows);
}
}

private function formatClassLink(string $class): string
{
if ('' === $fileLink = $this->getFileLink($class)) {
return $class;
}

return sprintf('<href=%s>%s</>', $fileLink, $class);
}

private function getFileLink(string $class): string
{
if (null === $this->fileLinkFormatter) {
return '';
}

try {
$r = new \ReflectionClass($class);
} catch (\ReflectionException $e) {
return '';
}

return $this->fileLinkFormatter->format($r->getFileName(), $r->getStartLine());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ class ErrorRendererPass implements CompilerPassInterface
{
private $rendererService;
private $rendererTag;
private $debugCommandService;

public function __construct(string $rendererService = 'error_renderer', string $rendererTag = 'error_renderer.renderer')
public function __construct(string $rendererService = 'error_renderer', string $rendererTag = 'error_renderer.renderer', string $debugCommandService = 'console.command.error_renderer_debug')
{
$this->rendererService = $rendererService;
$this->rendererTag = $rendererTag;
$this->debugCommandService = $debugCommandService;
}

/**
Expand Down Expand Up @@ -61,5 +63,9 @@ public function process(ContainerBuilder $container)

$definition = $container->getDefinition($this->rendererService);
$definition->replaceArgument(0, ServiceLocatorTagPass::register($container, $renderers));

if ($container->hasDefinition($this->debugCommandService)) {
$container->getDefinition($this->debugCommandService)->replaceArgument(0, $renderers);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\ErrorRenderer\Tests\Command;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\ErrorRenderer\Command\DebugCommand;
use Symfony\Component\ErrorRenderer\ErrorRenderer\JsonErrorRenderer;
use Symfony\Component\ErrorRenderer\ErrorRenderer\TxtErrorRenderer;
use Symfony\Component\ErrorRenderer\ErrorRenderer\XmlErrorRenderer;

class DebugCommandTest extends TestCase
{
public function testAvailableRenderers()
{
$tester = $this->createCommandTester();
$ret = $tester->execute([], ['decorated' => false]);

$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertSame(<<<TXT

Error Renderers
===============

The following error renderers are available:

-------- -----------------------------------------------------------------
Format Class
-------- -----------------------------------------------------------------
json Symfony\Component\ErrorRenderer\ErrorRenderer\JsonErrorRenderer
xml Symfony\Component\ErrorRenderer\ErrorRenderer\XmlErrorRenderer
txt Symfony\Component\ErrorRenderer\ErrorRenderer\TxtErrorRenderer
-------- -----------------------------------------------------------------


TXT
, $tester->getDisplay(true));
}

public function testFormatArgument()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(['format' => 'json'], ['decorated' => false]);

$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertSame(<<<TXT
{
"title": "Internal Server Error",
"status": 500,
"detail": "This is a sample exception."
}

TXT
, $tester->getDisplay(true));
}

private function createCommandTester()
{
$command = new DebugCommand([
'json' => new JsonErrorRenderer(false),
'xml' => new XmlErrorRenderer(false),
'txt' => new TxtErrorRenderer(false),
]);

$application = new Application();
$application->add($command);

return new CommandTester($application->find('debug:error-renderer'));
}

/**
* @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException
* @expectedExceptionMessage No error renderer found for format "foo". Known format are json, xml, txt.
*/
public function testInvalidFormat()
{
$tester = $this->createCommandTester();
$tester->execute(['format' => 'foo'], ['decorated' => false]);
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/ErrorRenderer/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"psr/log": "~1.0"
},
"require-dev": {
"symfony/console": "^4.4",
"symfony/dependency-injection": "^4.4",
"symfony/http-kernel": "^4.4"
},
Expand Down