HtmlOutputFormatter.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Console;
  12. use Symfony\Component\Console\Formatter\OutputFormatter;
  13. /**
  14. * @author Jordi Boggiano <j.boggiano@seld.be>
  15. */
  16. class HtmlOutputFormatter extends OutputFormatter
  17. {
  18. private static $availableForegroundColors = array(
  19. 30 => 'black',
  20. 31 => 'red',
  21. 32 => 'green',
  22. 33 => 'yellow',
  23. 34 => 'blue',
  24. 35 => 'magenta',
  25. 36 => 'cyan',
  26. 37 => 'white',
  27. );
  28. private static $availableBackgroundColors = array(
  29. 40 => 'black',
  30. 41 => 'red',
  31. 42 => 'green',
  32. 43 => 'yellow',
  33. 44 => 'blue',
  34. 45 => 'magenta',
  35. 46 => 'cyan',
  36. 47 => 'white',
  37. );
  38. private static $availableOptions = array(
  39. 1 => 'bold',
  40. 4 => 'underscore',
  41. //5 => 'blink',
  42. //7 => 'reverse',
  43. //8 => 'conceal'
  44. );
  45. /**
  46. * @param array $styles Array of "name => FormatterStyle" instances
  47. */
  48. public function __construct(array $styles = array())
  49. {
  50. parent::__construct(true, $styles);
  51. }
  52. public function format($message)
  53. {
  54. $formatted = parent::format($message);
  55. $clearEscapeCodes = '(?:39|49|0|22|24|25|27|28)';
  56. return preg_replace_callback("{\033\[([0-9;]+)m(.*?)\033\[(?:".$clearEscapeCodes.";)*?".$clearEscapeCodes."m}s", array($this, 'formatHtml'), $formatted);
  57. }
  58. private function formatHtml($matches)
  59. {
  60. $out = '<span style="';
  61. foreach (explode(';', $matches[1]) as $code) {
  62. if (isset(self::$availableForegroundColors[$code])) {
  63. $out .= 'color:'.self::$availableForegroundColors[$code].';';
  64. } elseif (isset(self::$availableBackgroundColors[$code])) {
  65. $out .= 'background-color:'.self::$availableBackgroundColors[$code].';';
  66. } elseif (isset(self::$availableOptions[$code])) {
  67. switch (self::$availableOptions[$code]) {
  68. case 'bold':
  69. $out .= 'font-weight:bold;';
  70. break;
  71. case 'underscore':
  72. $out .= 'text-decoration:underline;';
  73. break;
  74. }
  75. }
  76. }
  77. return $out.'">'.$matches[2].'</span>';
  78. }
  79. }