From b3f4d77e003d65617854f9f7ff96c58158921200 Mon Sep 17 00:00:00 2001 From: Jun Pataleta Date: Wed, 19 Jun 2019 15:08:43 +0800 Subject: [PATCH] MDL-65954 dataformat_pdf: Convert object records to array * count() doesn't work quite as expected when the record being written to the PDF is an object. So make sure to convert the record to an array. * In addition, instead of comparing the total vs the current cell counter, it would be more reliable to determine whether we're at the last element of the array by getting the key for the last element and comparing it with the key for the element that's currently being processed. --- dataformat/pdf/classes/writer.php | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/dataformat/pdf/classes/writer.php b/dataformat/pdf/classes/writer.php index 0559c93aebc0e..1f204d83e6174 100644 --- a/dataformat/pdf/classes/writer.php +++ b/dataformat/pdf/classes/writer.php @@ -89,6 +89,11 @@ public function start_sheet($columns) { public function write_record($record, $rownum) { $rowheight = 0; + // If $record is an object convert it to an array. + if (is_object($record)) { + $record = (array)$record; + } + foreach ($record as $cell) { $rowheight = max($rowheight, $this->pdf->getStringHeight($this->colwidth, $cell, false, true, '', 1)); } @@ -99,12 +104,19 @@ public function write_record($record, $rownum) { $this->print_heading(); } - $total = count($record); - $counter = 1; - foreach ($record as $cell) { - $nextposition = ($counter == $total) ? 1 : 0; + // Get the last key for this record. + end($record); + $lastkey = key($record); + + // Reset the record pointer. + reset($record); + + // Loop through each element. + foreach ($record as $key => $cell) { + // Determine whether we're at the last element of the record. + $nextposition = ($lastkey === $key) ? 1 : 0; + // Write the element. $this->pdf->Multicell($this->colwidth, $rowheight, $cell, 1, 'L', false, $nextposition); - $counter++; } }