first commit
This commit is contained in:
+35
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Psy Shell.
|
||||
*
|
||||
* (c) 2012-2026 Justin Hileman
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Psy\Output;
|
||||
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* An output pager is much the same as a regular OutputInterface, but allows
|
||||
* the stream to be flushed to a pager periodically.
|
||||
*/
|
||||
interface OutputPager extends OutputInterface
|
||||
{
|
||||
// TODO: Add doWrite to the OutputPager interface.
|
||||
// /**
|
||||
// * Writes a message to the output.
|
||||
// *
|
||||
// * @param string $message A message to write to the output
|
||||
// * @param bool $newline Whether to add a newline or not
|
||||
// */
|
||||
// public function doWrite($message, $newline): void;
|
||||
|
||||
/**
|
||||
* Close the current pager process.
|
||||
*/
|
||||
public function close();
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Psy Shell.
|
||||
*
|
||||
* (c) 2012-2026 Justin Hileman
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Psy\Output;
|
||||
|
||||
use Symfony\Component\Console\Output\StreamOutput;
|
||||
|
||||
/**
|
||||
* A passthrough pager is a no-op. It simply wraps a StreamOutput's stream and
|
||||
* does nothing when the pager is closed.
|
||||
*/
|
||||
class PassthruPager extends StreamOutput implements OutputPager
|
||||
{
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param StreamOutput $output
|
||||
*/
|
||||
public function __construct(StreamOutput $output)
|
||||
{
|
||||
parent::__construct($output->getStream());
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a message to the output.
|
||||
*
|
||||
* @param string $message A message to write to the output
|
||||
* @param bool $newline Whether to add a newline or not
|
||||
*/
|
||||
public function doWrite($message, $newline): void
|
||||
{
|
||||
parent::doWrite($message, $newline);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the current pager process.
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
// nothing to do here
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Psy Shell.
|
||||
*
|
||||
* (c) 2012-2026 Justin Hileman
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Psy\Output;
|
||||
|
||||
use Symfony\Component\Console\Output\StreamOutput;
|
||||
|
||||
/**
|
||||
* ProcOutputPager class.
|
||||
*
|
||||
* A ProcOutputPager instance wraps a regular StreamOutput's stream. Rather
|
||||
* than writing directly to the stream, it shells out to a pager process and
|
||||
* gives that process the stream as stdout. This means regular *nix commands
|
||||
* like `less` and `more` can be used to page large amounts of output.
|
||||
*/
|
||||
class ProcOutputPager extends StreamOutput implements OutputPager
|
||||
{
|
||||
/** @var ?resource */
|
||||
private $proc = null;
|
||||
/** @var ?resource */
|
||||
private $pipe = null;
|
||||
/** @var resource */
|
||||
private $stream;
|
||||
private string $cmd;
|
||||
private bool $closedEarly = false;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param StreamOutput $output
|
||||
* @param string $cmd Pager process command (default: 'less -R -F -X')
|
||||
*/
|
||||
public function __construct(StreamOutput $output, string $cmd = 'less -R -F -X')
|
||||
{
|
||||
$this->stream = $output->getStream();
|
||||
$this->cmd = $cmd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a message to the output.
|
||||
*
|
||||
* @param string $message A message to write to the output
|
||||
* @param bool $newline Whether to add a newline or not
|
||||
*
|
||||
* @throws \RuntimeException When unable to write output (should never happen)
|
||||
*/
|
||||
public function doWrite($message, $newline): void
|
||||
{
|
||||
// If the pager was closed early (user quit), don't reopen it.
|
||||
if ($this->closedEarly) {
|
||||
return;
|
||||
}
|
||||
|
||||
$pipe = $this->getPipe();
|
||||
if (false === @\fwrite($pipe, $message.($newline ? \PHP_EOL : ''))) {
|
||||
// @codeCoverageIgnoreStart
|
||||
// When the message is sufficiently long, writing to the pipe fails
|
||||
// if the pager process is closed before the entire message is read.
|
||||
//
|
||||
// This is a normal condition, so we close the pipe and ignore any
|
||||
// further writes until the next paging session.
|
||||
$this->close();
|
||||
$this->closedEarly = true;
|
||||
|
||||
return;
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
\fflush($pipe);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the current pager process.
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
if (\is_resource($this->pipe)) {
|
||||
\fclose($this->pipe);
|
||||
}
|
||||
|
||||
if (\is_resource($this->proc)) {
|
||||
$exit = \proc_close($this->proc);
|
||||
if ($exit !== 0) {
|
||||
throw new \RuntimeException('Error closing output stream');
|
||||
}
|
||||
}
|
||||
|
||||
$this->pipe = null;
|
||||
$this->proc = null;
|
||||
$this->closedEarly = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a pipe for paging output.
|
||||
*
|
||||
* If no active pager process exists, fork one and return its input pipe.
|
||||
*/
|
||||
private function getPipe()
|
||||
{
|
||||
if (!isset($this->pipe) || !isset($this->proc)) {
|
||||
$desc = [['pipe', 'r'], $this->stream, \fopen('php://stderr', 'w')];
|
||||
$this->proc = \proc_open($this->cmd, $desc, $pipes);
|
||||
|
||||
if (!\is_resource($this->proc)) {
|
||||
throw new \RuntimeException('Error opening output stream');
|
||||
}
|
||||
|
||||
$this->pipe = $pipes[0];
|
||||
}
|
||||
|
||||
return $this->pipe;
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Psy Shell.
|
||||
*
|
||||
* (c) 2012-2026 Justin Hileman
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Psy\Output;
|
||||
|
||||
use Psy\Formatter\LinkFormatter;
|
||||
use Symfony\Component\Console\Formatter\OutputFormatter;
|
||||
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
|
||||
use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
|
||||
/**
|
||||
* A ConsoleOutput subclass specifically for Psy Shell output.
|
||||
*/
|
||||
class ShellOutput extends ConsoleOutput
|
||||
{
|
||||
const NUMBER_LINES = 128;
|
||||
|
||||
private int $paging = 0;
|
||||
private OutputPager $pager;
|
||||
private Theme $theme;
|
||||
/** @var callable|null */
|
||||
private $writeListener = null;
|
||||
|
||||
/**
|
||||
* Construct a ShellOutput instance.
|
||||
*
|
||||
* @param mixed $verbosity (default: self::VERBOSITY_NORMAL)
|
||||
* @param bool|null $decorated (default: null)
|
||||
* @param OutputFormatterInterface|null $formatter (default: null)
|
||||
* @param string|OutputPager|null $pager (default: null)
|
||||
*/
|
||||
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, ?OutputFormatterInterface $formatter = null, $pager = null, $theme = null)
|
||||
{
|
||||
parent::__construct($verbosity, $decorated, $formatter);
|
||||
|
||||
$this->theme = $theme ?? new Theme('modern');
|
||||
$this->initFormatters();
|
||||
|
||||
$this->pager = $this->createPager($pager);
|
||||
}
|
||||
|
||||
/**
|
||||
* Page multiple lines of output.
|
||||
*
|
||||
* The output pager is started
|
||||
*
|
||||
* If $messages is callable, it will be called, passing this output instance
|
||||
* for rendering. Otherwise, all passed $messages are paged to output.
|
||||
*
|
||||
* Upon completion, the output pager is flushed.
|
||||
*
|
||||
* @param string|array|\Closure $messages A string, array of strings or a callback
|
||||
* @param int $type (default: 0)
|
||||
*/
|
||||
public function page($messages, int $type = 0)
|
||||
{
|
||||
if (\is_string($messages)) {
|
||||
// Split on newlines to avoid O(n^2) performance in Symfony's OutputFormatter
|
||||
// when processing large strings with many style tags.
|
||||
$messages = \explode("\n", $messages);
|
||||
}
|
||||
|
||||
if (!\is_array($messages) && !\is_callable($messages)) {
|
||||
throw new \InvalidArgumentException('Paged output requires a string, array or callback');
|
||||
}
|
||||
|
||||
$this->startPaging();
|
||||
|
||||
if (\is_callable($messages)) {
|
||||
$messages($this);
|
||||
} else {
|
||||
$this->write($messages, true, $type);
|
||||
}
|
||||
|
||||
$this->stopPaging();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a listener invoked whenever visible output is written.
|
||||
*/
|
||||
public function setWriteListener(?callable $listener): void
|
||||
{
|
||||
$this->writeListener = $listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start sending output to the output pager.
|
||||
*/
|
||||
public function startPaging()
|
||||
{
|
||||
$this->paging++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop paging output and flush the output pager.
|
||||
*/
|
||||
public function stopPaging()
|
||||
{
|
||||
$this->paging--;
|
||||
$this->closePager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a message to the output.
|
||||
*
|
||||
* Optionally, pass `$type | self::NUMBER_LINES` as the $type parameter to
|
||||
* number the lines of output.
|
||||
*
|
||||
* @throws \InvalidArgumentException When unknown output type is given
|
||||
*
|
||||
* @param string|array $messages The message as an array of lines or a single string
|
||||
* @param bool $newline Whether to add a newline or not
|
||||
* @param int $type The type of output
|
||||
*/
|
||||
public function write($messages, $newline = false, $type = 0): void
|
||||
{
|
||||
if ($this->getVerbosity() === self::VERBOSITY_QUIET) {
|
||||
return;
|
||||
}
|
||||
|
||||
$messages = (array) $messages;
|
||||
|
||||
if ($type & self::NUMBER_LINES) {
|
||||
$pad = \strlen((string) \count($messages));
|
||||
$template = $this->isDecorated() && $this->getFormatter()->hasStyle('whisper')
|
||||
? "<whisper>%{$pad}s:</whisper> %s"
|
||||
: "%{$pad}s: %s";
|
||||
|
||||
if ($type & self::OUTPUT_RAW) {
|
||||
$messages = \array_map([OutputFormatter::class, 'escape'], $messages);
|
||||
}
|
||||
|
||||
$indent = \str_repeat(' ', $pad + 2); // Indent continuation lines to align with text
|
||||
|
||||
foreach ($messages as $i => $line) {
|
||||
// Check if line contains newlines (multi-line entry)
|
||||
if (\strpos($line, "\n") !== false) {
|
||||
// Split into lines and indent continuation lines
|
||||
$lines = \explode("\n", $line);
|
||||
$firstLine = \array_shift($lines);
|
||||
$indentedLines = \array_map(function ($l) use ($indent) {
|
||||
return $indent.$l;
|
||||
}, $lines);
|
||||
|
||||
$messages[$i] = \sprintf($template, $i, $firstLine);
|
||||
if (!empty($indentedLines)) {
|
||||
$messages[$i] .= "\n".\implode("\n", $indentedLines);
|
||||
}
|
||||
} else {
|
||||
$messages[$i] = \sprintf($template, $i, $line);
|
||||
}
|
||||
}
|
||||
|
||||
// clean this up for super.
|
||||
$type = $type & ~self::NUMBER_LINES & ~self::OUTPUT_RAW;
|
||||
}
|
||||
|
||||
parent::write($messages, $newline, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a message to the output.
|
||||
*
|
||||
* Handles paged output, or writes directly to the output stream.
|
||||
*
|
||||
* @param string $message A message to write to the output
|
||||
* @param bool $newline Whether to add a newline or not
|
||||
*/
|
||||
public function doWrite($message, $newline): void
|
||||
{
|
||||
if ($this->writeListener) {
|
||||
($this->writeListener)();
|
||||
}
|
||||
|
||||
// @todo Update OutputPager interface to require doWrite
|
||||
if ($this->paging > 0 && ($this->pager instanceof ProcOutputPager || $this->pager instanceof PassthruPager)) {
|
||||
$this->pager->doWrite($message, $newline);
|
||||
} else {
|
||||
parent::doWrite($message, $newline);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the output Theme.
|
||||
*/
|
||||
public function setTheme(Theme $theme)
|
||||
{
|
||||
$this->theme = $theme;
|
||||
$this->initFormatters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the output pager used for future paging operations.
|
||||
*
|
||||
* @param string|OutputPager|null $pager
|
||||
*/
|
||||
public function setPager($pager): void
|
||||
{
|
||||
$this->closePager();
|
||||
$this->paging = 0;
|
||||
$this->pager = $this->createPager($pager);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush and close the output pager.
|
||||
*/
|
||||
private function closePager()
|
||||
{
|
||||
if ($this->paging <= 0) {
|
||||
$this->pager->close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|OutputPager|null $pager
|
||||
*/
|
||||
private function createPager($pager): OutputPager
|
||||
{
|
||||
if ($pager === null) {
|
||||
return new PassthruPager($this);
|
||||
}
|
||||
|
||||
if (\is_string($pager)) {
|
||||
return new ProcOutputPager($this, $pager);
|
||||
}
|
||||
|
||||
if ($pager instanceof OutputPager) {
|
||||
return $pager;
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('Unexpected pager parameter: '.$pager);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize output formatter styles.
|
||||
*/
|
||||
private function initFormatters()
|
||||
{
|
||||
$useGrayFallback = !$this->grayExists();
|
||||
$this->theme->applyStyles($this->getFormatter(), $useGrayFallback);
|
||||
$this->theme->applyErrorStyles($this->getErrorOutput()->getFormatter(), $useGrayFallback);
|
||||
|
||||
// Set inline styles for hyperlinks
|
||||
LinkFormatter::setStyles($this->theme->getInlineStyles($useGrayFallback));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the "gray" color exists on the output.
|
||||
*/
|
||||
private function grayExists(): bool
|
||||
{
|
||||
try {
|
||||
$this->write('<fg=gray></>');
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Psy Shell.
|
||||
*
|
||||
* (c) 2012-2026 Justin Hileman
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Psy\Output;
|
||||
|
||||
use Symfony\Component\Console\Formatter\OutputFormatter;
|
||||
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Adapter for output methods provided by ShellOutput but used by commands.
|
||||
*
|
||||
* This allows commands to use paging and line numbering with any
|
||||
* OutputInterface implementation.
|
||||
*
|
||||
* @todo On the next major release, consider removing ShellOutput and folding
|
||||
* its functionality entirely into this adapter.
|
||||
*/
|
||||
class ShellOutputAdapter implements OutputInterface
|
||||
{
|
||||
// @todo Remove ShellOutput::NUMBER_LINES alias on next major release.
|
||||
public const NUMBER_LINES = ShellOutput::NUMBER_LINES;
|
||||
|
||||
private OutputInterface $output;
|
||||
|
||||
/**
|
||||
* @param OutputInterface $output
|
||||
*/
|
||||
public function __construct(OutputInterface $output)
|
||||
{
|
||||
$this->output = $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Page multiple lines of output.
|
||||
*
|
||||
* @param string|array|\Closure $messages
|
||||
*/
|
||||
public function page($messages, int $type = 0): void
|
||||
{
|
||||
if ($this->output instanceof ShellOutput) {
|
||||
$this->output->page($messages, $type);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (\is_string($messages)) {
|
||||
// Split on newlines to avoid O(n^2) performance in Symfony's OutputFormatter
|
||||
// when processing large strings with many style tags.
|
||||
$messages = \explode("\n", $messages);
|
||||
}
|
||||
|
||||
if (!\is_array($messages) && !\is_callable($messages)) {
|
||||
throw new \InvalidArgumentException('Paged output requires a string, array or callback');
|
||||
}
|
||||
|
||||
$this->startPaging();
|
||||
|
||||
if (\is_callable($messages)) {
|
||||
$messages($this);
|
||||
} else {
|
||||
$this->write($messages, true, $type);
|
||||
}
|
||||
|
||||
$this->stopPaging();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start sending output to the output pager.
|
||||
*/
|
||||
public function startPaging(): void
|
||||
{
|
||||
if ($this->output instanceof ShellOutput) {
|
||||
$this->output->startPaging();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop paging output and flush the output pager.
|
||||
*/
|
||||
public function stopPaging(): void
|
||||
{
|
||||
if ($this->output instanceof ShellOutput) {
|
||||
$this->output->stopPaging();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a message to the output.
|
||||
*
|
||||
* @param string|array $messages
|
||||
*/
|
||||
public function write($messages, $newline = false, $type = 0): void
|
||||
{
|
||||
if ($this->output instanceof ShellOutput) {
|
||||
$this->output->write($messages, $newline, $type);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$messages = (array) $messages;
|
||||
|
||||
if ($type & self::NUMBER_LINES) {
|
||||
$messages = $this->numberLines($messages, $type);
|
||||
|
||||
// clean this up for the wrapped output.
|
||||
$type = $type & ~self::NUMBER_LINES & ~OutputInterface::OUTPUT_RAW;
|
||||
}
|
||||
|
||||
$this->output->write($messages, $newline, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a message to the output and adds a newline at the end.
|
||||
*
|
||||
* @param string|array $messages
|
||||
*/
|
||||
public function writeln($messages, $type = 0): void
|
||||
{
|
||||
$this->write($messages, true, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function setVerbosity($level): void
|
||||
{
|
||||
$this->output->setVerbosity($level);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getVerbosity(): int
|
||||
{
|
||||
return $this->output->getVerbosity();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isQuiet(): bool
|
||||
{
|
||||
return $this->output->isQuiet();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isVerbose(): bool
|
||||
{
|
||||
return $this->output->isVerbose();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isVeryVerbose(): bool
|
||||
{
|
||||
return $this->output->isVeryVerbose();
|
||||
}
|
||||
|
||||
/**
|
||||
* @todo Remove method_exists guard when dropping support for Symfony < 7.2.
|
||||
*
|
||||
* @suppress PhanUndeclaredMethod
|
||||
*/
|
||||
public function isSilent(): bool
|
||||
{
|
||||
if (\method_exists($this->output, 'isSilent')) {
|
||||
return $this->output->isSilent();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isDebug(): bool
|
||||
{
|
||||
return $this->output->isDebug();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function setDecorated($decorated): void
|
||||
{
|
||||
$this->output->setDecorated($decorated);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isDecorated(): bool
|
||||
{
|
||||
return $this->output->isDecorated();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function setFormatter(OutputFormatterInterface $formatter): void
|
||||
{
|
||||
$this->output->setFormatter($formatter);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormatter(): OutputFormatterInterface
|
||||
{
|
||||
return $this->output->getFormatter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add line numbers to a message array.
|
||||
*
|
||||
* @param string[] $messages
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function numberLines(array $messages, int $type): array
|
||||
{
|
||||
$pad = \strlen((string) \count($messages));
|
||||
$template = $this->output->isDecorated() && $this->output->getFormatter()->hasStyle('whisper')
|
||||
? "<whisper>%{$pad}s:</whisper> %s"
|
||||
: "%{$pad}s: %s";
|
||||
|
||||
if ($type & OutputInterface::OUTPUT_RAW) {
|
||||
$messages = \array_map([OutputFormatter::class, 'escape'], $messages);
|
||||
}
|
||||
|
||||
foreach ($messages as $i => $line) {
|
||||
$messages[$i] = \sprintf($template, $i, $line);
|
||||
}
|
||||
|
||||
return $messages;
|
||||
}
|
||||
}
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Psy Shell.
|
||||
*
|
||||
* (c) 2012-2026 Justin Hileman
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Psy\Output;
|
||||
|
||||
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
|
||||
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
|
||||
|
||||
/**
|
||||
* An output Theme, which controls prompt strings, formatter styles, and compact output.
|
||||
*/
|
||||
class Theme
|
||||
{
|
||||
public const BUILTIN_THEMES = ['modern', 'compact', 'classic'];
|
||||
|
||||
const MODERN_THEME = []; // Defaults :)
|
||||
|
||||
const COMPACT_THEME = [
|
||||
'compact' => true,
|
||||
];
|
||||
|
||||
const CLASSIC_THEME = [
|
||||
'compact' => true,
|
||||
|
||||
'prompt' => '>>> ',
|
||||
'bufferPrompt' => '... ',
|
||||
'replayPrompt' => '--> ',
|
||||
'returnValue' => '=> ',
|
||||
];
|
||||
|
||||
private const BUILTIN_THEME_CONFIGS = [
|
||||
'modern' => self::MODERN_THEME,
|
||||
'compact' => self::COMPACT_THEME,
|
||||
'classic' => self::CLASSIC_THEME,
|
||||
];
|
||||
|
||||
// Custom themes fall back to DEFAULT_STYLES for any undefined style.
|
||||
const DEFAULT_STYLES = [
|
||||
'info' => ['green', null, ['bold']],
|
||||
'warning' => ['black', 'yellow'],
|
||||
'error' => ['white', 'red', ['bold']],
|
||||
'whisper' => ['gray'],
|
||||
|
||||
'aside' => ['blue'],
|
||||
'strong' => [null, null, ['bold']],
|
||||
'return' => ['cyan'],
|
||||
'urgent' => ['red'],
|
||||
'hidden' => ['black'],
|
||||
'command' => ['cyan', null, ['bold']],
|
||||
'command_option' => ['yellow'],
|
||||
'command_argument' => ['green'],
|
||||
|
||||
// Keywords
|
||||
'public' => [null, null, ['bold']],
|
||||
'protected' => ['yellow'],
|
||||
'private' => ['red'],
|
||||
'global' => ['cyan', null, ['bold']],
|
||||
'const' => ['cyan'],
|
||||
'class' => ['blue', null, ['underscore']],
|
||||
'function' => [null],
|
||||
'virtual' => ['magenta'],
|
||||
'default' => [null],
|
||||
|
||||
// Types
|
||||
'number' => ['magenta'],
|
||||
'integer' => ['magenta'],
|
||||
'float' => ['magenta'],
|
||||
'string' => ['green'],
|
||||
'array_key' => ['blue'],
|
||||
'bool' => ['cyan'],
|
||||
'keyword' => ['yellow'],
|
||||
'comment' => ['blue'],
|
||||
'code_comment' => ['gray'],
|
||||
'object' => ['blue'],
|
||||
'resource' => ['yellow'],
|
||||
|
||||
// Code-specific formatting
|
||||
'inline_html' => ['cyan'],
|
||||
|
||||
// Interactive readline
|
||||
'input_frame' => ['bright-white', 'gray'],
|
||||
'input_frame_error' => ['bright-white', 'red'],
|
||||
'input_highlight' => [null, null, ['reverse']],
|
||||
];
|
||||
|
||||
const ERROR_STYLES = ['info', 'warning', 'error', 'whisper', 'class'];
|
||||
|
||||
private bool $compact = false;
|
||||
|
||||
private string $prompt = '> ';
|
||||
private string $bufferPrompt = '. ';
|
||||
private string $replayPrompt = '- ';
|
||||
private string $returnValue = '= ';
|
||||
|
||||
private string $grayFallback = 'blue';
|
||||
|
||||
private array $styles = [];
|
||||
|
||||
/**
|
||||
* @param string|array $config theme name or config options
|
||||
*/
|
||||
public function __construct($config = 'modern')
|
||||
{
|
||||
if (\is_string($config)) {
|
||||
if (isset(self::BUILTIN_THEME_CONFIGS[$config])) {
|
||||
$config = self::BUILTIN_THEME_CONFIGS[$config];
|
||||
} else {
|
||||
\trigger_error(\sprintf('Unknown theme: %s', $config), \E_USER_NOTICE);
|
||||
$config = static::MODERN_THEME;
|
||||
}
|
||||
}
|
||||
|
||||
if (!\is_array($config)) {
|
||||
throw new \InvalidArgumentException('Invalid theme config');
|
||||
}
|
||||
|
||||
foreach ($config as $name => $value) {
|
||||
switch ($name) {
|
||||
case 'compact':
|
||||
$this->setCompact($value);
|
||||
break;
|
||||
|
||||
case 'prompt':
|
||||
$this->setPrompt($value);
|
||||
break;
|
||||
|
||||
case 'bufferPrompt':
|
||||
$this->setBufferPrompt($value);
|
||||
break;
|
||||
|
||||
case 'replayPrompt':
|
||||
$this->setReplayPrompt($value);
|
||||
break;
|
||||
|
||||
case 'returnValue':
|
||||
$this->setReturnValue($value);
|
||||
break;
|
||||
|
||||
case 'grayFallback':
|
||||
$this->setGrayFallback($value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$this->setStyles($config['styles'] ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable compact output.
|
||||
*/
|
||||
public function setCompact(bool $compact)
|
||||
{
|
||||
$this->compact = $compact;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether to use compact output.
|
||||
*/
|
||||
public function compact(): bool
|
||||
{
|
||||
return $this->compact;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the prompt string.
|
||||
*/
|
||||
public function setPrompt(string $prompt)
|
||||
{
|
||||
$this->prompt = $prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the prompt string.
|
||||
*/
|
||||
public function prompt(): string
|
||||
{
|
||||
return $this->prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the buffer prompt string (used for multi-line input continuation).
|
||||
*/
|
||||
public function setBufferPrompt(string $bufferPrompt)
|
||||
{
|
||||
$this->bufferPrompt = $bufferPrompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the buffer prompt string (used for multi-line input continuation).
|
||||
*/
|
||||
public function bufferPrompt(): string
|
||||
{
|
||||
return $this->bufferPrompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the prompt string used when replaying history.
|
||||
*/
|
||||
public function setReplayPrompt(string $replayPrompt)
|
||||
{
|
||||
$this->replayPrompt = $replayPrompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the prompt string used when replaying history.
|
||||
*/
|
||||
public function replayPrompt(): string
|
||||
{
|
||||
return $this->replayPrompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the return value marker.
|
||||
*/
|
||||
public function setReturnValue(string $returnValue)
|
||||
{
|
||||
$this->returnValue = $returnValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the return value marker.
|
||||
*/
|
||||
public function returnValue(): string
|
||||
{
|
||||
return $this->returnValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the fallback color when "gray" is unavailable.
|
||||
*/
|
||||
public function setGrayFallback(string $grayFallback)
|
||||
{
|
||||
$this->grayFallback = $grayFallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the shell output formatter styles.
|
||||
*
|
||||
* Accepts a map from style name to [fg, bg, options], for example:
|
||||
*
|
||||
* [
|
||||
* 'error' => ['white', 'red', ['bold']],
|
||||
* 'warning' => ['black', 'yellow'],
|
||||
* ]
|
||||
*
|
||||
* Foreground, background or options can be null, or even omitted entirely.
|
||||
*/
|
||||
public function setStyles(array $styles)
|
||||
{
|
||||
foreach (\array_keys(static::DEFAULT_STYLES) as $name) {
|
||||
$this->styles[$name] = $styles[$name] ?? static::DEFAULT_STYLES[$name];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the built-in theme name, or null for custom themes.
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
foreach (self::BUILTIN_THEMES as $name) {
|
||||
if ($this->equals(new self($name))) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two themes by effective config.
|
||||
*/
|
||||
public function equals(self $theme): bool
|
||||
{
|
||||
return $this->compact === $theme->compact
|
||||
&& $this->prompt === $theme->prompt
|
||||
&& $this->bufferPrompt === $theme->bufferPrompt
|
||||
&& $this->replayPrompt === $theme->replayPrompt
|
||||
&& $this->returnValue === $theme->returnValue
|
||||
&& $this->grayFallback === $theme->grayFallback
|
||||
&& $this->styles === $theme->styles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the current output formatter styles.
|
||||
*/
|
||||
public function applyStyles(OutputFormatterInterface $formatter, bool $useGrayFallback)
|
||||
{
|
||||
foreach (\array_keys(static::DEFAULT_STYLES) as $name) {
|
||||
$formatter->setStyle($name, new OutputFormatterStyle(...$this->getStyle($name, $useGrayFallback)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the current output formatter error styles.
|
||||
*/
|
||||
public function applyErrorStyles(OutputFormatterInterface $errorFormatter, bool $useGrayFallback)
|
||||
{
|
||||
foreach (static::ERROR_STYLES as $name) {
|
||||
$errorFormatter->setStyle($name, new OutputFormatterStyle(...$this->getStyle($name, $useGrayFallback)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a style definition as an array.
|
||||
*
|
||||
* @return array [foreground, background, options]
|
||||
*/
|
||||
private function getStyle(string $name, bool $useGrayFallback): array
|
||||
{
|
||||
if (!$useGrayFallback) {
|
||||
return $this->styles[$name];
|
||||
}
|
||||
|
||||
// The default input_frame styles use extended colors (bright-white,
|
||||
// gray) unavailable on older Symfony Console. Drop them rather than
|
||||
// falling back to unreadable backgrounds.
|
||||
if (($name === 'input_frame' || $name === 'input_frame_error') && $this->styles[$name] === static::DEFAULT_STYLES[$name]) {
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
return \array_map(fn ($style) => ($style === 'gray') ? $this->grayFallback : $style, $this->styles[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a style as inline style string for use with hrefs.
|
||||
*
|
||||
* Converts style array [fg, bg, options] to inline format: "fg=color;bg=color;options=opt1,opt2"
|
||||
*
|
||||
* @return string Inline style string (e.g., "fg=blue;options=underscore")
|
||||
*/
|
||||
private function getStyleAsInline(string $name, bool $useGrayFallback = false): string
|
||||
{
|
||||
$style = $this->getStyle($name, $useGrayFallback) ?? static::DEFAULT_STYLES[$name] ?? [null, null, []];
|
||||
$fg = $style[0] ?? null;
|
||||
$bg = $style[1] ?? null;
|
||||
$options = $style[2] ?? [];
|
||||
|
||||
$parts = [];
|
||||
|
||||
if ($fg !== null) {
|
||||
$parts[] = \sprintf('fg=%s', $fg);
|
||||
}
|
||||
|
||||
if ($bg !== null) {
|
||||
$parts[] = \sprintf('bg=%s', $bg);
|
||||
}
|
||||
|
||||
if (!empty($options)) {
|
||||
$parts[] = \sprintf('options=%s', \implode(',', $options));
|
||||
}
|
||||
|
||||
return \implode(';', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all styles as inline style strings, for use with hrefs or other manual formatting.
|
||||
*
|
||||
* @return array Map of style name to inline style string
|
||||
*/
|
||||
public function getInlineStyles(bool $useGrayFallback = false): array
|
||||
{
|
||||
$inlineStyles = [];
|
||||
|
||||
foreach (\array_keys(static::DEFAULT_STYLES) as $name) {
|
||||
$inlineStyles[$name] = $this->getStyleAsInline($name, $useGrayFallback);
|
||||
}
|
||||
|
||||
return $inlineStyles;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user