-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
92 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
<?php | ||
|
||
namespace Ahc\CliSyntax; | ||
|
||
class Highlighter | ||
{ | ||
/** @var string The PHP code. */ | ||
protected $code; | ||
|
||
/** @var bool Indicates if it has been already configured. */ | ||
protected static $configured; | ||
|
||
public function __construct(string $code) | ||
{ | ||
$this->code = $code; | ||
} | ||
|
||
public function __toString(): string | ||
{ | ||
return $this->highlight(); | ||
} | ||
|
||
public static function for(string $file): self | ||
{ | ||
if (!\is_file($file)) { | ||
throw new \InvalidArgumentException('The given file doesnot exist or is unreadable.'); | ||
} | ||
|
||
return new static(\file_get_contents($file)); | ||
} | ||
|
||
public function highlight(): string | ||
{ | ||
static::configure(); | ||
|
||
$html = \highlight_string($this->code, true); | ||
$html = \str_replace(['<br />', '<br/>', '<br>'], "\n", $html); | ||
|
||
return $this->parse($html); | ||
} | ||
|
||
public function configure() | ||
{ | ||
if (static::$configured) { | ||
return; | ||
} | ||
|
||
foreach (['comment', 'default', 'html', 'keyword', 'string'] as $type) { | ||
\ini_set("highlight.$type", \ini_get("highlight.$type") . \sprintf('" data-type="%s', $type)); | ||
} | ||
|
||
static::$configured = true; | ||
} | ||
|
||
protected function parse(string $html): string | ||
{ | ||
$str = ''; | ||
$dom = new \DOMDocument; | ||
|
||
$dom->loadHTML($html); | ||
foreach ($dom->getElementsByTagName('span') as $el) { | ||
$str .= $this->visit($el); | ||
} | ||
|
||
return $str; | ||
} | ||
|
||
protected function visit(\DOMElement $el): string | ||
{ | ||
if ('html' === $type = $el->getAttribute('data-type')) { | ||
return ''; | ||
} | ||
|
||
$text = $el->textContent; | ||
|
||
$text = \str_replace([' ', '<', '>'], [' ', '<', '>'], $text); | ||
|
||
return $this->format($text, $type); | ||
} | ||
|
||
protected function format(string $text, string $type): string | ||
{ | ||
static $formats = [ | ||
'comment' => "\033[1;30;40m%s\033[0m", | ||
'default' => "\033[0;32;40m%s\033[0m", | ||
'keyword' => "\033[0;36;40m%s\033[0m", | ||
'string' => "\033[0;33;40m%s\033[0m", | ||
]; | ||
|
||
return \sprintf($formats[$type] ?? '%s', $text); | ||
} | ||
} |