PageRenderTime 81ms CodeModel.GetById 45ms RepoModel.GetById 2ms app.codeStats 0ms

/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php

https://gitlab.com/ealexis.t/trends
PHP | 230 lines | 146 code | 29 blank | 55 comment | 17 complexity | 19d5ce60855f39471630cafe255ee938 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Monolog\Formatter\LineFormatter;
  12. /**
  13. * Handler sending logs to browser's javascript console with no browser extension required
  14. *
  15. * @author Olivier Poitrey <rs@dailymotion.com>
  16. */
  17. class BrowserConsoleHandler extends AbstractProcessingHandler
  18. {
  19. protected static $initialized = false;
  20. protected static $records = array();
  21. /**
  22. * {@inheritDoc}
  23. *
  24. * Formatted output may contain some formatting markers to be transferred to `console.log` using the %c format.
  25. *
  26. * Example of formatted string:
  27. *
  28. * You can do [[blue text]]{color: blue} or [[green background]]{background-color: green; color: white}
  29. */
  30. protected function getDefaultFormatter()
  31. {
  32. return new LineFormatter('[[%channel%]]{macro: autolabel} [[%level_name%]]{font-weight: bold} %message%');
  33. }
  34. /**
  35. * {@inheritDoc}
  36. */
  37. protected function write(array $record)
  38. {
  39. // Accumulate records
  40. self::$records[] = $record;
  41. // Register shutdown handler if not already done
  42. if (!self::$initialized) {
  43. self::$initialized = true;
  44. $this->registerShutdownFunction();
  45. }
  46. }
  47. /**
  48. * Convert records to javascript console commands and send it to the browser.
  49. * This method is automatically called on PHP shutdown if output is HTML or Javascript.
  50. */
  51. public static function send()
  52. {
  53. $format = self::getResponseFormat();
  54. if ($format === 'unknown') {
  55. return;
  56. }
  57. if (count(self::$records)) {
  58. if ($format === 'html') {
  59. self::writeOutput('<script>' . self::generateScript() . '</script>');
  60. } elseif ($format === 'js') {
  61. self::writeOutput(self::generateScript());
  62. }
  63. self::reset();
  64. }
  65. }
  66. /**
  67. * Forget all logged records
  68. */
  69. public static function reset()
  70. {
  71. self::$records = array();
  72. }
  73. /**
  74. * Wrapper for register_shutdown_function to allow overriding
  75. */
  76. protected function registerShutdownFunction()
  77. {
  78. if (PHP_SAPI !== 'cli') {
  79. register_shutdown_function(array('Monolog\Handler\BrowserConsoleHandler', 'send'));
  80. }
  81. }
  82. /**
  83. * Wrapper for echo to allow overriding
  84. *
  85. * @param string $str
  86. */
  87. protected static function writeOutput($str)
  88. {
  89. echo $str;
  90. }
  91. /**
  92. * Checks the format of the response
  93. *
  94. * If Content-Type is set to application/javascript or text/javascript -> js
  95. * If Content-Type is set to text/html, or is unset -> html
  96. * If Content-Type is anything else -> unknown
  97. *
  98. * @return string One of 'js', 'html' or 'unknown'
  99. */
  100. protected static function getResponseFormat()
  101. {
  102. // Check content type
  103. foreach (headers_list() as $header) {
  104. if (stripos($header, 'content-type:') === 0) {
  105. // This handler only works with HTML and javascript outputs
  106. // text/javascript is obsolete in favour of application/javascript, but still used
  107. if (stripos($header, 'application/javascript') !== false || stripos($header, 'text/javascript') !== false) {
  108. return 'js';
  109. }
  110. if (stripos($header, 'text/html') === false) {
  111. return 'unknown';
  112. }
  113. break;
  114. }
  115. }
  116. return 'html';
  117. }
  118. private static function generateScript()
  119. {
  120. $script = array();
  121. foreach (self::$records as $record) {
  122. $context = self::dump('Context', $record['context']);
  123. $extra = self::dump('Extra', $record['extra']);
  124. if (empty($context) && empty($extra)) {
  125. $script[] = self::call_array('log', self::handleStyles($record['formatted']));
  126. } else {
  127. $script = array_merge($script,
  128. array(self::call_array('groupCollapsed', self::handleStyles($record['formatted']))),
  129. $context,
  130. $extra,
  131. array(self::call('groupEnd'))
  132. );
  133. }
  134. }
  135. return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);";
  136. }
  137. private static function handleStyles($formatted)
  138. {
  139. $args = array(self::quote('font-weight: normal'));
  140. $format = '%c' . $formatted;
  141. preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  142. foreach (array_reverse($matches) as $match) {
  143. $args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0]));
  144. $args[] = '"font-weight: normal"';
  145. $pos = $match[0][1];
  146. $format = substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . substr($format, $pos + strlen($match[0][0]));
  147. }
  148. array_unshift($args, self::quote($format));
  149. return $args;
  150. }
  151. private static function handleCustomStyles($style, $string)
  152. {
  153. static $colors = array('blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey');
  154. static $labels = array();
  155. return preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function ($m) use ($string, &$colors, &$labels) {
  156. if (trim($m[1]) === 'autolabel') {
  157. // Format the string as a label with consistent auto assigned background color
  158. if (!isset($labels[$string])) {
  159. $labels[$string] = $colors[count($labels) % count($colors)];
  160. }
  161. $color = $labels[$string];
  162. return "background-color: $color; color: white; border-radius: 3px; padding: 0 2px 0 2px";
  163. }
  164. return $m[1];
  165. }, $style);
  166. }
  167. private static function dump($title, array $dict)
  168. {
  169. $script = array();
  170. $dict = array_filter($dict);
  171. if (empty($dict)) {
  172. return $script;
  173. }
  174. $script[] = self::call('log', self::quote('%c%s'), self::quote('font-weight: bold'), self::quote($title));
  175. foreach ($dict as $key => $value) {
  176. $value = json_encode($value);
  177. if (empty($value)) {
  178. $value = self::quote('');
  179. }
  180. $script[] = self::call('log', self::quote('%s: %o'), self::quote($key), $value);
  181. }
  182. return $script;
  183. }
  184. private static function quote($arg)
  185. {
  186. return '"' . addcslashes($arg, "\"\n\\") . '"';
  187. }
  188. private static function call()
  189. {
  190. $args = func_get_args();
  191. $method = array_shift($args);
  192. return self::call_array($method, $args);
  193. }
  194. private static function call_array($method, array $args)
  195. {
  196. return 'c.' . $method . '(' . implode(', ', $args) . ');';
  197. }
  198. }