2 namespace Consolidation\AnnotatedCommand\Options;
4 use Symfony\Component\Console\Application;
5 use Consolidation\AnnotatedCommand\CommandData;
6 use Consolidation\OutputFormatters\Options\FormatterOptions;
8 class PrepareTerminalWidthOption implements PrepareFormatter
10 /** var Application */
11 protected $application;
16 protected $defaultWidth;
19 protected $maxWidth = PHP_INT_MAX;
22 protected $minWidth = 0;
25 protected $shouldWrap = true;
27 public function __construct($defaultWidth = 0)
29 $this->defaultWidth = $defaultWidth;
32 public function setApplication(Application $application)
34 $this->application = $application;
37 public function setTerminal($terminal)
39 $this->terminal = $terminal;
42 public function getTerminal()
44 if (!$this->terminal && class_exists('\Symfony\Component\Console\Terminal')) {
45 $this->terminal = new \Symfony\Component\Console\Terminal();
47 return $this->terminal;
50 public function enableWrap($shouldWrap)
52 $this->shouldWrap = $shouldWrap;
55 public function prepare(CommandData $commandData, FormatterOptions $options)
57 $width = $this->getTerminalWidth();
59 $width = $this->defaultWidth;
62 // Enforce minimum and maximum widths
63 $width = min($width, $this->getMaxWidth($commandData));
64 $width = max($width, $this->getMinWidth($commandData));
66 $options->setWidth($width);
69 protected function getTerminalWidth()
71 // Don't wrap if wrapping has been disabled.
72 if (!$this->shouldWrap) {
76 $terminal = $this->getTerminal();
78 return $terminal->getWidth();
81 return $this->getTerminalWidthViaApplication();
84 protected function getTerminalWidthViaApplication()
86 if (!$this->application) {
89 $dimensions = $this->application->getTerminalDimensions();
90 if ($dimensions[0] == null) {
94 return $dimensions[0];
97 protected function getMaxWidth(CommandData $commandData)
99 return $this->maxWidth;
102 protected function getMinWidth(CommandData $commandData)
104 return $this->minWidth;