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\Exception\InvalidArgumentException;
15 use Symfony\Component\Console\Exception\RuntimeException;
16 use Symfony\Component\Console\Formatter\OutputFormatterInterface;
19 * StreamOutput writes the output to a given stream.
23 * $output = new StreamOutput(fopen('php://stdout', 'w'));
25 * As `StreamOutput` can use any stream, you can also use a file:
27 * $output = new StreamOutput(fopen('/path/to/output.log', 'a', false));
29 * @author Fabien Potencier <fabien@symfony.com>
31 class StreamOutput extends Output
38 * @param resource $stream A stream resource
39 * @param int $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface)
40 * @param bool|null $decorated Whether to decorate messages (null for auto-guessing)
41 * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter)
43 * @throws InvalidArgumentException When first argument is not a real stream
45 public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
47 if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) {
48 throw new InvalidArgumentException('The StreamOutput class needs a stream as its first argument.');
51 $this->stream = $stream;
53 if (null === $decorated) {
54 $decorated = $this->hasColorSupport();
57 parent::__construct($verbosity, $decorated, $formatter);
61 * Gets the stream attached to this StreamOutput instance.
63 * @return resource A stream resource
65 public function getStream()
73 protected function doWrite($message, $newline)
75 if (false === @fwrite($this->stream, $message) || ($newline && (false === @fwrite($this->stream, PHP_EOL)))) {
76 // should never happen
77 throw new RuntimeException('Unable to write output.');
80 fflush($this->stream);
84 * Returns true if the stream supports colorization.
86 * Colorization is disabled if not supported by the stream:
88 * - Windows != 10.0.10586 without Ansicon, ConEmu or Mintty
91 * @return bool true if the stream supports colorization, false otherwise
93 protected function hasColorSupport()
95 if (DIRECTORY_SEPARATOR === '\\') {
97 '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR.'.'.PHP_WINDOWS_VERSION_MINOR.'.'.PHP_WINDOWS_VERSION_BUILD
98 || false !== getenv('ANSICON')
99 || 'ON' === getenv('ConEmuANSI')
100 || 'xterm' === getenv('TERM');
103 return function_exists('posix_isatty') && @posix_isatty($this->stream);