Legacy logger: be less noisy on cli (no double logging and oneliners)

This commit is contained in:
Igor Scheller 2023-09-09 23:45:45 +02:00 committed by Michael Weimann
parent 00f4afa2ab
commit 8438b8dc51
2 changed files with 25 additions and 3 deletions

View File

@ -14,6 +14,10 @@ class Legacy implements HandlerInterface
public function render(Request $request, Throwable $e): void public function render(Request $request, Throwable $e): void
{ {
if ($this->isCli()) {
return;
}
echo 'An <del>un</del>expected error occurred. A team of untrained monkeys has been dispatched to fix it.'; echo 'An <del>un</del>expected error occurred. A team of untrained monkeys has been dispatched to fix it.';
} }
@ -27,7 +31,7 @@ class Legacy implements HandlerInterface
$this->stripBasePath($e->getFile()), $this->stripBasePath($e->getFile()),
$e->getLine(), $e->getLine(),
$previous ? $previous->getMessage() : 'None', $previous ? $previous->getMessage() : 'None',
json_encode($e->getTrace(), PHP_SAPI == 'cli' ? JSON_PRETTY_PRINT : 0) json_encode($e->getTrace())
)); ));
if (is_null($this->log)) { if (is_null($this->log)) {
@ -50,4 +54,13 @@ class Legacy implements HandlerInterface
$basePath = realpath(__DIR__ . '/../../..') . '/'; $basePath = realpath(__DIR__ . '/../../..') . '/';
return str_replace($basePath, '', $path); return str_replace($basePath, '', $path);
} }
/**
* Test if is called from cli
* @codeCoverageIgnore
*/
protected function isCli(): bool
{
return PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg';
}
} }

View File

@ -19,14 +19,23 @@ class LegacyTest extends TestCase
*/ */
public function testRender(): void public function testRender(): void
{ {
$handler = new Legacy(); /** @var Legacy|MockObject $handler */
$handler = $this->getMockBuilder(Legacy::class)
->onlyMethods(['isCli'])
->getMock();
/** @var Request|MockObject $request */ /** @var Request|MockObject $request */
$request = $this->createMock(Request::class); $request = $this->createMock(Request::class);
/** @var Exception|MockObject $exception */ /** @var Exception|MockObject $exception */
$exception = $this->createMock(Exception::class); $exception = $this->createMock(Exception::class);
$this->expectOutputRegex('/.*error occurred.*/i'); $handler->expects($this->exactly(2))
->method('isCli')
->willReturnOnConsecutiveCalls(false, true);
$this->expectOutputRegex('/.*error occurred.*/i');
$handler->render($request, $exception);
// As CLI
$handler->render($request, $exception); $handler->render($request, $exception);
} }