-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathMarkdownHighlightTrait.php
86 lines (77 loc) · 2.65 KB
/
MarkdownHighlightTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\apidoc\helpers;
use DomainException;
use Highlight\Highlighter;
/**
* MarkdownHighlightTrait provides code highlighting functionality for Markdown Parsers.
*
* @since 2.1.1
* @author Carsten Brandt <[email protected]>
*/
trait MarkdownHighlightTrait
{
/**
* @var Highlighter
*/
private static $highlighter;
/**
* @inheritdoc
*/
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' && strpos($block['content'], '<?=') !== false) {
$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 $e) {
return parent::renderCode($block);
}
}
/**
* Highlights code
*
* @param string $code code to highlight
* @param string $language 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 (strncmp($code, '<?php', 5) === 0) {
$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 <code><span style="color: #000000">\n and </span>tags added by php
$text = substr(trim($text), 36, -16);
return $text;
}
}