Trait yii\apidoc\helpers\MarkdownHighlightTrait
| Implemented by | yii\apidoc\helpers\ApiMarkdown |
|---|---|
| Available since extension's version | 2.1.1 |
| Source Code | https://github.com/yiisoft/yii2-apidoc/blob/master/helpers/MarkdownHighlightTrait.php |
MarkdownHighlightTrait provides code highlighting functionality for Markdown Parsers.
Public Methods
| Method | Description | Defined By |
|---|---|---|
| highlight() | Highlights code | yii\apidoc\helpers\MarkdownHighlightTrait |
Protected Methods
| Method | Description | Defined By |
|---|---|---|
| renderCode() | yii\apidoc\helpers\MarkdownHighlightTrait |
Method Details
Highlights code
| public static string highlight ( string $code, string $language ) | ||
| $code | string |
Code to highlight |
| $language | string |
Language of the code to highlight |
| return | string |
HTML of highlighted code |
|---|---|---|
public static function highlight($code, $language)
{
if ($language !== 'php') {
return htmlspecialchars($code, ENT_NOQUOTES | ENT_SUBSTITUTE);
}
if (str_starts_with($code, '<?php')) {
$text = @highlight_string(trim($code), true);
} else {
$text = highlight_string('<?php ' . trim($code), true);
$text = str_replace('<?php', '', $text);
if (($pos = strpos($text, ' ')) !== false) {
$text = substr($text, 0, $pos) . substr($text, $pos + 6);
}
}
// Remove prefixes and suffixes added by php
if (PHP_VERSION_ID >= 80300) {
// The `highlight_string` result format has changed since PHP8.3
$text = substr($text, 34, -13);
} else {
$text = substr($text, 36, -16);
}
return $text;
}
| protected renderCode ( mixed $block ) | ||
| $block | mixed | |
protected function renderCode($block)
{
if (self::$_highlighter === null) {
self::$_highlighter = new Highlighter();
self::$_highlighter->setAutodetectLanguages([
'apache', 'nginx',
'bash', 'dockerfile', 'http',
'css', 'less', 'scss',
'javascript', 'json', 'markdown',
'php', 'sql', 'twig', 'xml',
]);
}
try {
if (isset($block['language'])) {
if ($block['language'] === 'php' && str_contains((string) $block['content'], '<?=')) {
$block['language'] = 'html';
}
$result = self::$_highlighter->highlight($block['language'], $block['content'] . "\n");
return "<pre><code class=\"hljs {$result->language} language-{$block['language']}\">{$result->value}</code></pre>\n";
} else {
$result = self::$_highlighter->highlightAuto($block['content'] . "\n");
return "<pre><code class=\"hljs {$result->language}\">{$result->value}</code></pre>\n";
}
} catch (DomainException) {
return parent::renderCode($block);
}
}