Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions bin/view-json
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
41 changes: 38 additions & 3 deletions src/JsonFileHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -71,4 +72,38 @@ private function getRows(
}
}
}

/**
* @param string $jsonData
* @return array<int,array<string,string>>|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;
}
}