I'm trying to export a PDF and a XML file for every invoice matching my criteria. So far everything is working perfectly, except for one really weird behaviour.
In my Controller's execute function I have a foreach loop iterating over my result from DB like so
foreach($result as $row) {
$this->writeXml($row['document_increment']);
$this->writePdf($row['document_id'], $row['document_increment']);
}
which calls these two functions
public function writeXml($document_increment){
$content = $this->buildXml();
$myfile = fopen('/var/www/magento2/var/folder/_' . $document_increment. '.xml', "w");
fwrite($myfile, $content);
fclose($myfile);
}
public function writePdf($document_id, $document_increment){
$invoice = $this->invoiceRepository->get($document_id);
$pdf = $this->invoicePdfGeneratorService->execute($invoice);
$this->fileFactory->create(
'_' . $document_increment. '.pdf',
$pdf->render(),
\Magento\Framework\App\Filesystem\DirectoryList::VAR_ELO ,
'application/pdf'
);
}
I am fully aware that some of this code is not Magento 2 best practice at all, but this is more of a "can we do it at all?" situation.
Now, I have set up an ajax request to call my Controller manually in order to test it from the backend. When I do that, Magento generates two invoice PDFs and two invoice XML files - and then stops without any error, warning or similar. I have narrowed it down to the writePdf()
function. Removing it results in 5 (LIMIT
in Query) XML files as is intended.
I have already ruled out the usual
- execution time in php.ini
- invalid MySQL result / error in query (since it works fine with XML)
and checked all logs, but there is neither an exception /error / something nor some config that I deemed responsible.
I think this is really weird since it breaks after the second loop. Does anyone have an idea what could cause this? I'm really thankful for every hint.
EDIT
I changed the triggering action from an ajax call to a cron job. Things get even weirder: now it works, the cron saves all PDF and XML files. Can someone explain to me / does someone have any idea why?