Skip to content

Commit

Permalink
Merge pull request #5 from yamadashy/feature/fallback-highlighter
Browse files Browse the repository at this point in the history
feat: Add FallbackHighlighter for improved robustness
  • Loading branch information
yamadashy authored Sep 22, 2024
2 parents 9b4e4e7 + fa5fef2 commit da0cdb8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/CodeHighlighter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

class CodeHighlighter
{
/** @var Highlighter|OldHighlighter */
/** @var FallbackHighlighter|Highlighter|OldHighlighter */
private $highlighter;

public function __construct()
Expand All @@ -28,6 +28,9 @@ class_exists('\JakubOnderka\PhpConsoleHighlighter\Highlighter')
// Support Highlighter and ConsoleColor < 1.0.
$colors = new OldConsoleColor();
$this->highlighter = new OldHighlighter($colors);
} else {
// Fallback to non-highlighted output
$this->highlighter = new FallbackHighlighter();
}
}

Expand Down
31 changes: 31 additions & 0 deletions src/FallbackHighlighter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php declare(strict_types=1);

namespace Yamadashy\PhpStanFriendlyFormatter;

use PHP_Parallel_Lint\PhpConsoleHighlighter\Highlighter;

/**
* @see Highlighter
*/
class FallbackHighlighter
{
public function getCodeSnippet(string $fileContent, int $lineNumber, int $lineBefore, int $lineAfter): string
{
$lines = explode("\n", $fileContent);
$totalLines = \count($lines);

$startLine = max(1, $lineNumber - $lineBefore);
$endLine = min($totalLines, $lineNumber + $lineAfter);

$snippet = '';
$lineNumberWidth = \strlen((string) $endLine);

for ($i = $startLine; $i <= $endLine; ++$i) {
$currentLine = $lines[$i - 1] ?? '';
$linePrefix = '<fg=gray>'.str_pad((string) $i, $lineNumberWidth, ' ', STR_PAD_LEFT).'| </>';
$snippet .= ($lineNumber === $i ? '<fg=red> > </>' : ' ').$linePrefix.$currentLine."\n";
}

return rtrim($snippet);
}
}

0 comments on commit da0cdb8

Please sign in to comment.