Formatter.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Symfony\Components\Console\Output;
  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. * @package symfony
  15. * @subpackage console
  16. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  17. */
  18. class Formatter
  19. {
  20. /**
  21. * Formats a message within a section.
  22. *
  23. * @param string $section The section name
  24. * @param string $message The message
  25. * @param string $style The style to apply to the section
  26. */
  27. static public function formatSection($section, $message, $style = 'info')
  28. {
  29. return sprintf("<%s>[%s]</%s> %s", $style, $section, $style, $message);
  30. }
  31. /**
  32. * Formats a message as a block of text.
  33. *
  34. * @param string|array $messages The message to write in the block
  35. * @param string $style The style to apply to the whole block
  36. * @param Boolean $large Whether to return a large block
  37. *
  38. * @return string The formatter message
  39. */
  40. static public function formatBlock($messages, $style, $large = false)
  41. {
  42. if (!is_array($messages))
  43. {
  44. $messages = array($messages);
  45. }
  46. $len = 0;
  47. $lines = array();
  48. foreach ($messages as $message)
  49. {
  50. $lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
  51. $len = max(static::strlen($message) + ($large ? 4 : 2), $len);
  52. }
  53. $messages = $large ? array(str_repeat(' ', $len)) : array();
  54. foreach ($lines as $line)
  55. {
  56. $messages[] = $line.str_repeat(' ', $len - static::strlen($line));
  57. }
  58. if ($large)
  59. {
  60. $messages[] = str_repeat(' ', $len);
  61. }
  62. foreach ($messages as &$message)
  63. {
  64. $message = sprintf('<%s>%s</%s>', $style, $message, $style);
  65. }
  66. return implode("\n", $messages);
  67. }
  68. static protected function strlen($string)
  69. {
  70. return function_exists('mb_strlen') ? mb_strlen($string) : strlen($string);
  71. }
  72. }