Skip to content

Commit

Permalink
[Console] Updated formatter to use style stack.
Browse files Browse the repository at this point in the history
  • Loading branch information
jfsimon committed Apr 11, 2012
1 parent bd1d28c commit 4ee8cfb
Showing 1 changed file with 39 additions and 9 deletions.
48 changes: 39 additions & 9 deletions src/Symfony/Component/Console/Formatter/OutputFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ class OutputFormatter implements OutputFormatterInterface
/**
* The pattern to phrase the format.
*/
const FORMAT_PATTERN = '#<([a-z][a-z0-9_=;-]+)>(.*?)</\\1?>#is';
const FORMAT_PATTERN = '#<(/?)([a-z][a-z0-9_=;-]+)?>([^<]*)#is';

private $decorated;
private $styles = array();
private $styleStack;

/**
* Initializes console output formatter.
Expand All @@ -48,6 +49,8 @@ public function __construct($decorated = null, array $styles = array())
foreach ($styles as $name => $style) {
$this->setStyle($name, $style);
}

$this->styleStack = new OutputFormatterStyleStack();
}

/**
Expand Down Expand Up @@ -144,29 +147,43 @@ public function format($message)
*/
private function replaceStyle($match)
{
if (!$this->isDecorated()) {
return $match[2];
if ('' === $match[2]) {
if ('/' === $match[1]) {
// we got "</>" tag
$this->styleStack->pop();

return $this->applyStyle($this->styleStack->getCurrent(), $match[3]);
}

// we got "<>" tag
return '<>'.$match[3];
}

if (isset($this->styles[strtolower($match[1])])) {
$style = $this->styles[strtolower($match[1])];
if (isset($this->styles[strtolower($match[2])])) {
$style = $this->styles[strtolower($match[2])];
} else {
$style = $this->createStyleFromString($match[1]);
$style = $this->createStyleFromString($match[2]);

if (false === $style) {
return $match[0];
return $match[3];
}
}

return $style->apply($this->format($match[2]));
if ('/' === $match[1]) {
$this->styleStack->pop($style);
} else {
$this->styleStack->push($style);
}

return $this->applyStyle($this->styleStack->getCurrent(), $match[3]);
}

/**
* Tries to create new style instance from string.
*
* @param string $string
*
* @return Symfony\Component\Console\Format\FormatterStyle|Boolean false if string is not format string
* @return \Symfony\Component\Console\Formatter\OutputFormatterStyle|Boolean false if string is not format string
*/
private function createStyleFromString($string)
{
Expand All @@ -189,4 +206,17 @@ private function createStyleFromString($string)

return $style;
}

/**
* Applies style to text if must be applied.
*
* @param OutputFormatterStyleInterface $style Style to apply
* @param string $text Input text
*
* @return string string Styled text
*/
private function applyStyle(OutputFormatterStyleInterface $style, $text)
{
return $this->isDecorated() && strlen($text) > 0 ? $style->apply($text) : $text;
}
}

0 comments on commit 4ee8cfb

Please sign in to comment.