This repository was archived by the owner on Oct 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPygments.php
More file actions
108 lines (91 loc) · 2.46 KB
/
Copy pathPygments.php
File metadata and controls
108 lines (91 loc) · 2.46 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace Starmind\Pygments;
class Pygments
{
protected $pygmentize;
protected $formatter;
/**
* @param Pygmentize $pygmentize
*/
public function __construct(Pygmentize $pygmentize)
{
$this->pygmentize = $pygmentize;
}
/**
* @param $input
* @param null $lexer
* @param Formatter $formatter
* @return mixed
*/
public function highlight($input, $lexer, Formatter $formatter)
{
// set formatter
$this->formatter = $formatter;
if (is_file($input)) {
$outputString = $this->highlightFile($input, $lexer);
} else {
$tmpFile = tempnam("/tmp", "pygmentize_");
$this->createTempFile($tmpFile, $input);
$outputString = $this->highlightFile($tmpFile, $lexer);
$this->removeTempFile($tmpFile);
}
return $outputString;
}
/**
* @param $file
* @param $lexer
* @return string
* @throws \RuntimeException
*/
protected function highlightFile($file, $lexer)
{
if (! file_exists($file)) {
throw new \RuntimeException(sprintf('File %s does not exist.', $file));
}
try {
$outputString = $this->pygmentize->executeCommand($this->getHighlightCommand($lexer, $file));
} catch (\RuntimeException $e) {
$outputString = $e->getMessage();
}
return $outputString;
}
/**
* @param $lexer
* @param $input
* @return string
*/
protected function getHighlightCommand($lexer, $input)
{
// if a lexer is given use it, otherwise guess language
$lexer = $lexer ? '-l ' . $lexer : '-g';
return sprintf(
'%s %s %s',
$this->formatter->getCliParameters(), $lexer, $input
);
}
/**
* @param $filename
* @param $content
* @throws \RuntimeException
*/
protected function createTempFile($filename, $content)
{
$fh = fopen($filename, "w");
if ($fh !== false) {
fwrite($fh, $content);
fclose($fh);
chmod($filename, 0777);
} else {
throw new \RuntimeException(sprintf('Could not write %s', $filename));
}
}
/**
* @param $filename
*/
protected function removeTempFile($filename)
{
if (file_exists($filename)) {
unlink($filename);
}
}
}