4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Output;
14 use Symfony\Component\Console\Formatter\OutputFormatterInterface;
17 * StreamOutput writes the output to a given stream.
21 * $output = new StreamOutput(fopen('php://stdout', 'w'));
23 * As `StreamOutput` can use any stream, you can also use a file:
25 * $output = new StreamOutput(fopen('/path/to/output.log', 'a', false));
27 * @author Fabien Potencier <fabien@symfony.com>
31 class StreamOutput extends Output
38 * @param mixed $stream A stream resource
39 * @param integer $verbosity The verbosity level (self::VERBOSITY_QUIET, self::VERBOSITY_NORMAL,
40 * self::VERBOSITY_VERBOSE)
41 * @param Boolean $decorated Whether to decorate messages or not (null for auto-guessing)
42 * @param OutputFormatter $formatter Output formatter instance
44 * @throws \InvalidArgumentException When first argument is not a real stream
48 public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
50 if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) {
51 throw new \InvalidArgumentException('The StreamOutput class needs a stream as its first argument.');
54 $this->stream = $stream;
56 if (null === $decorated) {
57 $decorated = $this->hasColorSupport($decorated);
60 parent::__construct($verbosity, $decorated, $formatter);
64 * Gets the stream attached to this StreamOutput instance.
66 * @return resource A stream resource
68 public function getStream()
74 * Writes a message to the output.
76 * @param string $message A message to write to the output
77 * @param Boolean $newline Whether to add a newline or not
79 * @throws \RuntimeException When unable to write output (should never happen)
81 protected function doWrite($message, $newline)
83 if (false === @fwrite($this->stream, $message.($newline ? PHP_EOL : ''))) {
84 // @codeCoverageIgnoreStart
85 // should never happen
86 throw new \RuntimeException('Unable to write output.');
87 // @codeCoverageIgnoreEnd
90 fflush($this->stream);
94 * Returns true if the stream supports colorization.
96 * Colorization is disabled if not supported by the stream:
98 * - windows without ansicon
101 * @return Boolean true if the stream supports colorization, false otherwise
103 protected function hasColorSupport()
105 // @codeCoverageIgnoreStart
106 if (DIRECTORY_SEPARATOR == '\\') {
107 return false !== getenv('ANSICON');
110 return function_exists('posix_isatty') && @posix_isatty($this->stream);
111 // @codeCoverageIgnoreEnd