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;
16 private static $width;
17 private static $height;
20 * Gets the terminal width.
24 public function getWidth()
26 $width = getenv('COLUMNS');
27 if (false !== $width) {
28 return (int) trim($width);
31 if (null === self::$width) {
32 self::initDimensions();
35 return self::$width ?: 80;
39 * Gets the terminal height.
43 public function getHeight()
45 $height = getenv('LINES');
46 if (false !== $height) {
47 return (int) trim($height);
50 if (null === self::$height) {
51 self::initDimensions();
54 return self::$height ?: 50;
57 private static function initDimensions()
59 if ('\\' === \DIRECTORY_SEPARATOR) {
60 if (preg_match('/^(\d+)x(\d+)(?: \((\d+)x(\d+)\))?$/', trim(getenv('ANSICON')), $matches)) {
61 // extract [w, H] from "wxh (WxH)"
62 // or [w, h] from "wxh"
63 self::$width = (int) $matches[1];
64 self::$height = isset($matches[4]) ? (int) $matches[4] : (int) $matches[2];
65 } elseif (null !== $dimensions = self::getConsoleMode()) {
66 // extract [w, h] from "wxh"
67 self::$width = (int) $dimensions[0];
68 self::$height = (int) $dimensions[1];
70 } elseif ($sttyString = self::getSttyColumns()) {
71 if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
72 // extract [w, h] from "rows h; columns w;"
73 self::$width = (int) $matches[2];
74 self::$height = (int) $matches[1];
75 } elseif (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
76 // extract [w, h] from "; h rows; w columns"
77 self::$width = (int) $matches[2];
78 self::$height = (int) $matches[1];
84 * Runs and parses mode CON if it's available, suppressing any error output.
86 * @return int[]|null An array composed of the width and the height or null if it could not be parsed
88 private static function getConsoleMode()
90 if (!\function_exists('proc_open')) {
94 $descriptorspec = array(
95 1 => array('pipe', 'w'),
96 2 => array('pipe', 'w'),
98 $process = proc_open('mode CON', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
99 if (\is_resource($process)) {
100 $info = stream_get_contents($pipes[1]);
103 proc_close($process);
105 if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
106 return array((int) $matches[2], (int) $matches[1]);
112 * Runs and parses stty -a if it's available, suppressing any error output.
114 * @return string|null
116 private static function getSttyColumns()
118 if (!\function_exists('proc_open')) {
122 $descriptorspec = array(
123 1 => array('pipe', 'w'),
124 2 => array('pipe', 'w'),
127 $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
128 if (\is_resource($process)) {
129 $info = stream_get_contents($pipes[1]);
132 proc_close($process);