FormatterHelper.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. * @return string
  23. */
  24. public function formatSection(string $section, string $message, string $style = 'info')
  25. {
  26. return sprintf('<%s>[%s]</%s> %s', $style, $section, $style, $message);
  27. }
  28. /**
  29. * Formats a message as a block of text.
  30. *
  31. * @param string|array $messages The message to write in the block
  32. *
  33. * @return string
  34. */
  35. public function formatBlock($messages, string $style, bool $large = false)
  36. {
  37. if (!\is_array($messages)) {
  38. $messages = [$messages];
  39. }
  40. $len = 0;
  41. $lines = [];
  42. foreach ($messages as $message) {
  43. $message = OutputFormatter::escape($message);
  44. $lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
  45. $len = max(self::width($message) + ($large ? 4 : 2), $len);
  46. }
  47. $messages = $large ? [str_repeat(' ', $len)] : [];
  48. for ($i = 0; isset($lines[$i]); ++$i) {
  49. $messages[] = $lines[$i].str_repeat(' ', $len - self::width($lines[$i]));
  50. }
  51. if ($large) {
  52. $messages[] = str_repeat(' ', $len);
  53. }
  54. for ($i = 0; isset($messages[$i]); ++$i) {
  55. $messages[$i] = sprintf('<%s>%s</%s>', $style, $messages[$i], $style);
  56. }
  57. return implode("\n", $messages);
  58. }
  59. /**
  60. * Truncates a message to the given length.
  61. *
  62. * @return string
  63. */
  64. public function truncate(string $message, int $length, string $suffix = '...')
  65. {
  66. $computedLength = $length - self::width($suffix);
  67. if ($computedLength > self::width($message)) {
  68. return $message;
  69. }
  70. return self::substr($message, 0, $length).$suffix;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function getName()
  76. {
  77. return 'formatter';
  78. }
  79. }