Utility.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. <?php
  2. namespace Tools\Utility;
  3. use Cake\Routing\Router;
  4. use Cake\Utility\Hash;
  5. use RuntimeException;
  6. /**
  7. * Main class for all app-wide utility methods
  8. *
  9. * @author Mark Scherer
  10. * @license MIT
  11. */
  12. class Utility {
  13. /**
  14. * More sane !empty() check for actual (form) data input.
  15. * It allows only empty string `''`, bool `false` or `null` to be failing the check.
  16. *
  17. * @param mixed $value
  18. * @return bool
  19. */
  20. public static function notBlank($value) {
  21. return $value === 0 || $value === 0.0 || $value === '0' || !empty($value);
  22. }
  23. /**
  24. * More sane !empty() method to not false positive `'0'` (0 as string) as empty.
  25. *
  26. * @deprecated Use notBlank() instead as it correctly handles also numeric input (int/float).
  27. *
  28. * @param mixed $value
  29. * @return bool
  30. */
  31. public static function notEmpty($value) {
  32. return !empty($value) || $value === '0';
  33. }
  34. /**
  35. * Clean implementation of inArray to avoid false positives.
  36. *
  37. * in_array itself has some PHP flaws regarding cross-type comparison:
  38. * - in_array('50x', array(40, 50, 60)) would be true!
  39. * - in_array(50, array('40x', '50x', '60x')) would be true!
  40. *
  41. * @param mixed $needle
  42. * @param array $haystack
  43. * @return bool Success
  44. */
  45. public static function inArray($needle, $haystack) {
  46. $strict = !is_numeric($needle);
  47. return in_array((string)$needle, $haystack, $strict);
  48. }
  49. /**
  50. * Tokenizes a string using $separator.
  51. *
  52. * Options
  53. * - clean: true/false (defaults to true and removes empty tokens and whitespace)
  54. *
  55. * @param string $data The data to tokenize
  56. * @param string $separator The token to split the data on.
  57. * @param array $options
  58. * @return array
  59. */
  60. public static function tokenize($data, $separator = ',', $options = []) {
  61. $defaults = [
  62. 'clean' => true
  63. ];
  64. $options += $defaults;
  65. if (empty($data)) {
  66. return [];
  67. }
  68. $tokens = explode($separator, $data);
  69. if (empty($tokens) || !$options['clean']) {
  70. return $tokens;
  71. }
  72. $tokens = array_map('trim', $tokens);
  73. foreach ($tokens as $key => $token) {
  74. if ($token === '') {
  75. unset($tokens[$key]);
  76. }
  77. }
  78. return $tokens;
  79. }
  80. /**
  81. * Multibyte analogue of preg_match_all() function. Only that this returns the result.
  82. * By default this works properly with UTF8 strings.
  83. *
  84. * Do not forget to use preg_quote() first on strings that could potentially contain
  85. * unescaped characters.
  86. *
  87. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  88. *
  89. * Example: /some(.*)pattern/u
  90. *
  91. * @param string $pattern The pattern to use.
  92. * @param string $subject The string to match.
  93. * @param int $flags
  94. * @param int|null $offset
  95. * @return array Result
  96. */
  97. public static function pregMatchAll($pattern, $subject, $flags = PREG_SET_ORDER, $offset = null) {
  98. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  99. preg_match_all($pattern, $subject, $matches, $flags, $offset);
  100. return $matches;
  101. }
  102. /**
  103. * Multibyte analogue of preg_match() function. Only that this returns the result.
  104. * By default this works properly with UTF8 strings.
  105. *
  106. * Do not forget to use preg_quote() first on strings that could potentially contain
  107. * unescaped characters.
  108. *
  109. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  110. *
  111. * Example: /some(.*)pattern/u
  112. *
  113. * @param string $pattern The pattern to use.
  114. * @param string $subject The string to match.
  115. * @param int|null $flags
  116. * @param int|null $offset
  117. * @return array Result
  118. */
  119. public static function pregMatch($pattern, $subject, $flags = null, $offset = null) {
  120. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  121. preg_match($pattern, $subject, $matches, $flags, $offset);
  122. return $matches;
  123. }
  124. /**
  125. * Multibyte analogue of str_split() function.
  126. * By default this works properly with UTF8 strings.
  127. *
  128. * @param string $str
  129. * @param int $length
  130. * @return array Result
  131. */
  132. public static function strSplit($str, $length = 1) {
  133. if ($length < 1) {
  134. return [];
  135. }
  136. $result = [];
  137. $c = mb_strlen($str);
  138. for ($i = 0; $i < $c; $i += $length) {
  139. $result[] = mb_substr($str, $i, $length);
  140. }
  141. return $result;
  142. }
  143. /**
  144. * Get the current IP address.
  145. *
  146. * @param bool $safe
  147. * @return string IP address
  148. */
  149. public static function getClientIp($safe = true) {
  150. if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
  151. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  152. } elseif (!$safe && env('HTTP_CLIENT_IP')) {
  153. $ipaddr = env('HTTP_CLIENT_IP');
  154. } else {
  155. $ipaddr = env('REMOTE_ADDR');
  156. }
  157. return trim($ipaddr);
  158. }
  159. /**
  160. * Get the current referrer if available.
  161. *
  162. * @param bool $full (defaults to false and leaves the url untouched)
  163. * @return string referer (local or foreign)
  164. */
  165. public static function getReferer($full = false) {
  166. $ref = env('HTTP_REFERER');
  167. $forwarded = env('HTTP_X_FORWARDED_HOST');
  168. if ($forwarded) {
  169. $ref = $forwarded;
  170. }
  171. if (empty($ref)) {
  172. return $ref;
  173. }
  174. if ($full) {
  175. $ref = Router::url($ref, $full);
  176. }
  177. return $ref;
  178. }
  179. /**
  180. * Remove unnessary stuff + add http:// for external urls
  181. * TODO: protocol to lower!
  182. *
  183. * @param string $url
  184. * @param bool $headerRedirect
  185. * @return string Cleaned Url
  186. */
  187. public static function cleanUrl($url, $headerRedirect = false) {
  188. if ($url === '' || $url === 'http://' || $url === 'http://www' || $url === 'http://www.') {
  189. $url = '';
  190. } else {
  191. $url = static::autoPrefixUrl($url, 'http://');
  192. }
  193. if ($headerRedirect && !empty($url)) {
  194. $headers = static::getHeaderFromUrl($url);
  195. if ($headers !== false) {
  196. $headerString = implode("\n", $headers);
  197. if ((bool)preg_match('#^HTTP/.*\s+[(301)]+\s#i', $headerString)) {
  198. foreach ($headers as $header) {
  199. if (mb_strpos($header, 'Location:') === 0) {
  200. $url = trim(hDec(mb_substr($header, 9))); // rawurldecode/urldecode ?
  201. }
  202. }
  203. }
  204. }
  205. }
  206. $length = mb_strlen($url);
  207. while (!empty($url) && mb_strrpos($url, '/') === $length - 1) {
  208. $url = mb_substr($url, 0, $length - 1);
  209. $length--;
  210. }
  211. return $url;
  212. }
  213. /**
  214. * Removes http:// or other protocols from the link.
  215. *
  216. * @param string $url
  217. * @param array $protocols Defaults to http and https. Pass empty array for all.
  218. * @return string strippedUrl
  219. */
  220. public static function stripProtocol($url, $protocols = ['http', 'https']) {
  221. $pieces = parse_url($url);
  222. // Already stripped?
  223. if (empty($pieces['scheme'])) {
  224. return $url;
  225. }
  226. if ($protocols && !in_array($pieces['scheme'], $protocols)) {
  227. return $url;
  228. }
  229. return mb_substr($url, mb_strlen($pieces['scheme']) + 3);
  230. }
  231. /**
  232. * A more robust wrapper around for file_exists() which easily
  233. * fails to return true for existent remote files.
  234. * Per default it allows http/https images to be looked up via urlExists()
  235. * for a better result.
  236. *
  237. * @param string $file File
  238. * @param string $pattern
  239. * @return bool Success
  240. */
  241. public static function fileExists($file, $pattern = '~^https?://~i') {
  242. if (!preg_match($pattern, $file)) {
  243. return file_exists($file);
  244. }
  245. return static::urlExists($file);
  246. }
  247. /**
  248. * file_exists() does not always work with URLs.
  249. * So if you check on strpos(http) === 0 you can use this
  250. * to check for URLs instead.
  251. *
  252. * @param string $url Absolute URL
  253. * @return bool Success
  254. */
  255. public static function urlExists($url) {
  256. // @codingStandardsIgnoreStart
  257. $headers = @get_headers($url);
  258. // @codingStandardsIgnoreEnd
  259. if ($headers && preg_match('|\b200\b|', $headers[0])) {
  260. return true;
  261. }
  262. return false;
  263. }
  264. /**
  265. * Parse headers from a specific URL content.
  266. *
  267. * @param string $url
  268. * @return mixed array of headers or FALSE on failure
  269. */
  270. public static function getHeaderFromUrl($url) {
  271. // @codingStandardsIgnoreStart
  272. $url = @parse_url($url);
  273. // @codingStandardsIgnoreEnd
  274. if (empty($url)) {
  275. return false;
  276. }
  277. $url = array_map('trim', $url);
  278. $url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
  279. $path = (isset($url['path'])) ? $url['path'] : '';
  280. if (empty($path)) {
  281. $path = '/';
  282. }
  283. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  284. $defaults = [
  285. 'http' => [
  286. 'header' => "Accept: text/html\r\n" .
  287. "Connection: Close\r\n" .
  288. "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",
  289. ]
  290. ];
  291. stream_context_get_default($defaults);
  292. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  293. $url = "$url[scheme]://$url[host]$url[port]$path";
  294. $headers = get_headers($url);
  295. if (is_array($headers)) {
  296. return $headers;
  297. }
  298. }
  299. return false;
  300. }
  301. /**
  302. * Add protocol prefix if necessary (and possible)
  303. *
  304. * @param string $url
  305. * @param string|null $prefix
  306. * @return string
  307. */
  308. public static function autoPrefixUrl($url, $prefix = null) {
  309. if ($prefix === null) {
  310. $prefix = 'http://';
  311. }
  312. $pos = strpos($url, '.');
  313. if ($pos !== false) {
  314. if (strpos(substr($url, 0, $pos), '//') === false) {
  315. $url = $prefix . $url;
  316. }
  317. }
  318. return $url;
  319. }
  320. /**
  321. * Returns true only if all values are true.
  322. *
  323. * @param array $array
  324. * @return bool Result
  325. */
  326. public static function logicalAnd($array) {
  327. if (empty($array)) {
  328. return false;
  329. }
  330. foreach ($array as $result) {
  331. if (!$result) {
  332. return false;
  333. }
  334. }
  335. return true;
  336. }
  337. /**
  338. * Returns true if at least one value is true.
  339. *
  340. * @param array $array
  341. * @return bool Result
  342. */
  343. public static function logicalOr($array) {
  344. foreach ($array as $result) {
  345. if ($result) {
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. /**
  352. * On non-transaction db connections it will return a deep array of bools instead of bool.
  353. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too.
  354. *
  355. * @param array $array
  356. * @return bool
  357. * @deprecated Not sure this is useful for CakePHP 3.0
  358. */
  359. public static function isValidSaveAll($array) {
  360. if (!$array) {
  361. return false;
  362. }
  363. $ret = true;
  364. foreach ($array as $key => $val) {
  365. if (is_array($val)) {
  366. $ret = $ret & static::logicalAnd($val);
  367. } else {
  368. $ret = $ret & $val;
  369. }
  370. }
  371. return (bool)$ret;
  372. }
  373. /**
  374. * Convenience function for automatic casting in form methods etc.
  375. *
  376. * @param mixed $value
  377. * @param string $type
  378. * @return mixed Safe value for DB query, or NULL if type was not a valid one
  379. */
  380. public static function typeCast($value, $type) {
  381. switch ($type) {
  382. case 'int':
  383. $value = (int)$value;
  384. break;
  385. case 'float':
  386. $value = (float)$value;
  387. break;
  388. case 'double':
  389. $value = (double)$value;
  390. break;
  391. case 'array':
  392. $value = (array)$value;
  393. break;
  394. case 'bool':
  395. $value = (bool)$value;
  396. break;
  397. case 'string':
  398. $value = (string)$value;
  399. break;
  400. default:
  401. return null;
  402. }
  403. return $value;
  404. }
  405. /**
  406. * Trim recursively
  407. *
  408. * @param mixed $value
  409. * @param bool $transformNullToString
  410. * @return mixed
  411. */
  412. public static function trimDeep($value, $transformNullToString = false) {
  413. if (is_array($value)) {
  414. foreach ($value as $k => $v) {
  415. $value[$k] = static::trimDeep($v, $transformNullToString);
  416. }
  417. return $value;
  418. }
  419. if (is_string($value) || is_null($value)) {
  420. return ($value === null && !$transformNullToString) ? $value : trim($value);
  421. }
  422. return $value;
  423. }
  424. /**
  425. * Applies h() recursively
  426. *
  427. * @param string|array $value
  428. * @return array|string
  429. */
  430. public static function specialcharsDeep($value) {
  431. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  432. return $value;
  433. }
  434. /**
  435. * Main deep method
  436. *
  437. * @param string|callable $function Callable or function name.
  438. * @param mixed $value
  439. * @return array|string
  440. */
  441. public static function deep($function, $value) {
  442. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  443. return $value;
  444. }
  445. /**
  446. * Counts the dimensions of an array. If $all is set to false (which is the default) it will
  447. * only consider the dimension of the first element in the array.
  448. *
  449. * @param array $array Array to count dimensions on
  450. * @param bool $all Set to true to count the dimension considering all elements in array
  451. * @param int $count Start the dimension count at this number
  452. * @return int The number of dimensions in $array
  453. */
  454. public static function countDim($array, $all = false, $count = 0) {
  455. if ($all) {
  456. $depth = [$count];
  457. if (is_array($array) && reset($array) !== false) {
  458. foreach ($array as $value) {
  459. $depth[] = static::countDim($value, true, $count + 1);
  460. }
  461. }
  462. $return = max($depth);
  463. } else {
  464. if (is_array(reset($array))) {
  465. $return = static::countDim(reset($array)) + 1;
  466. } else {
  467. $return = 1;
  468. }
  469. }
  470. return $return;
  471. }
  472. /**
  473. * Expands the values of an array of strings into a deep array.
  474. * Opposite of flattenList().
  475. *
  476. * It needs at least a single separator to be present in all values
  477. * as the key would otherwise be undefined. If data can contain such key-less
  478. * rows, use $undefinedKey to avoid an exception being thrown. But it will
  479. * effectivly collide with other values in that same key then.
  480. *
  481. * So `Some.Deep.Value` becomes `array('Some' => array('Deep' => array('Value')))`.
  482. *
  483. * @param array $data
  484. * @param string $separator
  485. * @param string|null $undefinedKey
  486. * @return array
  487. */
  488. public static function expandList(array $data, $separator = '.', $undefinedKey = null) {
  489. $result = [];
  490. foreach ($data as $value) {
  491. $keys = explode($separator, $value);
  492. $value = array_pop($keys);
  493. $keys = array_reverse($keys);
  494. if (!isset($keys[0])) {
  495. if ($undefinedKey === null) {
  496. throw new RuntimeException('Key-less values are not supported without $undefinedKey.');
  497. }
  498. $keys[0] = $undefinedKey;
  499. }
  500. $child = [$keys[0] => [$value]];
  501. array_shift($keys);
  502. foreach ($keys as $k) {
  503. $child = [
  504. $k => $child
  505. ];
  506. }
  507. $result = Hash::merge($result, $child);
  508. }
  509. return $result;
  510. }
  511. /**
  512. * Flattens a deep array into an array of strings.
  513. * Opposite of expandList().
  514. *
  515. * So `array('Some' => array('Deep' => array('Value')))` becomes `Some.Deep.Value`.
  516. *
  517. * Note that primarily only string should be used.
  518. * However, boolean values are casted to int and thus
  519. * both boolean and integer values also supported.
  520. *
  521. * @param array $data
  522. * @param string $separator
  523. * @return array
  524. */
  525. public static function flattenList(array $data, $separator = '.') {
  526. $result = [];
  527. $stack = [];
  528. $path = null;
  529. reset($data);
  530. while (!empty($data)) {
  531. $key = key($data);
  532. $element = $data[$key];
  533. unset($data[$key]);
  534. if (is_array($element) && !empty($element)) {
  535. if (!empty($data)) {
  536. $stack[] = [$data, $path];
  537. }
  538. $data = $element;
  539. reset($data);
  540. $path .= $key . $separator;
  541. } else {
  542. if (is_bool($element)) {
  543. $element = (int)$element;
  544. }
  545. $result[] = $path . $element;
  546. }
  547. if (empty($data) && !empty($stack)) {
  548. list($data, $path) = array_pop($stack);
  549. reset($data);
  550. }
  551. }
  552. return $result;
  553. }
  554. /**
  555. * Force-flattens an array.
  556. *
  557. * Careful with this method. It can lose information.
  558. * The keys will not be changed, thus possibly overwrite each other.
  559. *
  560. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  561. *
  562. * @param array $array Array to flatten
  563. * @param bool $preserveKeys
  564. * @return array
  565. */
  566. public static function arrayFlatten($array, $preserveKeys = false) {
  567. if ($preserveKeys) {
  568. return static::_arrayFlatten($array);
  569. }
  570. if (!$array) {
  571. return [];
  572. }
  573. $result = [];
  574. foreach ($array as $key => $value) {
  575. if (is_array($value)) {
  576. $result = array_merge($result, static::arrayFlatten($value));
  577. } else {
  578. $result[$key] = $value;
  579. }
  580. }
  581. return $result;
  582. }
  583. /**
  584. * Force-flattens an array and preserves the keys.
  585. *
  586. * Careful with this method. It can lose information.
  587. * The keys will not be changed, thus possibly overwrite each other.
  588. *
  589. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  590. *
  591. * @param array $a
  592. * @param array $f
  593. * @return array
  594. */
  595. protected static function _arrayFlatten($a, $f = []) {
  596. if (!$a) {
  597. return [];
  598. }
  599. foreach ($a as $k => $v) {
  600. if (is_array($v)) {
  601. $f = static::_arrayFlatten($v, $f);
  602. } else {
  603. $f[$k] = $v;
  604. }
  605. }
  606. return $f;
  607. }
  608. /**
  609. * Similar to array_shift but on the keys of the array
  610. * like array_shift() only for keys and not values
  611. *
  612. * @param array $array keyValuePairs
  613. * @return string key
  614. */
  615. public static function arrayShiftKeys(&$array) {
  616. foreach ($array as $key => $value) {
  617. unset($array[$key]);
  618. return $key;
  619. }
  620. }
  621. /**
  622. * @var float
  623. */
  624. protected static $_counterStartTime = 0.0;
  625. /**
  626. * Returns microtime as float value
  627. * (to be subtracted right away)
  628. *
  629. * @param int $precision
  630. * @return float
  631. */
  632. public static function microtime($precision = 8) {
  633. return round(microtime(true), $precision);
  634. }
  635. /**
  636. * @return void
  637. */
  638. public static function startClock() {
  639. static::$_counterStartTime = static::microtime();
  640. }
  641. /**
  642. * @param int $precision
  643. * @param bool $restartClock
  644. * @return float
  645. */
  646. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  647. $startTime = static::$_counterStartTime;
  648. if ($restartClock) {
  649. static::startClock();
  650. }
  651. return static::calcElapsedTime($startTime, static::microtime(), $precision);
  652. }
  653. /**
  654. * Returns microtime as float value
  655. * (to be subtracted right away)
  656. *
  657. * @param int $start
  658. * @param int $end
  659. * @param int $precision
  660. * @return float
  661. */
  662. public static function calcElapsedTime($start, $end, $precision = 8) {
  663. $elapsed = $end - $start;
  664. return round($elapsed, $precision);
  665. }
  666. /**
  667. * Returns pretty JSON
  668. *
  669. * @link https://github.com/ndejong/pretty_json/blob/master/pretty_json.php
  670. * @param string $json The original JSON string
  671. * @param string $indString The string to indent with
  672. * @return string
  673. * @deprecated Now there is a JSON_PRETTY_PRINT option available on json_encode()
  674. */
  675. public static function prettyJson($json, $indString = "\t") {
  676. // Replace any escaped \" marks so we don't get tripped up on quotemarks_counter
  677. $tokens = preg_split('|([\{\}\]\[,])|', str_replace('\"', '~~PRETTY_JSON_QUOTEMARK~~', $json), -1, PREG_SPLIT_DELIM_CAPTURE);
  678. $indent = 0;
  679. $result = '';
  680. $quotemarksCounter = 0;
  681. $nextTokenUsePrefix = true;
  682. foreach ($tokens as $token) {
  683. $quotemarksCounter = $quotemarksCounter + (count(explode('"', $token)) - 1);
  684. if ($token === '') {
  685. continue;
  686. }
  687. if ($nextTokenUsePrefix) {
  688. $prefix = str_repeat($indString, $indent);
  689. } else {
  690. $prefix = null;
  691. }
  692. // Determine if the quote marks are open or closed
  693. if ($quotemarksCounter & 1) {
  694. // odd - thus quotemarks open
  695. $nextTokenUsePrefix = false;
  696. $newLine = null;
  697. } else {
  698. // even - thus quotemarks closed
  699. $nextTokenUsePrefix = true;
  700. $newLine = "\n";
  701. }
  702. if ($token === '{' || $token === '[') {
  703. $indent++;
  704. $result .= $token . $newLine;
  705. } elseif ($token === '}' || $token === ']') {
  706. $indent--;
  707. if ($indent >= 0) {
  708. $prefix = str_repeat($indString, $indent);
  709. }
  710. if ($nextTokenUsePrefix) {
  711. $result .= $newLine . $prefix . $token;
  712. } else {
  713. $result .= $newLine . $token;
  714. }
  715. } elseif ($token === ',') {
  716. $result .= $token . $newLine;
  717. } else {
  718. $result .= $prefix . $token;
  719. }
  720. }
  721. return str_replace('~~PRETTY_JSON_QUOTEMARK~~', '\"', $result);
  722. }
  723. }