Utility.php 20 KB

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