PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/foody.blogtamsudev.vn/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php

https://gitlab.com/ntphuc/BackendFeedy
PHP | 280 lines | 165 code | 39 blank | 76 comment | 33 complexity | a69f85e0db4ea6af9ecc2252676a02b9 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\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) || $data instanceof \Traversable) {
  62. $normalized = array();
  63. $count = 1;
  64. foreach ($data as $key => $value) {
  65. if ($count++ >= 1000) {
  66. $normalized['...'] = 'Over 1000 items, 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. $trace = $e->getTrace();
  108. foreach ($trace as $frame) {
  109. if (isset($frame['file'])) {
  110. $data['trace'][] = $frame['file'].':'.$frame['line'];
  111. } else {
  112. // We should again normalize the frames, because it might contain invalid items
  113. $data['trace'][] = $this->toJson($this->normalize($frame), true);
  114. }
  115. }
  116. if ($previous = $e->getPrevious()) {
  117. $data['previous'] = $this->normalizeException($previous);
  118. }
  119. return $data;
  120. }
  121. /**
  122. * Return the JSON representation of a value
  123. *
  124. * @param mixed $data
  125. * @param bool $ignoreErrors
  126. * @throws \RuntimeException if encoding fails and errors are not ignored
  127. * @return string
  128. */
  129. protected function toJson($data, $ignoreErrors = false)
  130. {
  131. // suppress json_encode errors since it's twitchy with some inputs
  132. if ($ignoreErrors) {
  133. return @$this->jsonEncode($data);
  134. }
  135. $json = $this->jsonEncode($data);
  136. if ($json === false) {
  137. $json = $this->handleJsonError(json_last_error(), $data);
  138. }
  139. return $json;
  140. }
  141. /**
  142. * @param mixed $data
  143. * @return string JSON encoded data or null on failure
  144. */
  145. private function jsonEncode($data)
  146. {
  147. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  148. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  149. }
  150. return json_encode($data);
  151. }
  152. /**
  153. * Handle a json_encode failure.
  154. *
  155. * If the failure is due to invalid string encoding, try to clean the
  156. * input and encode again. If the second encoding iattempt fails, the
  157. * inital error is not encoding related or the input can't be cleaned then
  158. * raise a descriptive exception.
  159. *
  160. * @param int $code return code of json_last_error function
  161. * @param mixed $data data that was meant to be encoded
  162. * @throws \RuntimeException if failure can't be corrected
  163. * @return string JSON encoded data after error correction
  164. */
  165. private function handleJsonError($code, $data)
  166. {
  167. if ($code !== JSON_ERROR_UTF8) {
  168. $this->throwEncodeError($code, $data);
  169. }
  170. if (is_string($data)) {
  171. $this->detectAndCleanUtf8($data);
  172. } elseif (is_array($data)) {
  173. array_walk_recursive($data, array($this, 'detectAndCleanUtf8'));
  174. } else {
  175. $this->throwEncodeError($code, $data);
  176. }
  177. $json = $this->jsonEncode($data);
  178. if ($json === false) {
  179. $this->throwEncodeError(json_last_error(), $data);
  180. }
  181. return $json;
  182. }
  183. /**
  184. * Throws an exception according to a given code with a customized message
  185. *
  186. * @param int $code return code of json_last_error function
  187. * @param mixed $data data that was meant to be encoded
  188. * @throws \RuntimeException
  189. */
  190. private function throwEncodeError($code, $data)
  191. {
  192. switch ($code) {
  193. case JSON_ERROR_DEPTH:
  194. $msg = 'Maximum stack depth exceeded';
  195. break;
  196. case JSON_ERROR_STATE_MISMATCH:
  197. $msg = 'Underflow or the modes mismatch';
  198. break;
  199. case JSON_ERROR_CTRL_CHAR:
  200. $msg = 'Unexpected control character found';
  201. break;
  202. case JSON_ERROR_UTF8:
  203. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  204. break;
  205. default:
  206. $msg = 'Unknown error';
  207. }
  208. throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
  209. }
  210. /**
  211. * Detect invalid UTF-8 string characters and convert to valid UTF-8.
  212. *
  213. * Valid UTF-8 input will be left unmodified, but strings containing
  214. * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
  215. * original encoding of ISO-8859-15. This conversion may result in
  216. * incorrect output if the actual encoding was not ISO-8859-15, but it
  217. * will be clean UTF-8 output and will not rely on expensive and fragile
  218. * detection algorithms.
  219. *
  220. * Function converts the input in place in the passed variable so that it
  221. * can be used as a callback for array_walk_recursive.
  222. *
  223. * @param mixed &$data Input to check and convert if needed
  224. * @private
  225. */
  226. public function detectAndCleanUtf8(&$data)
  227. {
  228. if (is_string($data) && !preg_match('//u', $data)) {
  229. $data = preg_replace_callback(
  230. '/[\x80-\xFF]+/',
  231. function ($m) { return utf8_encode($m[0]); },
  232. $data
  233. );
  234. $data = str_replace(
  235. array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'),
  236. array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'),
  237. $data
  238. );
  239. }
  240. }
  241. }