|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the CLI-SYNTAX package. |
| 7 | + * |
| 8 | + * (c) Jitendra Adhikari <[email protected]> |
| 9 | + * <https://github.com/adhocore> |
| 10 | + * |
| 11 | + * Licensed under MIT license. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Ahc\CliSyntax; |
| 15 | + |
| 16 | +abstract class Pretty |
| 17 | +{ |
| 18 | + /** @var string The PHP code. */ |
| 19 | + protected $code; |
| 20 | + |
| 21 | + /** @var bool Indicates if it has been already configured. */ |
| 22 | + protected static $configured; |
| 23 | + |
| 24 | + public function __construct(string $code = null) |
| 25 | + { |
| 26 | + $this->code = $code ?? ''; |
| 27 | + } |
| 28 | + |
| 29 | + public static function for(string $file): self |
| 30 | + { |
| 31 | + if (!\is_file($file)) { |
| 32 | + throw new \InvalidArgumentException('The given file doesnot exist or is unreadable.'); |
| 33 | + } |
| 34 | + |
| 35 | + return new static(\file_get_contents($file)); |
| 36 | + } |
| 37 | + |
| 38 | + public static function configure() |
| 39 | + { |
| 40 | + if (static::$configured) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + foreach (['comment', 'default', 'html', 'keyword', 'string'] as $type) { |
| 45 | + \ini_set("highlight.$type", \ini_get("highlight.$type") . \sprintf('" data-type="%s', $type)); |
| 46 | + } |
| 47 | + |
| 48 | + static::$configured = true; |
| 49 | + } |
| 50 | + |
| 51 | + protected function parse(string $code = null) |
| 52 | + { |
| 53 | + static::configure(); |
| 54 | + |
| 55 | + $html = \highlight_string($code ?? $this->code, true); |
| 56 | + $html = \str_replace('<br />', "\n", $html); |
| 57 | + |
| 58 | + $dom = new \DOMDocument; |
| 59 | + $dom->loadHTML($html); |
| 60 | + |
| 61 | + foreach ($dom->getElementsByTagName('span') as $el) { |
| 62 | + if ('html' !== $el->getAttribute('data-type')) { |
| 63 | + $this->visit($el); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + abstract protected function visit(\DOMElement $el); |
| 69 | +} |
0 commit comments