FormatterHelper.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Symfony\Component\Console\Helper;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. /**
  12. * The Formatter class provides helpers to format messages.
  13. *
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.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. if (!is_array($messages)) {
  41. $messages = array($messages);
  42. }
  43. $len = 0;
  44. $lines = array();
  45. foreach ($messages as $message) {
  46. $lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
  47. $len = max($this->strlen($message) + ($large ? 4 : 2), $len);
  48. }
  49. $messages = $large ? array(str_repeat(' ', $len)) : array();
  50. foreach ($lines as $line) {
  51. $messages[] = $line.str_repeat(' ', $len - $this->strlen($line));
  52. }
  53. if ($large) {
  54. $messages[] = str_repeat(' ', $len);
  55. }
  56. foreach ($messages as &$message) {
  57. $message = sprintf('<%s>%s</%s>', $style, $message, $style);
  58. }
  59. return implode("\n", $messages);
  60. }
  61. protected function strlen($string)
  62. {
  63. return function_exists('mb_strlen') ? mb_strlen($string) : strlen($string);
  64. }
  65. /**
  66. * Returns the helper's canonical name
  67. */
  68. public function getName()
  69. {
  70. return 'formatter';
  71. }
  72. }