Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401]

   1  <?php
   2  
   3  namespace Box\Spout\Writer\ODS\Manager;
   4  
   5  use Box\Spout\Common\Entity\Cell;
   6  use Box\Spout\Common\Entity\Row;
   7  use Box\Spout\Common\Entity\Style\Style;
   8  use Box\Spout\Common\Exception\InvalidArgumentException;
   9  use Box\Spout\Common\Exception\IOException;
  10  use Box\Spout\Common\Helper\Escaper\ODS as ODSEscaper;
  11  use Box\Spout\Common\Helper\StringHelper;
  12  use Box\Spout\Writer\Common\Entity\Worksheet;
  13  use Box\Spout\Writer\Common\Manager\Style\StyleMerger;
  14  use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
  15  use Box\Spout\Writer\ODS\Manager\Style\StyleManager;
  16  
  17  /**
  18   * Class WorksheetManager
  19   * ODS worksheet manager, providing the interfaces to work with ODS worksheets.
  20   */
  21  class WorksheetManager implements WorksheetManagerInterface
  22  {
  23      /** @var \Box\Spout\Common\Helper\Escaper\ODS Strings escaper */
  24      private $stringsEscaper;
  25  
  26      /** @var StringHelper String helper */
  27      private $stringHelper;
  28  
  29      /** @var StyleManager Manages styles */
  30      private $styleManager;
  31  
  32      /** @var StyleMerger Helper to merge styles together */
  33      private $styleMerger;
  34  
  35      /**
  36       * WorksheetManager constructor.
  37       *
  38       * @param StyleManager $styleManager
  39       * @param StyleMerger $styleMerger
  40       * @param ODSEscaper $stringsEscaper
  41       * @param StringHelper $stringHelper
  42       */
  43      public function __construct(
  44          StyleManager $styleManager,
  45          StyleMerger $styleMerger,
  46          ODSEscaper $stringsEscaper,
  47          StringHelper $stringHelper
  48      ) {
  49          $this->styleManager = $styleManager;
  50          $this->styleMerger = $styleMerger;
  51          $this->stringsEscaper = $stringsEscaper;
  52          $this->stringHelper = $stringHelper;
  53      }
  54  
  55      /**
  56       * Prepares the worksheet to accept data
  57       *
  58       * @param Worksheet $worksheet The worksheet to start
  59       * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
  60       * @return void
  61       */
  62      public function startSheet(Worksheet $worksheet)
  63      {
  64          $sheetFilePointer = fopen($worksheet->getFilePath(), 'w');
  65          $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
  66  
  67          $worksheet->setFilePointer($sheetFilePointer);
  68      }
  69  
  70      /**
  71       * Checks if the sheet has been sucessfully created. Throws an exception if not.
  72       *
  73       * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
  74       * @throws IOException If the sheet data file cannot be opened for writing
  75       * @return void
  76       */
  77      private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
  78      {
  79          if (!$sheetFilePointer) {
  80              throw new IOException('Unable to open sheet for writing.');
  81          }
  82      }
  83  
  84      /**
  85       * Returns the table XML root node as string.
  86       *
  87       * @param Worksheet $worksheet
  88       * @return string <table> node as string
  89       */
  90      public function getTableElementStartAsString(Worksheet $worksheet)
  91      {
  92          $externalSheet = $worksheet->getExternalSheet();
  93          $escapedSheetName = $this->stringsEscaper->escape($externalSheet->getName());
  94          $tableStyleName = 'ta' . ($externalSheet->getIndex() + 1);
  95  
  96          $tableElement  = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
  97          $tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $worksheet->getMaxNumColumns() . '"/>';
  98  
  99          return $tableElement;
 100      }
 101  
 102      /**
 103       * Adds a row to the given worksheet.
 104       *
 105       * @param Worksheet $worksheet The worksheet to add the row to
 106       * @param Row $row The row to be added
 107       * @throws IOException If the data cannot be written
 108       * @throws InvalidArgumentException If a cell value's type is not supported
 109       * @return void
 110       */
 111      public function addRow(Worksheet $worksheet, Row $row)
 112      {
 113          $cells = $row->getCells();
 114          $rowStyle = $row->getStyle();
 115  
 116          $data = '<table:table-row table:style-name="ro1">';
 117  
 118          $currentCellIndex = 0;
 119          $nextCellIndex = 1;
 120  
 121          for ($i = 0; $i < $row->getNumCells(); $i++) {
 122              /** @var Cell $cell */
 123              $cell = $cells[$currentCellIndex];
 124              /** @var Cell|null $nextCell */
 125              $nextCell = isset($cells[$nextCellIndex]) ? $cells[$nextCellIndex] : null;
 126  
 127              if ($nextCell === null || $cell->getValue() !== $nextCell->getValue()) {
 128                  $data .= $this->applyStyleAndGetCellXML($cell, $rowStyle, $currentCellIndex, $nextCellIndex);
 129                  $currentCellIndex = $nextCellIndex;
 130              }
 131  
 132              $nextCellIndex++;
 133          }
 134  
 135          $data .= '</table:table-row>';
 136  
 137          $wasWriteSuccessful = fwrite($worksheet->getFilePointer(), $data);
 138          if ($wasWriteSuccessful === false) {
 139              throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
 140          }
 141  
 142          // only update the count if the write worked
 143          $lastWrittenRowIndex = $worksheet->getLastWrittenRowIndex();
 144          $worksheet->setLastWrittenRowIndex($lastWrittenRowIndex + 1);
 145      }
 146  
 147      /**
 148       * Applies styles to the given style, merging the cell's style with its row's style
 149       * Then builds and returns xml for the cell.
 150       *
 151       * @param Cell $cell
 152       * @param Style $rowStyle
 153       * @param int $currentCellIndex
 154       * @param int $nextCellIndex
 155       * @throws InvalidArgumentException If a cell value's type is not supported
 156       * @return string
 157       */
 158      private function applyStyleAndGetCellXML(Cell $cell, Style $rowStyle, $currentCellIndex, $nextCellIndex)
 159      {
 160          // Apply row and extra styles
 161          $mergedCellAndRowStyle = $this->styleMerger->merge($cell->getStyle(), $rowStyle);
 162          $cell->setStyle($mergedCellAndRowStyle);
 163          $newCellStyle = $this->styleManager->applyExtraStylesIfNeeded($cell);
 164  
 165          $registeredStyle = $this->styleManager->registerStyle($newCellStyle);
 166          $styleIndex = $registeredStyle->getId() + 1; // 1-based
 167  
 168          $numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
 169  
 170          return $this->getCellXML($cell, $styleIndex, $numTimesValueRepeated);
 171      }
 172  
 173      /**
 174       * Returns the cell XML content, given its value.
 175       *
 176       * @param Cell $cell The cell to be written
 177       * @param int $styleIndex Index of the used style
 178       * @param int $numTimesValueRepeated Number of times the value is consecutively repeated
 179       * @throws InvalidArgumentException If a cell value's type is not supported
 180       * @return string The cell XML content
 181       */
 182      private function getCellXML(Cell $cell, $styleIndex, $numTimesValueRepeated)
 183      {
 184          $data = '<table:table-cell table:style-name="ce' . $styleIndex . '"';
 185  
 186          if ($numTimesValueRepeated !== 1) {
 187              $data .= ' table:number-columns-repeated="' . $numTimesValueRepeated . '"';
 188          }
 189  
 190          if ($cell->isString()) {
 191              $data .= ' office:value-type="string" calcext:value-type="string">';
 192  
 193              $cellValueLines = explode("\n", $cell->getValue());
 194              foreach ($cellValueLines as $cellValueLine) {
 195                  $data .= '<text:p>' . $this->stringsEscaper->escape($cellValueLine) . '</text:p>';
 196              }
 197  
 198              $data .= '</table:table-cell>';
 199          } elseif ($cell->isBoolean()) {
 200              $data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $cell->getValue() . '">';
 201              $data .= '<text:p>' . $cell->getValue() . '</text:p>';
 202              $data .= '</table:table-cell>';
 203          } elseif ($cell->isNumeric()) {
 204              $data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cell->getValue() . '">';
 205              $data .= '<text:p>' . $cell->getValue() . '</text:p>';
 206              $data .= '</table:table-cell>';
 207          } elseif ($cell->isEmpty()) {
 208              $data .= '/>';
 209          } else {
 210              throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
 211          }
 212  
 213          return $data;
 214      }
 215  
 216      /**
 217       * Closes the worksheet
 218       *
 219       * @param Worksheet $worksheet
 220       * @return void
 221       */
 222      public function close(Worksheet $worksheet)
 223      {
 224          $worksheetFilePointer = $worksheet->getFilePointer();
 225  
 226          if (!is_resource($worksheetFilePointer)) {
 227              return;
 228          }
 229  
 230          fclose($worksheetFilePointer);
 231      }
 232  }