Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Class JsonToArraySyntax
- *
- * @author Yurii Slobodeniuk <silencedis@gmail.com>
- */
- class JsonToArraySyntax
- {
- /**
- * @param string $json A JSON string
- *
- * @return string
- *
- * @throws \Exception An exception with last json error message if failed to decode the json string
- */
- public function convert(string $json): string
- {
- $array = json_decode($json, true);
- if ($array === null && json_last_error()) {
- throw new \Exception(json_last_error_msg());
- }
- return $this->getArraySyntax($array);
- }
- /**
- * @param array $array An array to print
- * @param int $level An internal parameter
- *
- * @return string
- */
- private function getArraySyntax(array $array, int $level = 0): string
- {
- $strParts = [];
- $level++;
- $strParts[] = '[' . PHP_EOL;
- foreach ($array as $key => $value) {
- $strParts[] = str_repeat(' ', 4 * $level);
- if (!is_int($key)) {
- $strParts[] = "'$key' => ";
- }
- if (is_iterable($value)) {
- $strParts[] = $this->getArraySyntax($value, $level);
- $strParts[] = PHP_EOL;
- } elseif (is_numeric($value)) {
- $strParts[] = "$value," . PHP_EOL;
- } else {
- $strParts[] = sprintf("'%s',", addslashes($value)) . PHP_EOL;
- }
- }
- $strParts[] = str_repeat(' ', 4 * ($level - 1)) . ']' . (($level - 1) == 0 ? '' : ',');
- return implode('', $strParts);
- }
- }
Add Comment
Please, Sign In to add comment