kzykhys/pygments
Thin PHP wrapper around the Python Pygments syntax highlighter. Highlight code to HTML/ANSI, generate CSS for styles (e.g., monokai), guess lexer by filename, and list available lexers/formatters/styles. Supports custom pygmentize path.
sudo easy_install Pygments # Install Python Pygments
composer require kzykhys/pygments
use KzykHys\Pygments\Pygments;
$pygments = new Pygments();
$highlighted = $pygments->highlight('<?php echo "Hello"; ?>', 'php', 'html');
<pre>{{ app(Pygments::class)->highlight($code, 'php') }}</pre>
highlight(string $code, string $lexer, string $formatter = 'html')getLexers(), getFormatters(), getStyles()guessLexer(string $filename)pygmentize is in your PATH or specify a custom path:
$pygments = new Pygments('/usr/local/bin/pygmentize');
// In a Laravel controller
public function showCodeExample(Request $request) {
$code = file_get_contents(storage_path('app/code/example.js'));
$highlighted = app(Pygments::class)->highlight($code, 'javascript');
return view('docs.example', ['code' => $highlighted]);
}
@component('components.code-block', ['code' => $code, 'language' => 'php'])
@endcomponent
$lexer = app(Pygments::class)->guessLexer('app/Http/Controllers/UserController.php');
// Outputs: 'php'
$css = app(Pygments::class)->getCss('monokai', '.code-block');
file_put_contents(public_path('css/syntax.css'), $css);
$ansiCode = app(Pygments::class)->highlight('print("Hello")', 'python', 'ansi');
echo $ansiCode; // Renders colored output in terminal
Register the wrapper as a singleton in AppServiceProvider:
public function register()
{
$this->app->singleton(Pygments::class, function ($app) {
return new \KzykHys\Pygments\Pygments('/usr/bin/pygmentize');
});
}
Avoid repeated Python process spawning:
$cacheKey = "pygments:{$lexer}:".md5($code);
$highlighted = cache()->remember($cacheKey, now()->addHours(1), function () use ($code, $lexer) {
return app(Pygments::class)->highlight($code, $lexer);
});
Create reusable syntax:
Blade::directive('highlight', function ($expression) {
return "<?php echo app('Pygments')->highlight({$expression[0]}, '{$expression[1]}'); ?>";
});
Usage:
@highlight($code, 'php')
Support multiple output formats (HTML, ANSI, LaTeX):
$html = app(Pygments::class)->highlight($code, 'python', 'html');
$latex = app(Pygments::class)->highlight($code, 'python', 'latex');
Python Dependency:
Shell Injection Vulnerabilities:
highlight() can execute arbitrary shell commands.$lexer and $formatter against allowed lists:
$allowedLexers = ['php', 'javascript', 'python', 'sql'];
if (!in_array($lexer, $allowedLexers)) {
throw new \InvalidArgumentException("Invalid lexer: {$lexer}");
}
Performance Overhead:
PHP Version Conflicts:
create_function).Lexer/Formatter Limitations:
getLexers() and getFormatters() for supported options.Verify pygmentize Path:
which pygmentize # Should return /usr/bin/pygmentize or similar
If missing, install Pygments:
pip install Pygments
Check Python Version:
Log Errors: Wrap calls in try-catch to log failures:
try {
$highlighted = app(Pygments::class)->highlight($code, $lexer);
} catch (\Exception $e) {
Log::error("Pygments error: {$e->getMessage()}");
$highlighted = "<pre><code>{$code}</code></pre>"; // Fallback
}
Test Lexer Guessing:
$lexer = app(Pygments::class)->guessLexer('example.go');
// Debug: var_dump($lexer); // Should output 'go'
Custom Lexers/Formatters:
highlight() method to pass extra arguments to pygmentize.Fallback Mechanisms:
highlight_string in PHP) if Pygments fails:
public function highlight($code, $lexer, $formatter = 'html') {
try {
return parent::highlight($code, $lexer, $formatter);
} catch (\Exception $e) {
return highlight_string($code, true);
}
}
Docker Integration:
# Build stage
FROM python:2.7 as builder
RUN pip install Pygments
# Runtime stage
FROM php:8.1-apache
COPY --from=builder /usr/local/bin/pygmentize /usr/local/bin/
Configuration Management:
pygmentize path in .env:
PYGMENTIZE_PATH=/usr/bin/pygmentize
$pygments = new Pygments(config('pygments.path'));
Batch Processing:
$files = glob(storage_path('app/code/*.php'));
foreach ($files as $file) {
$code = file_get_contents($file);
$highlighted = app(Pygments::class)->highlight($code, 'php');
file_put_contents($file, $highlighted);
}
ANSI to HTML Conversion:
$ansi = app(Pygments::class)->highlight($code, 'python', 'ansi');
$html = preg_replace('/\x1b\[([0-9;]+)?m/', '', $ansi); // Strip ANSI codes
Lexer Prioritization:
$lexer = app(Pygments::class)->guessLexer('config.yaml');
if ($lexer === 'yaml')
How can I help you explore Laravel packages today?