Автор: Konstantin Kudryashov (ever.zet@gmail.com)
Наследование: implements Symfony\Component\Console\Formatter\OutputFormatterInterface
Пример #1
0
 /**
  * {@inheritdoc}
  */
 public function removeFormat($string)
 {
     $this->innerFormatter->setDecorated(false);
     $formatted = $this->innerFormatter->format($string);
     $this->innerFormatter->setDecorated(true);
     return $formatted;
 }
Пример #2
0
 /**
  * Override run method to internationalize error message.
  *
  * @param \Symfony\Component\Console\Input\InputInterface $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  * @return int Return code
  */
 public function run(InputInterface $input, OutputInterface $output)
 {
     // Set extra colors
     // The most problem is $output->getFormatter() don't work.
     // So create new formatter to add extra color.
     $formatter = new OutputFormatter($output->isDecorated());
     $formatter->setStyle('red', new OutputFormatterStyle('red', 'black'));
     $formatter->setStyle('green', new OutputFormatterStyle('green', 'black'));
     $formatter->setStyle('yellow', new OutputFormatterStyle('yellow', 'black'));
     $formatter->setStyle('blue', new OutputFormatterStyle('blue', 'black'));
     $formatter->setStyle('magenta', new OutputFormatterStyle('magenta', 'black'));
     $formatter->setStyle('yellow-blue', new OutputFormatterStyle('yellow', 'blue'));
     $output->setFormatter($formatter);
     \App::setLocale(\Config::get('syncle::MessageLang'));
     try {
         $result = parent::run($input, $output);
     } catch (\RuntimeException $e) {
         // All error messages were hard coded in
         // Symfony/Component/Console/Input/Input.php
         if ($e->getMessage() == 'Not enough arguments.') {
             $this->error(\Lang::get('syncle::BaseCommand.ArgumentNotEnough'));
         } elseif ($e->getMessage() == 'Too many arguments.') {
             $this->error(\Lang::get('syncle::BaseCommand.TooManyArgument'));
         } elseif (preg_match('/The "(.+)" option does not exist./', $e->getMessage(), $matches)) {
             $this->error(\Lang::get('syncle::BaseCommand.OptionNotExist', array('option' => $matches[1])));
         } else {
             $this->error($e->getMessage());
         }
         $result = 1;
     }
     return $result;
 }
Пример #3
0
 public function testFormattedEscapedOutput()
 {
     $output = new StreamOutput($this->stream, StreamOutput::VERBOSITY_NORMAL, true, null);
     $output->writeln('<info>' . OutputFormatter::escape('<error>some error</error>') . '</info>');
     rewind($output->getStream());
     $this->assertSame("<error>some error</error>" . PHP_EOL, stream_get_contents($output->getStream()));
 }
 /**
  * {@inheritdoc}
  */
 protected function writePrompt(OutputInterface $output, Question $question)
 {
     $text = OutputFormatter::escape($question->getQuestion());
     $default = $question->getDefault();
     switch (true) {
         case null === $default:
             $text = sprintf(' <info>%s</info>:', $text);
             break;
         case $question instanceof ConfirmationQuestion:
             $text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no');
             break;
         case $question instanceof ChoiceQuestion && $question->isMultiselect():
             $choices = $question->getChoices();
             $default = explode(',', $default);
             foreach ($default as $key => $value) {
                 $default[$key] = $choices[trim($value)];
             }
             $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape(implode(', ', $default)));
             break;
         case $question instanceof ChoiceQuestion:
             $choices = $question->getChoices();
             $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape($choices[$default]));
             break;
         default:
             $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape($default));
     }
     $output->writeln($text);
     if ($question instanceof ChoiceQuestion) {
         $width = max(array_map('strlen', array_keys($question->getChoices())));
         foreach ($question->getChoices() as $key => $value) {
             $output->writeln(sprintf("  [<comment>%-{$width}s</comment>] %s", $key, $value));
         }
     }
     $output->write(' > ');
 }
Пример #5
0
 /**
  * {@inheritdoc}
  */
 public function generate(ReportSummary $reportSummary)
 {
     $dom = new \DOMDocument('1.0', 'UTF-8');
     // new nodes should be added to this or existing children
     $root = $dom->createElement('report');
     $dom->appendChild($root);
     $filesXML = $dom->createElement('files');
     $root->appendChild($filesXML);
     $i = 1;
     foreach ($reportSummary->getChanged() as $file => $fixResult) {
         $fileXML = $dom->createElement('file');
         $fileXML->setAttribute('id', $i++);
         $fileXML->setAttribute('name', $file);
         $filesXML->appendChild($fileXML);
         if ($reportSummary->shouldAddAppliedFixers()) {
             $fileXML->appendChild($this->createAppliedFixersElement($dom, $fixResult));
         }
         if (!empty($fixResult['diff'])) {
             $fileXML->appendChild($this->createDiffElement($dom, $fixResult));
         }
     }
     if (null !== $reportSummary->getTime()) {
         $root->appendChild($this->createTimeElement($reportSummary->getTime(), $dom));
     }
     if (null !== $reportSummary->getTime()) {
         $root->appendChild($this->createMemoryElement($reportSummary->getMemory(), $dom));
     }
     $dom->formatOutput = true;
     return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML();
 }
 public function format($message)
 {
     $message = preg_replace('/<info>(.*),\\s*(.*)<\\/info>/i', '<info>$2 ($1)</info>', $message);
     $formatted = parent::format($message);
     $clearEscapeCodes = '(?:39|49|0|22|24|25|27|28)';
     return preg_replace_callback("{\\[([0-9;]+)m(.*?)\\[(?:" . $clearEscapeCodes . ";)*?" . $clearEscapeCodes . "m}s", array($this, 'formatHtml'), $formatted);
 }
 /**
  * Print escaped values of all parameters
  * Strings like 'Namespace\\' has to be escaped
  *
  * @link https://github.com/symfony/symfony/issues/17908
  *
  * @return void
  */
 public function complete()
 {
     $this->io->write('<info>Summary :</info>');
     foreach ($this->getConfigKey('Placeholders') as $placeholder) {
         $this->io->write(sprintf(_('%1$s: <info>%2$s</info>'), Formatter\OutputFormatter::escape($placeholder['name']), Formatter\OutputFormatter::escape($placeholder['value'])));
     }
 }
Пример #8
0
 /**
  * @param boolean $decorated
  *
  * @param array $styles
  */
 public function __construct($decorated = false, array $styles = array())
 {
     parent::__construct($decorated, $styles);
     $this->setStyle('pending', new OutputFormatterStyle('yellow'));
     $this->setStyle('pending-bg', new OutputFormatterStyle('black', 'yellow', array('bold')));
     $this->setStyle('skipped', new OutputFormatterStyle('cyan'));
     $this->setStyle('skipped-bg', new OutputFormatterStyle('white', 'cyan', array('bold')));
     $this->setStyle('failed', new OutputFormatterStyle('red'));
     $this->setStyle('failed-bg', new OutputFormatterStyle('white', 'red', array('bold')));
     $this->setStyle('broken', new OutputFormatterStyle('magenta'));
     $this->setStyle('broken-bg', new OutputFormatterStyle('white', 'magenta', array('bold')));
     $this->setStyle('passed', new OutputFormatterStyle('green'));
     $this->setStyle('passed-bg', new OutputFormatterStyle('black', 'green', array('bold')));
     $this->setStyle('value', new OutputFormatterStyle('yellow'));
     $this->setStyle('lineno', new OutputFormatterStyle(null, 'black'));
     $this->setStyle('code', new OutputFormatterStyle('white'));
     $this->setStyle('hl', new OutputFormatterStyle('black', 'yellow', array('bold')));
     $this->setStyle('question', new OutputFormatterStyle('black', 'yellow', array('bold')));
     $this->setStyle('trace', new OutputFormatterStyle());
     $this->setStyle('trace-class', new OutputFormatterStyle('cyan'));
     $this->setStyle('trace-func', new OutputFormatterStyle('cyan'));
     $this->setStyle('trace-type', new OutputFormatterStyle());
     $this->setStyle('trace-args', new OutputFormatterStyle());
     $this->setStyle('diff-add', new OutputFormatterStyle('green'));
     $this->setStyle('diff-del', new OutputFormatterStyle('red'));
 }
Пример #9
0
 /**
  * Formats a message as a block of text.
  *
  * @param string|array $messages The message to write in the block
  * @param string|null $type The block type (added in [] on first line)
  * @param string|null $style The style to apply to the whole block
  * @param string $prefix The prefix for the block
  * @param bool $padding Whether to add vertical padding
  */
 public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false)
 {
     $this->autoPrependBlock();
     $messages = is_array($messages) ? array_values($messages) : array($messages);
     $lines = array();
     // add type
     if (null !== $type) {
         $messages[0] = sprintf('[%s] %s', $type, $messages[0]);
     }
     // wrap and add newlines for each element
     foreach ($messages as $key => $message) {
         $message = OutputFormatter::escape($message);
         $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - Helper::strlen($prefix), PHP_EOL, true)));
         if (count($messages) > 1 && $key < count($messages) - 1) {
             $lines[] = '';
         }
     }
     if ($padding && $this->isDecorated()) {
         array_unshift($lines, '');
         $lines[] = '';
     }
     foreach ($lines as &$line) {
         $line = sprintf('%s%s', $prefix, $line);
         $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
         if ($style) {
             $line = sprintf('<%s>%s</>', $style, $line);
         }
     }
     $this->writeln($lines);
     $this->newLine();
 }
Пример #10
0
 /**
  * Get a backtrace for an exception.
  *
  * Optionally limit the number of rows to include with $count, and exclude
  * Psy from the trace.
  *
  * @param \Exception $e          The exception with a backtrace.
  * @param int        $count      (default: PHP_INT_MAX)
  * @param bool       $includePsy (default: true)
  *
  * @return array Formatted stacktrace lines.
  */
 protected function getBacktrace(\Exception $e, $count = null, $includePsy = true)
 {
     if ($cwd = getcwd()) {
         $cwd = rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
     }
     if ($count === null) {
         $count = PHP_INT_MAX;
     }
     $lines = array();
     $trace = $e->getTrace();
     array_unshift($trace, array('function' => '', 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a', 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a', 'args' => array()));
     if (!$includePsy) {
         for ($i = count($trace) - 1; $i >= 0; $i--) {
             $thing = isset($trace[$i]['class']) ? $trace[$i]['class'] : $trace[$i]['function'];
             if (preg_match('/\\\\?Psy\\\\/', $thing)) {
                 $trace = array_slice($trace, $i + 1);
                 break;
             }
         }
     }
     for ($i = 0, $count = min($count, count($trace)); $i < $count; $i++) {
         $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
         $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
         $function = $trace[$i]['function'];
         $file = isset($trace[$i]['file']) ? $this->replaceCwd($cwd, $trace[$i]['file']) : 'n/a';
         $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
         $lines[] = sprintf(' <class>%s</class>%s%s() at <info>%s:%s</info>', OutputFormatter::escape($class), OutputFormatter::escape($type), OutputFormatter::escape($function), OutputFormatter::escape($file), OutputFormatter::escape($line));
     }
     return $lines;
 }
    public function testContentWithLineBreaks()
    {
        $formatter = new OutputFormatter(true);
        $this->assertEquals(<<<EOF

some text
EOF
, $formatter->format(<<<EOF
<info>
some text</info>
EOF
));
        $this->assertEquals(<<<EOF
some text

EOF
, $formatter->format(<<<EOF
<info>some text
</info>
EOF
));
        $this->assertEquals(<<<EOF

some text

EOF
, $formatter->format(<<<EOF
<info>
some text
</info>
EOF
));
        $this->assertEquals(<<<EOF

some text
more text

EOF
, $formatter->format(<<<EOF
<info>
some text
more text
</info>
EOF
));
    }
Пример #12
0
 /**
  * Constructor
  *
  * @author Art <*****@*****.**>
  */
 public function __construct()
 {
     parent::__construct();
     self::initStyles();
     foreach (self::$styles as $code => $class) {
         $this->setStyle($code, $class);
     }
 }
 /**
  * OutputFormatter constructor.
  *
  * @param bool  $decorated
  * @param array $styles
  */
 public function __construct($decorated = false, array $styles = array())
 {
     parent::__construct($decorated, $styles);
     $this->setStyle('passed', new OutputFormatterStyle('green', null, array()));
     $this->setStyle('passed-bg', new OutputFormatterStyle('black', 'green', array('bold')));
     $this->setStyle('broken', new OutputFormatterStyle('red', null, array()));
     $this->setStyle('broken-bg', new OutputFormatterStyle('white', 'red', array('bold')));
     $this->setStyle('blink', new OutputFormatterStyle(null, null, array('blink')));
 }
Пример #14
0
 public function __construct($decorated = false, array $styles = array())
 {
     parent::__construct(true, $styles);
     $this->setStyle('logo', new OutputFormatterStyle('magenta'));
     $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
     $this->setStyle('comment', new OutputFormatterStyle('magenta', null, array('underscore')));
     $this->setStyle('info', new OutputFormatterStyle('cyan'));
     $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
 }
Пример #15
0
 function __construct($config)
 {
     $this->config = array_merge($this->config, $config);
     // enable interactive output mode for CLI
     $this->isInteractive = $this->config['interactive'] && isset($_SERVER['TERM']) && php_sapi_name() == 'cli' && $_SERVER['TERM'] != 'linux';
     $formatter = new OutputFormatter($this->config['colors']);
     $formatter->setStyle('bold', new OutputFormatterStyle(null, null, ['bold']));
     $formatter->setStyle('focus', new OutputFormatterStyle('magenta', null, ['bold']));
     $formatter->setStyle('ok', new OutputFormatterStyle('white', 'magenta'));
     $formatter->setStyle('error', new OutputFormatterStyle('white', 'red'));
     $formatter->setStyle('debug', new OutputFormatterStyle('cyan'));
     $formatter->setStyle('comment', new OutputFormatterStyle('yellow'));
     $formatter->setStyle('info', new OutputFormatterStyle('green'));
     $this->formatHelper = new FormatterHelper();
     parent::__construct($this->config['verbosity'], $this->config['colors'], $formatter);
 }
Пример #16
0
 /**
  * Initialize and get console output formatter
  *
  * @return OutputFormatter
  */
 protected function getOutputFormatter()
 {
     if (null === $this->outputFormatter) {
         $formatter = new OutputFormatter(true);
         $formatter->setStyle(LogLevel::EMERGENCY, new OutputFormatterStyle('white', 'red'));
         $formatter->setStyle(LogLevel::ALERT, new OutputFormatterStyle('white', 'red'));
         $formatter->setStyle(LogLevel::CRITICAL, new OutputFormatterStyle('red'));
         $formatter->setStyle(LogLevel::ERROR, new OutputFormatterStyle('red'));
         $formatter->setStyle(LogLevel::WARNING, new OutputFormatterStyle('yellow'));
         $formatter->setStyle(LogLevel::NOTICE, new OutputFormatterStyle());
         $formatter->setStyle(LogLevel::INFO, new OutputFormatterStyle());
         $formatter->setStyle(LogLevel::DEBUG, new OutputFormatterStyle('cyan'));
         $this->outputFormatter = $formatter;
     }
     return $this->outputFormatter;
 }
Пример #17
0
 function __construct($config)
 {
     $this->config = array_merge($this->config, $config);
     $formatter = new OutputFormatter($this->config['colors']);
     $formatter->setStyle('bold', new OutputFormatterStyle(null, null, array('bold')));
     $formatter->setStyle('focus', new OutputFormatterStyle('magenta', null, array('bold')));
     $formatter->setStyle('ok', new OutputFormatterStyle('white', 'magenta'));
     $formatter->setStyle('error', new OutputFormatterStyle('white', 'red'));
     $formatter->setStyle('debug', new OutputFormatterStyle('cyan'));
     $formatter->setStyle('info', new OutputFormatterStyle('yellow'));
     $this->formatHelper = new FormatterHelper();
     parent::__construct($this->config['verbosity'], $this->config['colors'], $formatter);
 }
Пример #18
0
 /**
  * Present a reference to the value.
  *
  * @param mixed $value
  *
  * @return string
  */
 public function presentRef($value, $color = false)
 {
     $type = get_resource_type($value);
     if ($type === 'stream') {
         $meta = stream_get_meta_data($value);
         $type = sprintf('%s stream', $meta['stream_type']);
     }
     $id = str_replace('Resource id #', '', (string) $value);
     $format = $color ? self::COLOR_FMT : self::FMT;
     return sprintf($format, OutputFormatter::escape('<'), $type, $id);
 }
 public function run(InputInterface $input, OutputInterface $output)
 {
     // Set extra colors.
     // The most problem is $output->getFormatter() don't work...
     // So create new formatter to add extra color.
     $formatter = new OutputFormatter($output->isDecorated());
     $formatter->setStyle('red', new OutputFormatterStyle('red', 'black'));
     $formatter->setStyle('green', new OutputFormatterStyle('green', 'black'));
     $formatter->setStyle('yellow', new OutputFormatterStyle('yellow', 'black'));
     $formatter->setStyle('blue', new OutputFormatterStyle('blue', 'black'));
     $formatter->setStyle('magenta', new OutputFormatterStyle('magenta', 'black'));
     $formatter->setStyle('yellow-blue', new OutputFormatterStyle('yellow', 'blue'));
     $output->setFormatter($formatter);
     return parent::run($input, $output);
 }
 /**
  * @param string $diff
  * @param string $lineTemplate
  *
  * @return string
  */
 public function format($diff, $lineTemplate = '%s')
 {
     $isDecorated = $this->isDecoratedOutput;
     $template = $isDecorated ? $this->template : preg_replace('/<[^<>]+>/', '', $this->template);
     return sprintf($template, implode(PHP_EOL, array_map(function ($string) use($isDecorated, $lineTemplate) {
         if ($isDecorated) {
             $string = preg_replace(array('/^(\\+.*)/', '/^(\\-.*)/', '/^(@.*)/'), array('<fg=green>\\1</fg=green>', '<fg=red>\\1</fg=red>', '<fg=cyan>\\1</fg=cyan>'), $string);
         }
         $templated = sprintf($lineTemplate, $string);
         if (' ' === $string) {
             $templated = rtrim($templated);
         }
         return $templated;
     }, preg_split("#\n\r|\n#", $isDecorated ? OutputFormatter::escape(rtrim($diff)) : $diff))));
 }
Пример #21
0
 /**
  * Constructs a new OutputFormatter.
  *
  * @param bool                            $decorated
  * @param OutputFormatterStyleInterface[] $styles
  */
 public function __construct($decorated = false, array $styles = array())
 {
     parent::__construct($decorated, $styles);
     $this->setStyle('title', new OutputFormatterStyle());
     $this->setStyle(LogLevel::EMERGENCY, new OutputFormatterStyle('white', 'red'));
     $this->setStyle(LogLevel::CRITICAL, new OutputFormatterStyle('white', 'red'));
     $this->setStyle(LogLevel::ALERT, new OutputFormatterStyle('white', 'red'));
     $this->setStyle(LogLevel::ERROR, new OutputFormatterStyle('white', 'red'));
     $this->setStyle(LogLevel::WARNING, new OutputFormatterStyle('white', 'red'));
     $this->setStyle(LogLevel::NOTICE, new OutputFormatterStyle());
     $this->setStyle(LogLevel::INFO, new OutputFormatterStyle('black', 'yellow'));
     $this->setStyle(LogLevel::DEBUG, new OutputFormatterStyle());
     $this->setStyle('event-name', new OutputFormatterStyle('yellow'));
     $this->setStyle('event-task-name', new OutputFormatterStyle('yellow'));
     $this->setStyle('event-task-action-in_progress', new OutputFormatterStyle());
     $this->setStyle('event-task-action-failed', new OutputFormatterStyle('red'));
     $this->setStyle('event-task-action-completed', new OutputFormatterStyle('green'));
 }
Пример #22
0
 /**
  * Writes a file in two phase to the filesystem.
  *
  * First write the data to a temporary file (in the same directory) and than renames the temporary file. If the file
  * already exists and its content is equal to the data that must be written no action  is taken. This has the
  * following advantages:
  * * In case of some write error (e.g. disk full) the original file is kept in tact and no file with partially data
  * is written.
  * * Renaming a file is atomic. So, running processes will never read a partially written data.
  *
  * @param string       $filename The name of the file were the data must be stored.
  * @param string       $data     The data that must be written.
  * @param StratumStyle $io       The output decorator.
  */
 static function writeTwoPhases($filename, $data, $io)
 {
     $write_flag = true;
     if (file_exists($filename)) {
         $old_data = file_get_contents($filename);
         if ($data == $old_data) {
             $write_flag = false;
         }
     }
     if ($write_flag) {
         $tmp_filename = $filename . '.tmp';
         file_put_contents($tmp_filename, $data);
         rename($tmp_filename, $filename);
         $io->text(sprintf('Wrote <fso>%s</fso>', OutputFormatter::escape($filename)));
     } else {
         $io->text(sprintf('File <fso>%s</fso> is up to date', OutputFormatter::escape($filename)));
     }
 }
Пример #23
0
 /**
  * {@inheritdoc}
  */
 public function generate(ReportSummary $reportSummary)
 {
     $dom = new \DOMDocument('1.0', 'UTF-8');
     $testsuites = $dom->appendChild($dom->createElement('testsuites'));
     /** @var \DomElement $testsuite */
     $testsuite = $testsuites->appendChild($dom->createElement('testsuite'));
     $testsuite->setAttribute('name', 'PHP CS Fixer');
     if (count($reportSummary->getChanged())) {
         $this->createFailedTestCases($dom, $testsuite, $reportSummary);
     } else {
         $this->createSuccessTestCase($dom, $testsuite);
     }
     if ($reportSummary->getTime()) {
         $testsuite->setAttribute('time', sprintf('%.3f', $reportSummary->getTime() / 1000));
     }
     $dom->formatOutput = true;
     return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML();
 }
 private function format($value)
 {
     // Handle floats.
     if (is_float($value)) {
         // Some are unencodable...
         if (is_nan($value)) {
             return 'NAN';
         } elseif (is_infinite($value)) {
             return $value === INF ? 'INF' : '-INF';
         }
         // ... others just encode as ints when there's no decimal
         $float = Json::encode($value);
         if (strpos($float, '.') === false) {
             $float .= '.0';
         }
         return $float;
     }
     return OutputFormatter::escape(Json::encode($value));
 }
Пример #25
0
 /**
  * Formats a message as a block of text.
  *
  * @param string|array $messages The message to write in the block
  * @param string|null  $type     The block type (added in [] on first line)
  * @param string|null  $style    The style to apply to the whole block
  * @param string       $prefix   The prefix for the block
  * @param bool         $padding  Whether to add vertical padding
  */
 public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false)
 {
     $this->autoPrependBlock();
     $messages = is_array($messages) ? array_values($messages) : array($messages);
     $indentLength = 0;
     $lines = array();
     if (null !== $type) {
         $typePrefix = sprintf('[%s] ', $type);
         $indentLength = strlen($typePrefix);
         $lineIndentation = str_repeat(' ', $indentLength);
     }
     // wrap and add newlines for each element
     foreach ($messages as $key => $message) {
         $message = OutputFormatter::escape($message);
         $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - Helper::strlen($prefix) - $indentLength, PHP_EOL, true)));
         // prefix each line with a number of spaces equivalent to the type length
         if (null !== $type) {
             foreach ($lines as &$line) {
                 $line = $lineIndentation === substr($line, 0, $indentLength) ? $line : $lineIndentation . $line;
             }
         }
         if (count($messages) > 1 && $key < count($messages) - 1) {
             $lines[] = '';
         }
     }
     if (null !== $type) {
         $lines[0] = substr_replace($lines[0], $typePrefix, 0, $indentLength);
     }
     if ($padding && $this->isDecorated()) {
         array_unshift($lines, '');
         $lines[] = '';
     }
     foreach ($lines as &$line) {
         $line = sprintf('%s%s', $prefix, $line);
         $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
         if ($style) {
             $line = sprintf('<%s>%s</>', $style, $line);
         }
     }
     $this->writeln($lines);
     $this->newLine();
 }
Пример #26
0
 /**
  * @param bool  $isDecoratedOutput
  * @param array $fixResult
  *
  * @return string
  */
 private function getDiff($isDecoratedOutput, array $fixResult)
 {
     if (empty($fixResult['diff'])) {
         return '';
     }
     if ($isDecoratedOutput) {
         $template = '<comment>      ---------- begin diff ----------</comment>%s<comment>      ----------- end diff -----------</comment>';
         $diff = implode(PHP_EOL, array_map(function ($string) {
             $string = preg_replace('/^(\\+){3}/', '<info>+++</info>', $string);
             $string = preg_replace('/^(\\+){1}/', '<info>+</info>', $string);
             $string = preg_replace('/^(\\-){3}/', '<error>---</error>', $string);
             $string = preg_replace('/^(\\-){1}/', '<error>-</error>', $string);
             return $string;
         }, explode(PHP_EOL, OutputFormatter::escape($fixResult['diff']))));
     } else {
         $template = '      ---------- begin diff ----------%s      ----------- end diff -----------';
         $diff = $fixResult['diff'];
     }
     return PHP_EOL . sprintf($template, PHP_EOL . $diff . PHP_EOL) . PHP_EOL;
 }
Пример #27
0
 /**
  * Formats a message as a block of text.
  *
  * @param string|array $messages The message to write in the block
  * @param string       $style    The style to apply to the whole block
  * @param bool         $large    Whether to return a large block
  *
  * @return string The formatter message
  */
 public function formatBlock($messages, $style, $large = false)
 {
     $messages = (array) $messages;
     $len = 0;
     $lines = array();
     foreach ($messages as $message) {
         $message = OutputFormatter::escape($message);
         $lines[] = sprintf($large ? '  %s  ' : ' %s ', $message);
         $len = max($this->strlen($message) + ($large ? 4 : 2), $len);
     }
     $messages = $large ? array(str_repeat(' ', $len)) : array();
     foreach ($lines as $line) {
         $messages[] = $line . str_repeat(' ', $len - $this->strlen($line));
     }
     if ($large) {
         $messages[] = str_repeat(' ', $len);
     }
     foreach ($messages as &$message) {
         $message = sprintf('<%s>%s</%s>', $style, $message, $style);
     }
     return implode("\n", $messages);
 }
Пример #28
0
 private function renderCodeCoverage(array $reportLines, $widestLine)
 {
     $output = '';
     $widestLineNum = mb_strlen(count($reportLines));
     foreach ($reportLines as $i => $line) {
         $source = $this->formatter->escape(str_pad($line['line'], $widestLine));
         $lineNum = str_pad((string) ($i + 1), $widestLineNum, ' ', STR_PAD_LEFT);
         switch ($line['code']) {
             case self::COVERAGE_COVERED:
                 $output .= $this->formatter->format(sprintf('<bg=white;fg=green>[%s] %s</>', $lineNum, $source));
                 break;
             case self::COVERAGE_NOT_COVERED:
                 $output .= $this->formatter->format(sprintf('<bg=white;fg=red>[%s] %s</>', $lineNum, $source));
                 break;
             case self::COVERAGE_META:
                 $output .= $this->formatter->format(sprintf('<bg=white;fg=black>[%s] %s</>', $lineNum, $source));
                 break;
         }
         $output .= PHP_EOL;
     }
     return $output;
 }
Пример #29
0
 /**
  * {@inheritdoc}
  */
 public function generate(ReportSummary $reportSummary)
 {
     $jFiles = array();
     foreach ($reportSummary->getChanged() as $file => $fixResult) {
         $jfile = array('name' => $file);
         if ($reportSummary->shouldAddAppliedFixers()) {
             $jfile['appliedFixers'] = $fixResult['appliedFixers'];
         }
         if (!empty($fixResult['diff'])) {
             $jfile['diff'] = $fixResult['diff'];
         }
         $jFiles[] = $jfile;
     }
     $json = array('files' => $jFiles);
     if (null !== $reportSummary->getTime()) {
         $json['time'] = array('total' => round($reportSummary->getTime() / 1000, 3));
     }
     if (null !== $reportSummary->getMemory()) {
         $json['memory'] = round($reportSummary->getMemory() / 1024 / 1024, 3);
     }
     $json = json_encode($json);
     return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($json) : $json;
 }
 /**
  * Renders a caught Exception.
  *
  * Exceptions are formatted according to severity. ErrorExceptions which were
  * warnings or Strict errors aren't rendered as harshly as real errors.
  *
  * Stores $e as the last Exception in the Shell Context.
  *
  * @param \Exception      $e      An exception instance
  * @param OutputInterface $output An OutputInterface instance
  */
 public function renderException($e, $output)
 {
     $this->context->setLastException($e);
     $message = $e->getMessage();
     if (!$e instanceof PsyException) {
         $message = sprintf('%s with message \'%s\'', get_class($e), $message);
     }
     $severity = $e instanceof \ErrorException ? $this->getSeverity($e) : 'error';
     $output->writeln(sprintf('<%s>%s</%s>', $severity, OutputFormatter::escape($message), $severity));
     $this->resetCodeBuffer();
 }