Utils.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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;
  14. /**
  15. * @internal
  16. */
  17. public static function getClass($object): string
  18. {
  19. $class = \get_class($object);
  20. return 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).'@anonymous' : $class;
  21. }
  22. public static function substr(string $string, int $start, ?int $length = null)
  23. {
  24. if (extension_loaded('mbstring')) {
  25. return mb_strcut($string, $start, $length);
  26. }
  27. return substr($string, $start, $length);
  28. }
  29. /**
  30. * Makes sure if a relative path is passed in it is turned into an absolute path
  31. *
  32. * @param string $streamUrl stream URL or path without protocol
  33. */
  34. public static function canonicalizePath(string $streamUrl): string
  35. {
  36. $prefix = '';
  37. if ('file://' === substr($streamUrl, 0, 7)) {
  38. $streamUrl = substr($streamUrl, 7);
  39. $prefix = 'file://';
  40. }
  41. // other type of stream, not supported
  42. if (false !== strpos($streamUrl, '://')) {
  43. return $streamUrl;
  44. }
  45. // already absolute
  46. if (substr($streamUrl, 0, 1) === '/' || substr($streamUrl, 1, 1) === ':' || substr($streamUrl, 0, 2) === '\\\\') {
  47. return $prefix.$streamUrl;
  48. }
  49. $streamUrl = getcwd() . '/' . $streamUrl;
  50. return $prefix.$streamUrl;
  51. }
  52. /**
  53. * Return the JSON representation of a value
  54. *
  55. * @param mixed $data
  56. * @param int $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
  57. * @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
  58. * @throws \RuntimeException if encoding fails and errors are not ignored
  59. * @return string when errors are ignored and the encoding fails, "null" is returned which is valid json for null
  60. */
  61. public static function jsonEncode($data, ?int $encodeFlags = null, bool $ignoreErrors = false): string
  62. {
  63. if (null === $encodeFlags) {
  64. $encodeFlags = self::DEFAULT_JSON_FLAGS;
  65. }
  66. if ($ignoreErrors) {
  67. $json = @json_encode($data, $encodeFlags);
  68. if (false === $json) {
  69. return 'null';
  70. }
  71. return $json;
  72. }
  73. $json = json_encode($data, $encodeFlags);
  74. if (false === $json) {
  75. $json = self::handleJsonError(json_last_error(), $data);
  76. }
  77. return $json;
  78. }
  79. /**
  80. * Handle a json_encode failure.
  81. *
  82. * If the failure is due to invalid string encoding, try to clean the
  83. * input and encode again. If the second encoding attempt fails, the
  84. * initial error is not encoding related or the input can't be cleaned then
  85. * raise a descriptive exception.
  86. *
  87. * @param int $code return code of json_last_error function
  88. * @param mixed $data data that was meant to be encoded
  89. * @param int $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION
  90. * @throws \RuntimeException if failure can't be corrected
  91. * @return string JSON encoded data after error correction
  92. */
  93. public static function handleJsonError(int $code, $data, ?int $encodeFlags = null): string
  94. {
  95. if ($code !== JSON_ERROR_UTF8) {
  96. self::throwEncodeError($code, $data);
  97. }
  98. if (is_string($data)) {
  99. self::detectAndCleanUtf8($data);
  100. } elseif (is_array($data)) {
  101. array_walk_recursive($data, array('Monolog\Utils', 'detectAndCleanUtf8'));
  102. } else {
  103. self::throwEncodeError($code, $data);
  104. }
  105. if (null === $encodeFlags) {
  106. $encodeFlags = self::DEFAULT_JSON_FLAGS;
  107. }
  108. $json = json_encode($data, $encodeFlags);
  109. if ($json === false) {
  110. self::throwEncodeError(json_last_error(), $data);
  111. }
  112. return $json;
  113. }
  114. /**
  115. * Throws an exception according to a given code with a customized message
  116. *
  117. * @param int $code return code of json_last_error function
  118. * @param mixed $data data that was meant to be encoded
  119. * @throws \RuntimeException
  120. */
  121. private static function throwEncodeError(int $code, $data)
  122. {
  123. switch ($code) {
  124. case JSON_ERROR_DEPTH:
  125. $msg = 'Maximum stack depth exceeded';
  126. break;
  127. case JSON_ERROR_STATE_MISMATCH:
  128. $msg = 'Underflow or the modes mismatch';
  129. break;
  130. case JSON_ERROR_CTRL_CHAR:
  131. $msg = 'Unexpected control character found';
  132. break;
  133. case JSON_ERROR_UTF8:
  134. $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  135. break;
  136. default:
  137. $msg = 'Unknown error';
  138. }
  139. throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
  140. }
  141. /**
  142. * Detect invalid UTF-8 string characters and convert to valid UTF-8.
  143. *
  144. * Valid UTF-8 input will be left unmodified, but strings containing
  145. * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
  146. * original encoding of ISO-8859-15. This conversion may result in
  147. * incorrect output if the actual encoding was not ISO-8859-15, but it
  148. * will be clean UTF-8 output and will not rely on expensive and fragile
  149. * detection algorithms.
  150. *
  151. * Function converts the input in place in the passed variable so that it
  152. * can be used as a callback for array_walk_recursive.
  153. *
  154. * @param mixed &$data Input to check and convert if needed
  155. */
  156. private static function detectAndCleanUtf8(&$data)
  157. {
  158. if (is_string($data) && !preg_match('//u', $data)) {
  159. $data = preg_replace_callback(
  160. '/[\x80-\xFF]+/',
  161. function ($m) {
  162. return utf8_encode($m[0]);
  163. },
  164. $data
  165. );
  166. $data = str_replace(
  167. ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'],
  168. ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'],
  169. $data
  170. );
  171. }
  172. }
  173. }