hanneskod /
readme-tester
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace hanneskod\readmetester\Output; |
||
| 6 | |||
| 7 | class SyntaxHighlighter |
||
| 8 | { |
||
| 9 | private const REPLACEMENTS = [ |
||
| 10 | '/ /' => ' ', |
||
| 11 | '/<\/?code>/' => '', |
||
| 12 | '/<\?php /' => '', |
||
| 13 | '/<span style="color: ([^"]+)">/' => '<fg=$1>', |
||
| 14 | '/<\/span>/' => '</>', |
||
| 15 | '/<fg=[^>]+>\s*<\/>/' => '', |
||
| 16 | "/\r|\n/" => '', |
||
| 17 | '/<br\s*\/>/' => "\n", |
||
| 18 | ]; |
||
| 19 | |||
| 20 | public function __construct( |
||
| 21 | private string $stringColor = '', |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 22 | private string $commentColor = '', |
||
| 23 | private string $keywordColor = '', |
||
| 24 | private string $defaultColor = '', |
||
| 25 | private string $htmlColor = '', |
||
| 26 | ) { |
||
| 27 | if ($stringColor) { |
||
| 28 | ini_set('highlight.string', $stringColor); |
||
| 29 | } |
||
| 30 | |||
| 31 | if ($commentColor) { |
||
| 32 | ini_set('highlight.comment', $commentColor); |
||
| 33 | } |
||
| 34 | |||
| 35 | if ($keywordColor) { |
||
| 36 | ini_set('highlight.keyword', $keywordColor); |
||
| 37 | } |
||
| 38 | |||
| 39 | if ($defaultColor) { |
||
| 40 | ini_set('highlight.default', $defaultColor); |
||
| 41 | } |
||
| 42 | |||
| 43 | if ($htmlColor) { |
||
| 44 | ini_set('highlight.html', $htmlColor); |
||
| 45 | } |
||
| 46 | } |
||
| 47 | |||
| 48 | public function highlight(string $code): string |
||
| 49 | { |
||
| 50 | return html_entity_decode( |
||
| 51 | (string)preg_replace( |
||
| 52 | array_keys(self::REPLACEMENTS), |
||
| 53 | self::REPLACEMENTS, |
||
| 54 | highlight_string('<?php ' . $code, true) |
||
| 55 | ) |
||
| 56 | ); |
||
| 57 | } |
||
| 58 | } |
||
| 59 |