CLI search: add JSON output (with -j|--json parameters)

Futhermore, --pretty parameter also permit to prettify the JSON 
output.
This commit is contained in:
Benjamin Renard 2020-12-22 11:01:38 +01:00
parent 1c13aa7cdd
commit 43d2620f8e

View file

@ -1448,6 +1448,8 @@ class LSsearch extends LSlog_staticLoggerClass {
); );
$page_nb = 1; $page_nb = 1;
$all = false; $all = false;
$json = false;
$pretty = false;
for ($i=0; $i < count($command_args); $i++) { for ($i=0; $i < count($command_args); $i++) {
switch ($command_args[$i]) { switch ($command_args[$i]) {
case '-f': case '-f':
@ -1516,6 +1518,13 @@ class LSsearch extends LSlog_staticLoggerClass {
case '--all': case '--all':
$all = true; $all = true;
break; break;
case '-j':
case '--json':
$json = true;
break;
case '--pretty':
$pretty = true;
break;
default: default:
if (is_null($objType)) { if (is_null($objType)) {
$objType = $command_args[$i]; $objType = $command_args[$i];
@ -1574,6 +1583,37 @@ class LSsearch extends LSlog_staticLoggerClass {
self :: log_fatal("Fail to retreive page #$page_nb."); self :: log_fatal("Fail to retreive page #$page_nb.");
} }
// Handle JSON output
if ($json) {
$export = array(
'objects' => array(),
'total' => $search -> total,
);
if (!$all) {
$export['page'] = $page['nb'] + 1;
$export['nbPages'] = $page['nbPages'];
}
foreach(($all?$entries:$page['list']) as $obj) {
$export['objects'][$obj -> dn] = array(
'name' => $obj -> displayName,
);
if ($search -> displaySubDn)
$export['objects'][$obj -> dn][$search -> label_level] = $obj -> subDn;
if ($search -> extraDisplayedColumns) {
foreach ($search -> visibleExtraDisplayedColumns as $cid => $conf) {
$export['objects'][$obj -> dn][$conf['label']] = $obj -> $cid;
}
}
}
$output = json_encode($export, ($pretty?JSON_PRETTY_PRINT:0));
if ($output === false) {
self :: log_error("Fail to encode data as JSON");
exit(1);
}
echo $output;
exit(0);
}
if (empty($all?$entries:$page['list'])) { if (empty($all?$entries:$page['list'])) {
echo "No $objType object found.\n"; echo "No $objType object found.\n";
exit(0); exit(0);
@ -1643,6 +1683,7 @@ class LSsearch extends LSlog_staticLoggerClass {
'-e', '--extra-columns', '-e', '--extra-columns',
'-p', '--page', '-p', '--page',
'--all', '--all',
'-j', '--json', '--pretty',
); );
// Detect positional args // Detect positional args
@ -1820,6 +1861,8 @@ LScli :: add_command(
' - -e|--extra-columns : Display extra columns', ' - -e|--extra-columns : Display extra columns',
' - -p|--page : page number to show (starting by 1, default: first one)', ' - -p|--page : page number to show (starting by 1, default: first one)',
' - --all : list all matching objects (no pagination)', ' - --all : list all matching objects (no pagination)',
' - -j|--json : JSON output',
' - --pretty : prettify the JSON output',
), ),
true, true,
array('LSsearch', 'cli_search_args_autocompleter') array('LSsearch', 'cli_search_args_autocompleter')