NormalizerFormatter.php 10 KB

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