generated from spatie/package-skeleton-php
-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Shiki.php
88 lines (71 loc) · 2.37 KB
/
Shiki.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
87
88
<?php
namespace Spatie\ShikiPhp;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
class Shiki
{
protected string $defaultTheme;
private static ?string $customWorkingDirPath = null;
public static function setCustomWorkingDirPath(?string $path)
{
static::$customWorkingDirPath = $path;
}
public static function highlight(
string $code,
?string $language = null,
?string $theme = null,
?array $highlightLines = null,
?array $addLines = null,
?array $deleteLines = null,
?array $focusLines = null
): string {
$language = $language ?? 'php';
$theme = $theme ?? 'nord';
return (new static())->highlightCode($code, $language, $theme, [
'highlightLines' => $highlightLines ?? [],
'addLines' => $addLines ?? [],
'deleteLines' => $deleteLines ?? [],
'focusLines' => $focusLines ?? [],
]);
}
public function __construct(string $defaultTheme = 'nord')
{
$this->defaultTheme = $defaultTheme;
}
public function highlightCode(string $code, string $language, ?string $theme = null, ?array $options = []): string
{
$theme = $theme ?? $this->defaultTheme;
return $this->callShiki($code, $language, $theme, $options);
}
public function getWorkingDirPath(): string
{
if (static::$customWorkingDirPath !== null && ($path = realpath(static::$customWorkingDirPath)) !== false) {
return $path;
}
return realpath(dirname(__DIR__) . '/bin');
}
protected function callShiki(...$arguments): string
{
$home = getenv("HOME");
$command = [
(new ExecutableFinder())->find('node', 'node', [
'/usr/local/bin',
'/opt/homebrew/bin',
$home . '/n/bin', // support https://github.com/tj/n
]),
'shiki.js',
json_encode(array_values($arguments)),
];
$process = new Process(
$command,
$this->getWorkingDirPath(),
null,
);
$process->run();
if (! $process->isSuccessful()) {
throw new ProcessFailedException($process);
}
return $process->getOutput();
}
}