ConsoleHelper.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. <?php
  2. declare(strict_types=1);
  3. namespace Laminas\Stdlib;
  4. use function function_exists;
  5. use function fwrite;
  6. use function getenv;
  7. use function posix_isatty;
  8. use function preg_replace;
  9. use function sprintf;
  10. use function str_replace;
  11. use const DIRECTORY_SEPARATOR;
  12. use const PHP_EOL;
  13. use const STDERR;
  14. use const STDOUT;
  15. /**
  16. * Utilities for console tooling.
  17. *
  18. * Provides the following facilities:
  19. *
  20. * - Colorize strings using markup (e.g., `<info>message</info>`,
  21. * `<error>message</error>`)
  22. * - Write output to a specified stream, optionally with colorization.
  23. * - Write a line of output to a specified stream, optionally with
  24. * colorization, using the system EOL sequence..
  25. * - Write an error message to STDERR.
  26. *
  27. * Colorization will only occur when expected sequences are discovered, and
  28. * then, only if the console terminal allows it.
  29. *
  30. * Essentially, provides the bare minimum to allow you to provide messages to
  31. * the current console.
  32. */
  33. class ConsoleHelper
  34. {
  35. public const COLOR_GREEN = "\033[32m";
  36. public const COLOR_RED = "\033[31m";
  37. public const COLOR_RESET = "\033[0m";
  38. public const HIGHLIGHT_INFO = 'info';
  39. public const HIGHLIGHT_ERROR = 'error';
  40. /** @psalm-var array<ConsoleHelper::HIGHLIGHT_*, ConsoleHelper::COLOR_GREEN|ConsoleHelper::COLOR_RED> */
  41. private array $highlightMap = [
  42. self::HIGHLIGHT_INFO => self::COLOR_GREEN,
  43. self::HIGHLIGHT_ERROR => self::COLOR_RED,
  44. ];
  45. /** @var string Exists only for testing. */
  46. private string $eol = PHP_EOL;
  47. /** @var resource Exists only for testing. */
  48. private $stderr = STDERR;
  49. private bool $supportsColor;
  50. /**
  51. * @param resource $resource
  52. */
  53. public function __construct($resource = STDOUT)
  54. {
  55. $this->supportsColor = $this->detectColorCapabilities($resource);
  56. }
  57. /**
  58. * Colorize a string for use with the terminal.
  59. *
  60. * Takes strings formatted as `<key>string</key>` and formats them per the
  61. * $highlightMap; if color support is disabled, simply removes the formatting
  62. * tags.
  63. *
  64. * @param string $string
  65. * @return string
  66. */
  67. public function colorize($string)
  68. {
  69. $reset = $this->supportsColor ? self::COLOR_RESET : '';
  70. foreach ($this->highlightMap as $key => $color) {
  71. $pattern = sprintf('#<%s>(.*?)</%s>#s', $key, $key);
  72. $color = $this->supportsColor ? $color : '';
  73. $string = preg_replace($pattern, $color . '$1' . $reset, $string);
  74. }
  75. return $string;
  76. }
  77. /**
  78. * @param string $string
  79. * @param bool $colorize Whether or not to colorize the string
  80. * @param resource $resource Defaults to STDOUT
  81. * @return void
  82. */
  83. public function write($string, $colorize = true, $resource = STDOUT)
  84. {
  85. if ($colorize) {
  86. $string = $this->colorize($string);
  87. }
  88. $string = $this->formatNewlines($string);
  89. fwrite($resource, $string);
  90. }
  91. /**
  92. * @param string $string
  93. * @param bool $colorize Whether or not to colorize the line
  94. * @param resource $resource Defaults to STDOUT
  95. * @return void
  96. */
  97. public function writeLine($string, $colorize = true, $resource = STDOUT)
  98. {
  99. $this->write($string . $this->eol, $colorize, $resource);
  100. }
  101. /**
  102. * Emit an error message.
  103. *
  104. * Wraps the message in `<error></error>`, and passes it to `writeLine()`,
  105. * using STDERR as the resource; emits an additional empty line when done,
  106. * also to STDERR.
  107. *
  108. * @param string $message
  109. * @return void
  110. */
  111. public function writeErrorMessage($message)
  112. {
  113. $this->writeLine(sprintf('<error>%s</error>', $message), true, $this->stderr);
  114. $this->writeLine('', false, $this->stderr);
  115. }
  116. /**
  117. * @param resource $resource
  118. * @return bool
  119. */
  120. private function detectColorCapabilities($resource = STDOUT)
  121. {
  122. if ('\\' === DIRECTORY_SEPARATOR) {
  123. // Windows
  124. return false !== getenv('ANSICON')
  125. || 'ON' === getenv('ConEmuANSI')
  126. || 'xterm' === getenv('TERM');
  127. }
  128. return function_exists('posix_isatty') && posix_isatty($resource);
  129. }
  130. /**
  131. * Ensure newlines are appropriate for the current terminal.
  132. *
  133. * @param string $string
  134. * @return string
  135. */
  136. private function formatNewlines($string)
  137. {
  138. $string = str_replace($this->eol, "\0PHP_EOL\0", $string);
  139. $string = preg_replace("/(\r\n|\n|\r)/", $this->eol, $string);
  140. return str_replace("\0PHP_EOL\0", $this->eol, $string);
  141. }
  142. }