diff --git a/bin/view-json b/bin/view-json index 6af6b94..c0de117 100755 --- a/bin/view-json +++ b/bin/view-json @@ -50,6 +50,38 @@ $command = (new SingleCommandApplication()) ); } catch (FileHandlerException) { $io->error('invalid json file'); + $io->writeln( + ' + Expected Format + ======================================= + + [ + + { + "title": "The Catcher in the Rye", + "author": "J.D. Salinger", + "published_year": 1951 + }, + { + "title": "To Kill a Mockingbird", + "author": "Harper Lee", + "published_year": 1960 + }, + { + "title": "1984", + "author": "George Orwell", + "published_year": 1949 + } + + ] + + + + + ======================================= + + ' + ); return Command::FAILURE; } diff --git a/src/JsonFileHandler.php b/src/JsonFileHandler.php index f6aaad2..9c2beeb 100644 --- a/src/JsonFileHandler.php +++ b/src/JsonFileHandler.php @@ -50,13 +50,14 @@ private function getRows( throw new FileHandlerException("{$filename} is not valid"); } - $contents = json_decode($jsonContents, true); - if (!$contents || json_last_error() !== JSON_ERROR_NONE) { + + if (!$contents = $this->isValidJson($jsonContents)) { throw new FileHandlerException(json_last_error_msg()); } + $count = 0; - $headers = array_keys(reset($contents)); + $headers = array_keys($contents[0]); $indices = is_array($hideColumns) ? $this->setColumnsToHide($headers, $hideColumns) : []; foreach ($contents as $content) { if (!empty($indices)) { @@ -71,4 +72,38 @@ private function getRows( } } } + + /** + * @param string $jsonData + * @return array>|false + */ + private function isValidJson(string $jsonData): array|false + { + $data = json_decode($jsonData, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + return false; + } + + + if (!is_array($data)) { + return false; + } + + if (!isset($data[0]) || !is_array($data[0])) { + return false; + } + + $firstArrayKeys = array_keys($data[0]); + + foreach ($data as $item) { + $currentArrayKeys = array_keys($item); + + if ($firstArrayKeys !== $currentArrayKeys) { + return false; + } + } + + return $data; + } }