diff --git a/src/Console/ClishCommand.php b/src/Console/ClishCommand.php new file mode 100644 index 0000000..cf6db24 --- /dev/null +++ b/src/Console/ClishCommand.php @@ -0,0 +1,98 @@ + + * + * + * Licensed under MIT license. + */ + +namespace Ahc\CliSyntax\Console; + +use Ahc\Cli\Input\Command; +use Ahc\Cli\IO\Interactor; +use Ahc\CliSyntax\Exporter; +use Ahc\CliSyntax\Highlighter; + +class ClishCommand extends Command +{ + public function __construct() + { + parent::__construct('clish', 'PHP CLI syntax highlight and/or export.'); + + $this + ->option('-o --output', 'Output filepath where PNG image is exported') + ->option('-e --echo', 'Forces echo to STDOUT when --output is passed') + ->option('-f --file', \implode("\n", [ + 'Input PHP file to highlight and/or export', + '(will read from piped input if file not given)', + ])) + ->option('-F --font', 'Font to use for export to png') + ->usage( + ' $0 --file file.php ## print' + . ' cat file.php | $0 ## from piped stream' + . ' $0 < file.php ## from redirected stdin' + . ' $0 --file file.php --output file.png ## export' + . ' $0 --file file.php --output file.png --echo ## print + export' + . ' $0 -f file.php -o file.png -F dejavu ## export in dejavu font' + ); + } + + public function interact(Interactor $io) + { + if ($this->file) { + return; + } + + $code = $io->readPiped(function ($reader) use ($io) { + $io->warn('Type in or paste PHP Code below, Press Ctrl+D when done.', true); + $io->warn('(Opening tag `readAll(); + }); + + if ('' !== $code && \substr($code, 0, 5) != 'set('code', $code); + } + + public function execute() + { + $code = $this->file ? \file_get_contents($this->file) : $this->code; + $code = \trim($code); + + if ('' === $code) { + return; + } + + $this->doExport($code); + $this->doHighlight($code); + } + + protected function doHighlight(string $code = null) + { + if (!$this->output || $this->echo) { + echo new Highlighter($code); + } + } + + protected function doExport(string $code = null) + { + if (!$this->output) { + return; + } + + if (!\is_dir(\dirname($this->output))) { + \mkdir(\dirname($this->output), 0755, true); + } + + (new Exporter($code))->export($this->output, \array_filter(['font' => $this->font])); + } +}