NormalizerFormatter.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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\Formatter;
  11. use Exception;
  12. /**
  13. * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets
  14. *
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. */
  17. class NormalizerFormatter implements FormatterInterface
  18. {
  19. const SIMPLE_DATE = "Y-m-d H:i:s";
  20. protected $dateFormat;
  21. /**
  22. * @param string $dateFormat The format of the timestamp: one supported by DateTime::format
  23. */
  24. public function __construct($dateFormat = null)
  25. {
  26. $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
  27. if (!function_exists('json_encode')) {
  28. throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
  29. }
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function format(array $record)
  35. {
  36. return $this->normalize($record);
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function formatBatch(array $records)
  42. {
  43. foreach ($records as $key => $record) {
  44. $records[$key] = $this->format($record);
  45. }
  46. return $records;
  47. }
  48. protected function normalize($data)
  49. {
  50. if (null === $data || is_scalar($data)) {
  51. if (is_float($data)) {
  52. if (is_infinite($data)) {
  53. return ($data > 0 ? '' : '-') . 'INF';
  54. }
  55. if (is_nan($data)) {
  56. return 'NaN';
  57. }
  58. }
  59. return $data;
  60. }
  61. if (is_array($data)) {
  62. $normalized = array();
  63. $count = 1;
  64. foreach ($data as $key => $value) {
  65. if ($count++ >= 1000) {
  66. $normalized['...'] = 'Over 1000 items ('.count($data).' total), aborting normalization';
  67. break;
  68. }
  69. $normalized[$key] = $this->normalize($value);
  70. }
  71. return $normalized;
  72. }
  73. if ($data instanceof \DateTime) {
  74. return $data->format($this->dateFormat);
  75. }
  76. if (is_object($data)) {
  77. // TODO 2.0 only check for Throwable
  78. if ($data instanceof Exception || (PHP_VERSION_ID > 70000 && $data instanceof \Throwable)) {
  79. return $this->normalizeException($data);
  80. }
  81. // non-serializable objects that implement __toString stringified
  82. if (method_exists($data, '__toString') && !$data instanceof \JsonSerializable) {
  83. $value = $data->__toString();
  84. } else {
  85. // the rest is json-serialized in some way
  86. $value = $this->toJson($data, true);
  87. }
  88. return sprintf("[object] (%s: %s)", get_class($data), $value);
  89. }
  90. if (is_resource($data)) {
  91. return sprintf('[resource] (%s)', get_resource_type($data));
  92. }
  93. return '[unknown('.gettype($data).')]';
  94. }
  95. protected function normalizeException($e)
  96. {
  97. // TODO 2.0 only check for Throwable
  98. if (!$e instanceof Exception && !$e instanceof \Throwable) {
  99. throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e));
  100. }
  101. $data = array(
  102. 'class' => get_class($e),
  103. 'message' => $e->getMessage(),
  104. 'code' => $e->getCode(),
  105. 'file' => $e->getFile().':'.$e->getLine(),
  106. );
  107. if ($e instanceof \SoapFault) {
  108. if (isset($e->faultcode)) {
  109. $data['faultcode'] = $e->faultcode;
  110. }
  111. if (isset($e->faultactor)) {
  112. $data['faultactor'] = $e->faultactor;
  113. }
  114. if (isset($e->detail)) {
  115. $data['detail'] = $e->detail;
  116. }
  117. }
  118. $trace = $e->getTrace();
  119. foreach ($trace as $frame) {
  120. if (isset($frame['file'])) {
  121. $data['trace'][] = $frame['file'].':'.$frame['line'];
  122. } elseif (isset($frame['function']) && $frame['function'] === '{closure}') {
  123. // We should again normalize the frames, because it might contain invalid items
  124. $data['trace'][] = $frame['function'];
  125. } else {
  126. // We should again normalize the frames, because it might contain invalid items
  127. $data['trace'][] = $this->toJson($this->normalize($frame), true);
  128. }
  129. }
  130. if ($previous = $e->getPrevious()) {
  131. $data['previous'] = $this->normalizeException($previous);
  132. }
  133. return $data;
  134. }
  135. /**
  136. * Return the JSON representation of a value
  137. *
  138. * @param mixed $data
  139. * @param bool $ignoreErrors
  140. * @throws \RuntimeException if encoding fails and errors are not ignored
  141. * @return string
  142. */
  143. protected function toJson($data, $ignoreErrors = false)
  144. {
  145. // suppress json_encode errors since it's twitchy with some inputs
  146. if ($ignoreErrors) {
  147. return @$this->jsonEncode($data);
  148. }
  149. $json = $this->jsonEncode($data);
  150. if ($json === false) {
  151. $json = $this->handleJsonError(json_last_error(), $data);
  152. }
  153. return $json;
  154. }
  155. /**
  156. * @param mixed $data
  157. * @return string JSON encoded data or null on failure
  158. */
  159. private function jsonEncode($data)
  160. {
  161. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  162. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  163. }
  164. return json_encode($data);
  165. }
  166. /**
  167. * Handle a json_encode failure.
  168. *
  169. * If the failure is due to invalid string encoding, try to clean the
  170. * input and encode again. If the second encoding attempt fails, the
  171. * inital error is not encoding related or the input can't be cleaned then
  172. * raise a descriptive exception.
  173. *
  174. * @param int $code return code of json_last_error function
  175. * @param mixed $data data that was meant to be encoded
  176. * @throws \RuntimeException if failure can't be corrected
  177. * @return string JSON encoded data after error correction
  178. */
  179. private function handleJsonError($code, $data)
  180. {
  181. if ($code !== JSON_ERROR_UTF8) {
  182. $this->throwEncodeError($code, $data);
  183. }
  184. if (is_string($data)) {
  185. $this->detectAndCleanUtf8($data);
  186. } elseif (is_array($data)) {
  187. array_walk_recursive($data, array($this, 'detectAndCleanUtf8'));
  188. } else {
  189. $this->throwEncodeError($code, $data);
  190. }
  191. $json = $this->jsonEncode($data);
  192. if ($json === false) {
  193. $this->throwEncodeError(json_last_error(), $data);
  194. }
  195. return $json;
  196. }
  197. /**
  198. * Throws an exception according to a given code with a customized message
  199. *
  200. * @param int $code return code of json_last_error function
  201. * @param mixed $data data that was meant to be encoded
  202. * @throws \RuntimeException
  203. */
  204. private function throwEncodeError($code, $data)
  205. {
  206. switch ($code) {
  207. case JSON_ERROR_DEPTH:
  208. $msg = 'Maximum stack depth exceeded';
  209. break;
  210. case JSON_ERROR_STATE_MISMATCH:
  211. $msg = 'Underflow or the modes mismatch';
  212. break;
  213. case JSON_ERROR_CTRL_CHAR:
  214. $msg = 'Unexpected control character found';
  215. break;
  216. case JSON_ERROR_UTF8:
  217. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  218. break;
  219. default:
  220. $msg = 'Unknown error';
  221. }
  222. throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
  223. }
  224. /**
  225. * Detect invalid UTF-8 string characters and convert to valid UTF-8.
  226. *
  227. * Valid UTF-8 input will be left unmodified, but strings containing
  228. * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
  229. * original encoding of ISO-8859-15. This conversion may result in
  230. * incorrect output if the actual encoding was not ISO-8859-15, but it
  231. * will be clean UTF-8 output and will not rely on expensive and fragile
  232. * detection algorithms.
  233. *
  234. * Function converts the input in place in the passed variable so that it
  235. * can be used as a callback for array_walk_recursive.
  236. *
  237. * @param mixed &$data Input to check and convert if needed
  238. * @private
  239. */
  240. public function detectAndCleanUtf8(&$data)
  241. {
  242. if (is_string($data) && !preg_match('//u', $data)) {
  243. $data = preg_replace_callback(
  244. '/[\x80-\xFF]+/',
  245. function ($m) { return utf8_encode($m[0]); },
  246. $data
  247. );
  248. $data = str_replace(
  249. array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'),
  250. array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'),
  251. $data
  252. );
  253. }
  254. }
  255. }