Skip to content

Commit

Permalink
Fix BrowserConsoleHandler formatting
Browse files Browse the repository at this point in the history
This resolves an issue whereby all styles would be applied in reverse
order to the formatting markers.
  • Loading branch information
Trevor North authored and Seldaek committed Nov 12, 2019
1 parent 65f1f30 commit 0ff3a9b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/Monolog/Handler/BrowserConsoleHandler.php
Expand Up @@ -164,21 +164,22 @@ private static function generateScript()

private static function handleStyles($formatted)
{
$args = array(static::quote('font-weight: normal'));
$args = array();
$format = '%c' . $formatted;
preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

foreach (array_reverse($matches) as $match) {
$args[] = static::quote(static::handleCustomStyles($match[2][0], $match[1][0]));
$args[] = '"font-weight: normal"';
$args[] = static::quote(static::handleCustomStyles($match[2][0], $match[1][0]));

$pos = $match[0][1];
$format = substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . substr($format, $pos + strlen($match[0][0]));
}

array_unshift($args, static::quote($format));
$args[] = static::quote('font-weight: normal');
$args[] = static::quote($format);

return $args;
return array_reverse($args);
}

private static function handleCustomStyles($style, $string)
Expand Down
16 changes: 16 additions & 0 deletions tests/Monolog/Handler/BrowserConsoleHandlerTest.php
Expand Up @@ -48,6 +48,22 @@ public function testStyling()
$this->assertEquals($expected, $this->generateScript());
}

public function testStylingMultiple()
{
$handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter());

$handler->handle($this->getRecord(Logger::DEBUG, 'foo[[bar]]{color: red}[[baz]]{color: blue}'));

$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.log("%cfoo%cbar%c%cbaz%c", "font-weight: normal", "color: red", "font-weight: normal", "color: blue", "font-weight: normal");
}})(console);
EOF;

$this->assertEquals($expected, $this->generateScript());
}

public function testEscaping()
{
$handler = new BrowserConsoleHandler();
Expand Down

0 comments on commit 0ff3a9b

Please sign in to comment.