FormatterHelper.php 2.2 KB

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