4 * This file is part of Psy Shell.
6 * (c) 2012-2017 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
14 use Symfony\Component\Console\Output\StreamOutput;
17 * ProcOutputPager class.
19 * A ProcOutputPager instance wraps a regular StreamOutput's stream. Rather
20 * than writing directly to the stream, it shells out to a pager process and
21 * gives that process the stream as stdout. This means regular *nix commands
22 * like `less` and `more` can be used to page large amounts of output.
24 class ProcOutputPager extends StreamOutput implements OutputPager
34 * @param StreamOutput $output
35 * @param string $cmd Pager process command (default: 'less -R -S -F -X')
37 public function __construct(StreamOutput $output, $cmd = 'less -R -S -F -X')
39 $this->stream = $output->getStream();
44 * Writes a message to the output.
46 * @param string $message A message to write to the output
47 * @param bool $newline Whether to add a newline or not
49 * @throws \RuntimeException When unable to write output (should never happen)
51 public function doWrite($message, $newline)
53 $pipe = $this->getPipe();
54 if (false === @fwrite($pipe, $message . ($newline ? PHP_EOL : ''))) {
55 // @codeCoverageIgnoreStart
56 // should never happen
57 throw new \RuntimeException('Unable to write output.');
58 // @codeCoverageIgnoreEnd
65 * Close the current pager process.
67 public function close()
69 if (isset($this->pipe)) {
73 if (isset($this->proc)) {
74 $exit = proc_close($this->proc);
76 throw new \RuntimeException('Error closing output stream');
80 unset($this->pipe, $this->proc);
84 * Get a pipe for paging output.
86 * If no active pager process exists, fork one and return its input pipe.
88 private function getPipe()
90 if (!isset($this->pipe) || !isset($this->proc)) {
91 $desc = array(array('pipe', 'r'), $this->stream, fopen('php://stderr', 'w'));
92 $this->proc = proc_open($this->cmd, $desc, $pipes);
94 if (!is_resource($this->proc)) {
95 throw new \RuntimeException('Error opening output stream');
98 $this->pipe = $pipes[0];