MediaWiki master
CodeHighlighter.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Content;
4
6use Wikimedia\ObjectFactory\ObjectFactory;
7
15
17 private ?array $providers = null;
18
19 public function __construct(
20 private readonly ObjectFactory $objectFactory,
21 private readonly array $providerSpecs,
22 ) {
23 }
24
28 private function getProviders(): array {
29 $this->providers ??= array_map(
30 fn ( $spec ): CodeHighlightProvider => $this->objectFactory->createObject( $spec, [
31 'assertClass' => CodeHighlightProvider::class,
32 ] ),
33 $this->providerSpecs
34 );
35 return $this->providers;
36 }
37
45 public function highlight( string $code, CodeHighlighterOptions $options ): CodeHighlighterOutput {
46 foreach ( $this->getProviders() as $provider ) {
47 if ( $provider->isSupportedLanguage( $options->language ) ) {
48 return $provider->highlight( $code, $options );
49 }
50 }
51
52 // No highlighter supports this language. Fall back to unhighlighted code.
53 // Advanced options like line numbers, highlighting and copy buttons are not supported in fallback.
54 if ( $options->inline ) {
55 $html = Html::element( 'code',
56 [ 'dir' => $options->dir, 'class' => implode( ' ', $options->classes ) ],
57 $code
58 );
59 } else {
60 $html = Html::element( 'pre',
61 [ 'dir' => $options->dir, 'class' => 'mw-code ' . implode( ' ', $options->classes ) ],
62 "\n" . $code . "\n"
63 ) . "\n";
64 }
65
66 return new CodeHighlighterOutput( $html );
67 }
68
69}
Value object for code highlighting output.
Service for syntax highlighting.
highlight(string $code, CodeHighlighterOptions $options)
Highlight the given code based on the given language.
__construct(private readonly ObjectFactory $objectFactory, private readonly array $providerSpecs,)
This class is a collection of static functions that serve two purposes:
Definition Html.php:44
element(SerializerNode $parent, SerializerNode $node, $contents)