Utility.php 19 KB

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