FormatterHelper.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. /**
  12. * The Formatter class provides helpers to format messages.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class FormatterHelper extends Helper
  17. {
  18. /**
  19. * Formats a message within a section.
  20. *
  21. * @param string $section The section name
  22. * @param string $message The message
  23. * @param string $style The style to apply to the section
  24. */
  25. public function formatSection($section, $message, $style = 'info')
  26. {
  27. return sprintf('<%s>[%s]</%s> %s', $style, $section, $style, $message);
  28. }
  29. /**
  30. * Formats a message as a block of text.
  31. *
  32. * @param string|array $messages The message to write in the block
  33. * @param string $style The style to apply to the whole block
  34. * @param Boolean $large Whether to return a large block
  35. *
  36. * @return string The formatter message
  37. */
  38. public function formatBlock($messages, $style, $large = false)
  39. {
  40. $messages = (array) $messages;
  41. $len = 0;
  42. $lines = array();
  43. foreach ($messages as $message) {
  44. $lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
  45. $len = max($this->strlen($message) + ($large ? 4 : 2), $len);
  46. }
  47. $messages = $large ? array(str_repeat(' ', $len)) : array();
  48. foreach ($lines as $line) {
  49. $messages[] = $line.str_repeat(' ', $len - $this->strlen($line));
  50. }
  51. if ($large) {
  52. $messages[] = str_repeat(' ', $len);
  53. }
  54. foreach ($messages as &$message) {
  55. $message = sprintf('<%s>%s</%s>', $style, $message, $style);
  56. }
  57. return implode("\n", $messages);
  58. }
  59. /**
  60. * Returns the length of a string, using mb_strlen if it is available.
  61. *
  62. * @param string $string The string to check its length
  63. *
  64. * @return integer The length of the string
  65. */
  66. private function strlen($string)
  67. {
  68. if (!function_exists('mb_strlen')) {
  69. return strlen($string);
  70. }
  71. if (false === $encoding = mb_detect_encoding($string)) {
  72. return strlen($string);
  73. }
  74. return mb_strlen($string, $encoding);
  75. }
  76. /**
  77. * Returns the helper's canonical name.
  78. *
  79. * @return string The canonical name of the helper
  80. */
  81. public function getName()
  82. {
  83. return 'formatter';
  84. }
  85. }