-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeHighlighter.php
63 lines (53 loc) · 1.56 KB
/
CodeHighlighter.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
<?php
declare(strict_types=1);
/*
* This file is part of the CoSourceCode Plugin for ILIAS.
*
* (c) Thomas Joußen <[email protected]>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace CoSourceCode;
use DomainException;
use Exception;
use Highlight\Highlighter;
use function explode;
use function HighlightUtilities\splitCodeIntoArray;
use function html_entity_decode;
use function htmlentities;
class CodeHighlighter
{
private Highlighter $highlighter;
public function __construct(
?Highlighter $highlighter = null
) {
$this->highlighter = $highlighter ?? new Highlighter();
}
/**
* @param string $code
* @param string $language
* @param bool $splitLines
*
* @return array{language: string, value: string|array<string>}
*
* @throws Exception
*/
public function highlight(string $code, string $language = 'php', bool $splitLines = false): array
{
$code = html_entity_decode($code);
try {
$highlighted = $this->highlighter->highlight($language, $code);
return [
'language' => $highlighted->language,
'value' => $splitLines ? splitCodeIntoArray($highlighted->value) : $highlighted->value
];
} catch (DomainException $e) {
$code = htmlentities($code);
return [
'language' => $language,
'value' => $splitLines ? explode("\n", $code) : $code
];
}
}
}