123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192 |
- <?php
- namespace Symfony\Component\Console\Formatter;
- class OutputFormatter implements OutputFormatterInterface
- {
-
- const FORMAT_PATTERN = '#<([a-z][a-z0-9_=;-]+)>(.*?)</\\1?>#is';
- private $decorated;
- private $styles = array();
-
- public function __construct($decorated = null, array $styles = array())
- {
- $this->decorated = (Boolean) $decorated;
- $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
- $this->setStyle('info', new OutputFormatterStyle('green'));
- $this->setStyle('comment', new OutputFormatterStyle('yellow'));
- $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
- foreach ($styles as $name => $style) {
- $this->setStyle($name, $style);
- }
- }
-
- public function setDecorated($decorated)
- {
- $this->decorated = (Boolean) $decorated;
- }
-
- public function isDecorated()
- {
- return $this->decorated;
- }
-
- public function setStyle($name, OutputFormatterStyleInterface $style)
- {
- $this->styles[strtolower($name)] = $style;
- }
-
- public function hasStyle($name)
- {
- return isset($this->styles[strtolower($name)]);
- }
-
- public function getStyle($name)
- {
- if (!$this->hasStyle($name)) {
- throw new \InvalidArgumentException('Undefined style: '.$name);
- }
- return $this->styles[strtolower($name)];
- }
-
- public function format($message)
- {
- return preg_replace_callback(self::FORMAT_PATTERN, array($this, 'replaceStyle'), $message);
- }
-
- private function replaceStyle($match)
- {
- if (!$this->isDecorated()) {
- return $match[2];
- }
- if (isset($this->styles[strtolower($match[1])])) {
- $style = $this->styles[strtolower($match[1])];
- } else {
- $style = $this->createStyleFromString($match[1]);
- if (false === $style) {
- return $match[0];
- }
- }
- return $style->apply($this->format($match[2]));
- }
-
- private function createStyleFromString($string)
- {
- if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', strtolower($string), $matches, PREG_SET_ORDER)) {
- return false;
- }
- $style = new OutputFormatterStyle();
- foreach ($matches as $match) {
- array_shift($match);
- if ('fg' == $match[0]) {
- $style->setForeground($match[1]);
- } elseif ('bg' == $match[0]) {
- $style->setBackground($match[1]);
- } else {
- $style->setOption($match[1]);
- }
- }
- return $style;
- }
- }
|