HtmlOutputFormatter.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. return preg_replace_callback("{\033\[([0-9;]+)m(.*?)\033\[0m}s", array($this, 'formatHtml'), $formatted);
  56. }
  57. private function formatHtml($matches)
  58. {
  59. $out = '<span style="';
  60. foreach (explode(';', $matches[1]) as $code) {
  61. if (isset(self::$availableForegroundColors[$code])) {
  62. $out .= 'color:'.self::$availableForegroundColors[$code].';';
  63. } elseif (isset(self::$availableBackgroundColors[$code])) {
  64. $out .= 'background-color:'.self::$availableBackgroundColors[$code].';';
  65. } elseif (isset(self::$availableOptions[$code])) {
  66. switch (self::$availableOptions[$code]) {
  67. case 'bold':
  68. $out .= 'font-weight:bold;';
  69. break;
  70. case 'underscore':
  71. $out .= 'text-decoration:underline;';
  72. break;
  73. }
  74. }
  75. }
  76. return $out . '">'.$matches[2].'</span>';
  77. }
  78. }