FormatterHelper.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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, uses 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. return function_exists('mb_strlen') ? mb_strlen($string, mb_detect_encoding($string)) : strlen($string);
  69. }
  70. /**
  71. * Returns the helper's canonical name
  72. *
  73. * @return string The canonical name of the helper
  74. */
  75. public function getName()
  76. {
  77. return 'formatter';
  78. }
  79. }