vendor/monolog/monolog/src/Monolog/Utils.php line 86

Open in your IDE?
  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;
  11. final class Utils
  12. {
  13. const DEFAULT_JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR;
  14. public static function getClass(object $object): string
  15. {
  16. $class = \get_class($object);
  17. if (false === ($pos = \strpos($class, "@anonymous\0"))) {
  18. return $class;
  19. }
  20. if (false === ($parent = \get_parent_class($class))) {
  21. return \substr($class, 0, $pos + 10);
  22. }
  23. return $parent . '@anonymous';
  24. }
  25. public static function substr(string $string, int $start, ?int $length = null): string
  26. {
  27. if (extension_loaded('mbstring')) {
  28. return mb_strcut($string, $start, $length);
  29. }
  30. return substr($string, $start, (null === $length) ? strlen($string) : $length);
  31. }
  32. /**
  33. * Makes sure if a relative path is passed in it is turned into an absolute path
  34. *
  35. * @param string $streamUrl stream URL or path without protocol
  36. */
  37. public static function canonicalizePath(string $streamUrl): string
  38. {
  39. $prefix = '';
  40. if ('file://' === substr($streamUrl, 0, 7)) {
  41. $streamUrl = substr($streamUrl, 7);
  42. $prefix = 'file://';
  43. }
  44. // other type of stream, not supported
  45. if (false !== strpos($streamUrl, '://')) {
  46. return $streamUrl;
  47. }
  48. // already absolute
  49. if (substr($streamUrl, 0, 1) === '/' || substr($streamUrl, 1, 1) === ':' || substr($streamUrl, 0, 2) === '\\\\') {
  50. return $prefix.$streamUrl;
  51. }
  52. $streamUrl = getcwd() . '/' . $streamUrl;
  53. return $prefix.$streamUrl;
  54. }
  55. /**
  56. * Return the JSON representation of a value
  57. *
  58. * @param mixed $data
  59. * @param int $encodeFlags flags to pass to json encode, defaults to DEFAULT_JSON_FLAGS
  60. * @param bool $ignoreErrors whether to ignore encoding errors or to throw on error, when ignored and the encoding fails, "null" is returned which is valid json for null
  61. * @throws \RuntimeException if encoding fails and errors are not ignored
  62. * @return string when errors are ignored and the encoding fails, "null" is returned which is valid json for null
  63. */
  64. public static function jsonEncode($data, ?int $encodeFlags = null, bool $ignoreErrors = false): string
  65. {
  66. if (null === $encodeFlags) {
  67. $encodeFlags = self::DEFAULT_JSON_FLAGS;
  68. }
  69. if ($ignoreErrors) {
  70. $json = @json_encode($data, $encodeFlags);
  71. if (false === $json) {
  72. return 'null';
  73. }
  74. return $json;
  75. }
  76. $json = json_encode($data, $encodeFlags);
  77. if (false === $json) {
  78. $json = self::handleJsonError(json_last_error(), $data);
  79. }
  80. return $json;
  81. }
  82. /**
  83. * Handle a json_encode failure.
  84. *
  85. * If the failure is due to invalid string encoding, try to clean the
  86. * input and encode again. If the second encoding attempt fails, the
  87. * initial error is not encoding related or the input can't be cleaned then
  88. * raise a descriptive exception.
  89. *
  90. * @param int $code return code of json_last_error function
  91. * @param mixed $data data that was meant to be encoded
  92. * @param int $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION
  93. * @throws \RuntimeException if failure can't be corrected
  94. * @return string JSON encoded data after error correction
  95. */
  96. public static function handleJsonError(int $code, $data, ?int $encodeFlags = null): string
  97. {
  98. if ($code !== JSON_ERROR_UTF8) {
  99. self::throwEncodeError($code, $data);
  100. }
  101. if (is_string($data)) {
  102. self::detectAndCleanUtf8($data);
  103. } elseif (is_array($data)) {
  104. array_walk_recursive($data, array('Monolog\Utils', 'detectAndCleanUtf8'));
  105. } else {
  106. self::throwEncodeError($code, $data);
  107. }
  108. if (null === $encodeFlags) {
  109. $encodeFlags = self::DEFAULT_JSON_FLAGS;
  110. }
  111. $json = json_encode($data, $encodeFlags);
  112. if ($json === false) {
  113. self::throwEncodeError(json_last_error(), $data);
  114. }
  115. return $json;
  116. }
  117. /**
  118. * @internal
  119. */
  120. public static function pcreLastErrorMessage(int $code): string
  121. {
  122. if (PHP_VERSION_ID >= 80000) {
  123. return preg_last_error_msg();
  124. }
  125. $constants = (get_defined_constants(true))['pcre'];
  126. $constants = array_filter($constants, function ($key) {
  127. return substr($key, -6) == '_ERROR';
  128. }, ARRAY_FILTER_USE_KEY);
  129. $constants = array_flip($constants);
  130. return $constants[$code] ?? 'UNDEFINED_ERROR';
  131. }
  132. /**
  133. * Throws an exception according to a given code with a customized message
  134. *
  135. * @param int $code return code of json_last_error function
  136. * @param mixed $data data that was meant to be encoded
  137. * @throws \RuntimeException
  138. *
  139. * @return never
  140. */
  141. private static function throwEncodeError(int $code, $data): void
  142. {
  143. switch ($code) {
  144. case JSON_ERROR_DEPTH:
  145. $msg = 'Maximum stack depth exceeded';
  146. break;
  147. case JSON_ERROR_STATE_MISMATCH:
  148. $msg = 'Underflow or the modes mismatch';
  149. break;
  150. case JSON_ERROR_CTRL_CHAR:
  151. $msg = 'Unexpected control character found';
  152. break;
  153. case JSON_ERROR_UTF8:
  154. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  155. break;
  156. default:
  157. $msg = 'Unknown error';
  158. }
  159. throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
  160. }
  161. /**
  162. * Detect invalid UTF-8 string characters and convert to valid UTF-8.
  163. *
  164. * Valid UTF-8 input will be left unmodified, but strings containing
  165. * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
  166. * original encoding of ISO-8859-15. This conversion may result in
  167. * incorrect output if the actual encoding was not ISO-8859-15, but it
  168. * will be clean UTF-8 output and will not rely on expensive and fragile
  169. * detection algorithms.
  170. *
  171. * Function converts the input in place in the passed variable so that it
  172. * can be used as a callback for array_walk_recursive.
  173. *
  174. * @param mixed $data Input to check and convert if needed, passed by ref
  175. */
  176. private static function detectAndCleanUtf8(&$data): void
  177. {
  178. if (is_string($data) && !preg_match('//u', $data)) {
  179. $data = preg_replace_callback(
  180. '/[\x80-\xFF]+/',
  181. function ($m) {
  182. return function_exists('mb_convert_encoding') ? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1') : utf8_encode($m[0]);
  183. },
  184. $data
  185. );
  186. if (!is_string($data)) {
  187. $pcreErrorCode = preg_last_error();
  188. throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode));
  189. }
  190. $data = str_replace(
  191. ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'],
  192. ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'],
  193. $data
  194. );
  195. }
  196. }
  197. /**
  198. * Converts a string with a valid 'memory_limit' format, to bytes.
  199. *
  200. * @param string|false $val
  201. * @return int|false Returns an integer representing bytes. Returns FALSE in case of error.
  202. */
  203. public static function expandIniShorthandBytes($val)
  204. {
  205. if (!is_string($val)) {
  206. return false;
  207. }
  208. // support -1
  209. if ((int) $val < 0) {
  210. return (int) $val;
  211. }
  212. if (!preg_match('/^\s*(?<val>\d+)(?:\.\d+)?\s*(?<unit>[gmk]?)\s*$/i', $val, $match)) {
  213. return false;
  214. }
  215. $val = (int) $match['val'];
  216. switch (strtolower($match['unit'])) {
  217. case 'g':
  218. $val *= 1024;
  219. case 'm':
  220. $val *= 1024;
  221. case 'k':
  222. $val *= 1024;
  223. }
  224. return $val;
  225. }
  226. /**
  227. * @param array<mixed> $record
  228. */
  229. public static function getRecordMessageForException(array $record): string
  230. {
  231. $context = '';
  232. $extra = '';
  233. try {
  234. if ($record['context']) {
  235. $context = "\nContext: " . json_encode($record['context']);
  236. }
  237. if ($record['extra']) {
  238. $extra = "\nExtra: " . json_encode($record['extra']);
  239. }
  240. } catch (\Throwable $e) {
  241. // noop
  242. }
  243. return "\nThe exception occurred while attempting to log: " . $record['message'] . $context . $extra;
  244. }
  245. }