FormatterHelper.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Helper;
  11. use Symfony\Component\Console\Formatter\OutputFormatter;
  12. /**
  13. * The Formatter class provides helpers to format messages.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class FormatterHelper extends Helper
  18. {
  19. /**
  20. * Formats a message within a section.
  21. *
  22. * @param string $section The section name
  23. * @param string $message The message
  24. * @param string $style The style to apply to the section
  25. *
  26. * @return string The format section
  27. */
  28. public function formatSection($section, $message, $style = 'info')
  29. {
  30. return sprintf('<%s>[%s]</%s> %s', $style, $section, $style, $message);
  31. }
  32. /**
  33. * Formats a message as a block of text.
  34. *
  35. * @param string|array $messages The message to write in the block
  36. * @param string $style The style to apply to the whole block
  37. * @param bool $large Whether to return a large block
  38. *
  39. * @return string The formatter message
  40. */
  41. public function formatBlock($messages, $style, $large = false)
  42. {
  43. if (!\is_array($messages)) {
  44. $messages = array($messages);
  45. }
  46. $len = 0;
  47. $lines = array();
  48. foreach ($messages as $message) {
  49. $message = OutputFormatter::escape($message);
  50. $lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
  51. $len = max($this->strlen($message) + ($large ? 4 : 2), $len);
  52. }
  53. $messages = $large ? array(str_repeat(' ', $len)) : array();
  54. for ($i = 0; isset($lines[$i]); ++$i) {
  55. $messages[] = $lines[$i].str_repeat(' ', $len - $this->strlen($lines[$i]));
  56. }
  57. if ($large) {
  58. $messages[] = str_repeat(' ', $len);
  59. }
  60. for ($i = 0; isset($messages[$i]); ++$i) {
  61. $messages[$i] = sprintf('<%s>%s</%s>', $style, $messages[$i], $style);
  62. }
  63. return implode("\n", $messages);
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function getName()
  69. {
  70. return 'formatter';
  71. }
  72. }