Skip to content

Commit 6f9742e

Browse files
committed
[FEATURE] Make code extension work out-of-the box
* Add default templates * Use it for our own documentation * Treat rest and unknown language as "text" * Use warnings for unknown languages and supply debugging information * As i also want to use the debugInformation for our third-party highlighter, I introduced a new global into twig which only contains the array. This way third party packages do not have to know about the RenderContext.
1 parent d54f8a4 commit 6f9742e

File tree

9 files changed

+42
-18
lines changed

9 files changed

+42
-18
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{{ node.value|highlight(node.language) }}

packages/guides-code/src/Code/DependencyInjection/CodeExtension.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@
1212
use Symfony\Component\Config\FileLocator;
1313
use Symfony\Component\DependencyInjection\ContainerBuilder;
1414
use Symfony\Component\DependencyInjection\Extension\Extension;
15+
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
1516
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
1617

1718
use function assert;
1819
use function dirname;
1920

20-
class CodeExtension extends Extension implements ConfigurationInterface
21+
class CodeExtension extends Extension implements ConfigurationInterface, PrependExtensionInterface
2122
{
2223
public function getConfigTreeBuilder(): TreeBuilder
2324
{
@@ -70,4 +71,11 @@ public function getConfiguration(array $config, ContainerBuilder $container): Co
7071
{
7172
return $this;
7273
}
74+
75+
public function prepend(ContainerBuilder $container): void
76+
{
77+
$container->prependExtensionConfig('guides', [
78+
'base_template_paths' => [dirname(__DIR__, 3) . '/resources/template/html'],
79+
]);
80+
}
7381
}

packages/guides-code/src/Code/Highlighter/HighlightPhpHighlighter.php

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Psr\Log\LoggerInterface;
99
use Throwable;
1010

11+
use function array_merge;
1112
use function assert;
1213
use function is_string;
1314
use function preg_replace;
@@ -32,9 +33,10 @@ public function __construct(
3233
) {
3334
}
3435

35-
public function __invoke(string $language, string $code): HighlightResult
36+
/** @param $debugInformation array<string, string|null> */
37+
public function __invoke(string $language, string $code, array $debugInformation): HighlightResult
3638
{
37-
if ($language === 'text') {
39+
if ($language === 'text' || $language === '' || $language === 'rest') {
3840
// Highlighter escapes correctly the code, we need to manually escape only for "text" code
3941
$code = $this->escapeForbiddenCharactersInsideCodeBlock($code);
4042

@@ -49,9 +51,9 @@ public function __invoke(string $language, string $code): HighlightResult
4951

5052
return new HighlightResult($highlightLanguage, $highlightValue);
5153
} catch (Throwable $e) {
52-
$this->logger->error(
54+
$this->logger->warning(
5355
<<<'MESSAGE'
54-
Error highlighting {language} code block!
56+
Highlighting {language} code-block failed
5557
5658
Code:
5759
@@ -61,11 +63,11 @@ public function __invoke(string $language, string $code): HighlightResult
6163
6264
{exception}
6365
MESSAGE,
64-
[
66+
array_merge($debugInformation, [
6567
'language' => $language,
6668
'code' => $code,
6769
'exception' => $e,
68-
],
70+
]),
6971
);
7072

7173
return new HighlightResult($language, $code);

packages/guides-code/src/Code/Highlighter/Highlighter.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66

77
interface Highlighter
88
{
9-
public function __invoke(string $language, string $code): HighlightResult;
9+
/** @param array<string, string|null> $debugInformation */
10+
public function __invoke(string $language, string $code, array $debugInformation): HighlightResult;
1011
}

packages/guides-code/src/Code/Twig/CodeExtension.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
use Twig\Extension\AbstractExtension;
99
use Twig\TwigFilter;
1010

11+
use function is_array;
12+
1113
class CodeExtension extends AbstractExtension
1214
{
1315
public function __construct(
@@ -21,12 +23,18 @@ public function __construct(
2123
public function getFilters(): array
2224
{
2325
return [
24-
new TwigFilter('highlight', $this->highlight(...), ['is_safe' => ['html']]),
26+
new TwigFilter('highlight', $this->highlight(...), ['is_safe' => ['html'], 'needs_context' => true]),
2527
];
2628
}
2729

28-
public function highlight(string $code, string $language = 'text'): string
30+
/** @param array<string, mixed> $context */
31+
public function highlight(array $context, string $code, string $language = 'text'): string
2932
{
30-
return ($this->highlighter)($language, $code)->code;
33+
$debugInformation = $context['debugInformation'] ?? [];
34+
if (!is_array($debugInformation)) {
35+
$debugInformation = [];
36+
}
37+
38+
return ($this->highlighter)($language, $code, $debugInformation)->code;
3139
}
3240
}

packages/guides-code/tests/unit/Highlighter/HighlightPhpHighlighterTest.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public function testItEscapesCharactersForbiddenInPreTags(): void
2323
(__)\ )\/\
2424
||----w |
2525
|| ||
26-
TXT);
26+
TXT, []);
2727
self::assertSame(<<<'TXT'
2828
&lt; I'm an expert in my field. &gt;
2929
---------------------------
@@ -46,7 +46,7 @@ public function testItIsIdempotent(): void
4646
(__)\ )\/\
4747
||----w |
4848
|| ||
49-
TXT);
49+
TXT, []);
5050
self::assertSame(<<<'TXT'
5151
&lt; I'm an expert in my field. &gt;
5252
---------------------------
@@ -65,10 +65,10 @@ public function testItCatchesAndLogsExceptions(): void
6565
$highlight = new HighlightPhpHighlighter($highlighter, $logger);
6666

6767
$highlighter->method('highlight')->willThrowException(new Exception('test'));
68-
$highlight('php', 'echo "Hello world";');
68+
$highlight('php', 'echo "Hello world";', []);
6969

70-
self::assertTrue($logger->hasErrorRecords(), 'An error should be logged');
71-
self::assertTrue($logger->hasErrorThatPasses(static function (array $record): bool {
70+
self::assertTrue($logger->hasWarningRecords(), 'An error should be logged');
71+
self::assertTrue($logger->hasWarningThatPasses(static function (array $record): bool {
7272
return isset($record['context']['exception'], $record['context']['code'])
7373
&& $record['context']['code'] === 'echo "Hello world";';
7474
}));
@@ -88,6 +88,6 @@ public function testItUnderstandsAliases(): void
8888
->with('php', '#[Attribute]')
8989
->willReturn((object) ['language' => 'php', 'value' => '<span class="hljs-attribute">#[Attribute]</span>']);
9090

91-
$highlight('attribute', '#[Attribute]');
91+
$highlight('attribute', '#[Attribute]', []);
9292
}
9393
}

packages/guides/resources/template/html/body/code.html.twig

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,7 @@
99
{%- endif -%}
1010
<pre{% if node.classes %} class="{{ node.classesString }}"{% endif %}><code class="language-{{ node.language }}{{ node.startingLineNumber ? ' line-numbers' }}"
1111
{%- if node.startingLineNumber %} data-start="{{ node.startingLineNumber }}"{% endif -%}
12-
{%- if node.emphasizeLines %} data-emphasize-lines="{{ node.emphasizeLines }}"{% endif -%}>{{ node.value }}</code></pre>
12+
{%- if node.emphasizeLines %} data-emphasize-lines="{{ node.emphasizeLines }}"{% endif -%}>
13+
{%- include "body/code/highlighted-code.html.twig" -%}
14+
</code></pre>
1315
{%- endif -%}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{{ node.value }}

packages/guides/src/Twig/TwigTemplateRenderer.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ public function renderTemplate(RenderContext $context, string $template, array $
2828
{
2929
$twig = $this->environmentBuilder->getTwigEnvironment();
3030
$twig->addGlobal('env', $context);
31+
$twig->addGlobal('debugInformation', $context->getLoggerInformation());
3132

3233
return $twig->render($template, $params);
3334
}

0 commit comments

Comments
 (0)