Utility.php 20 KB

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