+ * @throws \League\Csv\CannotInsertRecord
+ * @throws \CRM_Core_Exception
+ */
+ public static function outputCSV(): void {
+ $userJobID = CRM_Utils_Request::retrieveValue('user_job_id', 'Integer', NULL, TRUE);
+ $status = CRM_Utils_Request::retrieveValue('status', 'String', NULL, TRUE);
+ $saveFileName = CRM_Import_Parser::saveFileName($status);
+
+ $form = new CRM_Import_Forms();
+ $form->controller = new CRM_Core_Controller();
+ $form->set('user_job_id', $userJobID);
+
+ $form->getUserJob();
+ $writer = Writer::createFromFileObject(new SplTempFileObject());
+ $headers = $form->getColumnHeaders();
+ if ($headers) {
+ array_unshift($headers, ts('Reason'));
+ array_unshift($headers, ts('Line Number'));
+ $writer->insertOne($headers);
+ }
+ $writer->addFormatter(['CRM_Import_Forms', 'reorderOutput']);
+ // Note this might be more inefficient that iterating the result
+ // set & doing insertOne - possibly something to explore later.
+ $writer->insertAll($form->getDataRows($status));
+
+ CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
+ CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
+ CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv; charset=UTF-8');
+ $writer->output($saveFileName);
+ CRM_Utils_System::civiExit();
+ }
+
+ /**
+ * When outputting the row as a csv, more the last 2 rows to the start.
+ *
+ * This is because the id and status message fields are at the end. It may make sense
+ * to move them to the start later, when order code cleanup has happened...
+ *
+ * @param array $record
+ */
+ public static function reorderOutput(array $record): array {
+ $rowNumber = array_pop($record);
+ $message = array_pop($record);
+ // Also pop off the status - but we are not going to use this at this stage.
+ array_pop($record);
+ // Related entities
+ array_pop($record);
+ // Entity_id
+ array_pop($record);
+ array_unshift($record, $message);
+ array_unshift($record, $rowNumber);
+ return $record;
+ }
+
+ /**
+ * Get the url to download the relevant csv file.
+ * @param string $status
+ *
+ * @return string