|
| 1 | +<?php |
| 2 | + |
| 3 | +/* Icinga Reporting | (c) 2023 Icinga GmbH | GPLv2 */ |
| 4 | + |
| 5 | +namespace Icinga\Module\Reporting\Clicommands; |
| 6 | + |
| 7 | +use InvalidArgumentException; |
| 8 | +use Icinga\Module\Pdfexport\ProvidedHook\Pdfexport; |
| 9 | +use Icinga\Module\Reporting\Cli\Command; |
| 10 | +use Icinga\Module\Reporting\Report; |
| 11 | + |
| 12 | +class DownloadCommand extends Command |
| 13 | +{ |
| 14 | + /** |
| 15 | + * Download report with specified ID as PDF, CSV or JSON |
| 16 | + * |
| 17 | + * USAGE |
| 18 | + * |
| 19 | + * icingacli reporting download <id> [--format=<pdf|csv|json>] |
| 20 | + * |
| 21 | + * OPTIONS |
| 22 | + * |
| 23 | + * --format=<pdf|csv|json> |
| 24 | + * Download report as PDF, CSV or JSON. Defaults to pdf. |
| 25 | + * |
| 26 | + * --output=<file> |
| 27 | + * Save report to the specified <file>. |
| 28 | + * |
| 29 | + * EXAMPLES |
| 30 | + * |
| 31 | + * Download report with ID 1: |
| 32 | + * icingacli reporting download 1 |
| 33 | + * |
| 34 | + * Download report with ID 1 as CSV: |
| 35 | + * icingacli reporting download 1 --format=csv |
| 36 | + * |
| 37 | + * Download report with ID 1 as JSON to the specified file: |
| 38 | + * icingacli reporting download 1 --format=json --output=sla.json |
| 39 | + */ |
| 40 | + public function defaultAction() |
| 41 | + { |
| 42 | + $id = $this->params->getStandalone(); |
| 43 | + if ($id === null) { |
| 44 | + $this->fail($this->translate('Argument id is mandatory')); |
| 45 | + } |
| 46 | + |
| 47 | + $report = Report::fromDb($id); |
| 48 | + $format = strtolower($this->params->get('format', 'pdf')); |
| 49 | + switch ($format) { |
| 50 | + case 'pdf': |
| 51 | + $content = Pdfexport::first()->htmlToPdf($report->toPdf()); |
| 52 | + break; |
| 53 | + case 'csv': |
| 54 | + $content = $report->toCsv(); |
| 55 | + break; |
| 56 | + case 'json': |
| 57 | + $content = $report->toJson(); |
| 58 | + break; |
| 59 | + default: |
| 60 | + throw new InvalidArgumentException(sprintf('Format %s is not supported', $format)); |
| 61 | + } |
| 62 | + |
| 63 | + $output = $this->params->get('output'); |
| 64 | + if ($output === null) { |
| 65 | + $name = sprintf( |
| 66 | + '%s (%s) %s', |
| 67 | + $report->getName(), |
| 68 | + $report->getTimeframe()->getName(), |
| 69 | + date('Y-m-d H:i') |
| 70 | + ); |
| 71 | + |
| 72 | + $output = "$name.$format"; |
| 73 | + } elseif (is_dir($output)) { |
| 74 | + $this->fail($this->translate(sprintf('%s is a directory', $output))); |
| 75 | + } |
| 76 | + |
| 77 | + file_put_contents($output, $content); |
| 78 | + echo "$output\n"; |
| 79 | + } |
| 80 | +} |
0 commit comments