Skip to content

Commit

Permalink
feat: add highlighter
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Dec 21, 2019
1 parent c2c8808 commit a7a0ca2
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions src/Highlighter.php
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(['&nbsp;', '&lt;', '&gt;'], [' ', '<', '>'], $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);
}
}

0 comments on commit a7a0ca2

Please sign in to comment.