Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  
   3  namespace PhpOffice\PhpSpreadsheet;
   4  
   5  use PhpOffice\PhpSpreadsheet\Reader\IReader;
   6  use PhpOffice\PhpSpreadsheet\Shared\File;
   7  use PhpOffice\PhpSpreadsheet\Writer\IWriter;
   8  
   9  /**
  10   * Factory to create readers and writers easily.
  11   *
  12   * It is not required to use this class, but it should make it easier to read and write files.
  13   * Especially for reading files with an unknown format.
  14   */
  15  abstract class IOFactory
  16  {
  17      public const READER_XLSX = 'Xlsx';
  18      public const READER_XLS = 'Xls';
  19      public const READER_XML = 'Xml';
  20      public const READER_ODS = 'Ods';
  21      public const READER_SYLK = 'Slk';
  22      public const READER_SLK = 'Slk';
  23      public const READER_GNUMERIC = 'Gnumeric';
  24      public const READER_HTML = 'Html';
  25      public const READER_CSV = 'Csv';
  26  
  27      public const WRITER_XLSX = 'Xlsx';
  28      public const WRITER_XLS = 'Xls';
  29      public const WRITER_ODS = 'Ods';
  30      public const WRITER_CSV = 'Csv';
  31      public const WRITER_HTML = 'Html';
  32  
  33      private static $readers = [
  34          self::READER_XLSX => Reader\Xlsx::class,
  35          self::READER_XLS => Reader\Xls::class,
  36          self::READER_XML => Reader\Xml::class,
  37          self::READER_ODS => Reader\Ods::class,
  38          self::READER_SLK => Reader\Slk::class,
  39          self::READER_GNUMERIC => Reader\Gnumeric::class,
  40          self::READER_HTML => Reader\Html::class,
  41          self::READER_CSV => Reader\Csv::class,
  42      ];
  43  
  44      private static $writers = [
  45          self::WRITER_XLS => Writer\Xls::class,
  46          self::WRITER_XLSX => Writer\Xlsx::class,
  47          self::WRITER_ODS => Writer\Ods::class,
  48          self::WRITER_CSV => Writer\Csv::class,
  49          self::WRITER_HTML => Writer\Html::class,
  50          'Tcpdf' => Writer\Pdf\Tcpdf::class,
  51          'Dompdf' => Writer\Pdf\Dompdf::class,
  52          'Mpdf' => Writer\Pdf\Mpdf::class,
  53      ];
  54  
  55      /**
  56       * Create Writer\IWriter.
  57       */
  58      public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter
  59      {
  60          if (!isset(self::$writers[$writerType])) {
  61              throw new Writer\Exception("No writer found for type $writerType");
  62          }
  63  
  64          // Instantiate writer
  65          $className = self::$writers[$writerType];
  66  
  67          return new $className($spreadsheet);
  68      }
  69  
  70      /**
  71       * Create IReader.
  72       */
  73      public static function createReader(string $readerType): IReader
  74      {
  75          if (!isset(self::$readers[$readerType])) {
  76              throw new Reader\Exception("No reader found for type $readerType");
  77          }
  78  
  79          // Instantiate reader
  80          $className = self::$readers[$readerType];
  81  
  82          return new $className();
  83      }
  84  
  85      /**
  86       * Loads Spreadsheet from file using automatic Reader\IReader resolution.
  87       *
  88       * @param string $filename The name of the spreadsheet file
  89       * @param int $flags the optional second parameter flags may be used to identify specific elements
  90       *                       that should be loaded, but which won't be loaded by default, using these values:
  91       *                            IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file
  92       * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try
  93       *                             all possible Readers until it finds a match; but this allows you to pass in a
  94       *                             list of Readers so it will only try the subset that you specify here.
  95       *                          Values in this list can be any of the constant values defined in the set
  96       *                                 IOFactory::READER_*.
  97       */
  98      public static function load(string $filename, int $flags = 0, ?array $readers = null): Spreadsheet
  99      {
 100          $reader = self::createReaderForFile($filename, $readers);
 101  
 102          return $reader->load($filename, $flags);
 103      }
 104  
 105      /**
 106       * Identify file type using automatic IReader resolution.
 107       */
 108      public static function identify(string $filename, ?array $readers = null): string
 109      {
 110          $reader = self::createReaderForFile($filename, $readers);
 111          $className = get_class($reader);
 112          $classType = explode('\\', $className);
 113          unset($reader);
 114  
 115          return array_pop($classType);
 116      }
 117  
 118      /**
 119       * Create Reader\IReader for file using automatic IReader resolution.
 120       *
 121       * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try
 122       *                             all possible Readers until it finds a match; but this allows you to pass in a
 123       *                             list of Readers so it will only try the subset that you specify here.
 124       *                          Values in this list can be any of the constant values defined in the set
 125       *                                 IOFactory::READER_*.
 126       */
 127      public static function createReaderForFile(string $filename, ?array $readers = null): IReader
 128      {
 129          File::assertFile($filename);
 130  
 131          $testReaders = self::$readers;
 132          if ($readers !== null) {
 133              $readers = array_map('strtoupper', $readers);
 134              $testReaders = array_filter(
 135                  self::$readers,
 136                  function (string $readerType) use ($readers) {
 137                      return in_array(strtoupper($readerType), $readers, true);
 138                  },
 139                  ARRAY_FILTER_USE_KEY
 140              );
 141          }
 142  
 143          // First, lucky guess by inspecting file extension
 144          $guessedReader = self::getReaderTypeFromExtension($filename);
 145          if (($guessedReader !== null) && array_key_exists($guessedReader, $testReaders)) {
 146              $reader = self::createReader($guessedReader);
 147  
 148              // Let's see if we are lucky
 149              if ($reader->canRead($filename)) {
 150                  return $reader;
 151              }
 152          }
 153  
 154          // If we reach here then "lucky guess" didn't give any result
 155          // Try walking through all the options in self::$readers (or the selected subset)
 156          foreach ($testReaders as $readerType => $class) {
 157              //    Ignore our original guess, we know that won't work
 158              if ($readerType !== $guessedReader) {
 159                  $reader = self::createReader($readerType);
 160                  if ($reader->canRead($filename)) {
 161                      return $reader;
 162                  }
 163              }
 164          }
 165  
 166          throw new Reader\Exception('Unable to identify a reader for this file');
 167      }
 168  
 169      /**
 170       * Guess a reader type from the file extension, if any.
 171       */
 172      private static function getReaderTypeFromExtension(string $filename): ?string
 173      {
 174          $pathinfo = pathinfo($filename);
 175          if (!isset($pathinfo['extension'])) {
 176              return null;
 177          }
 178  
 179          switch (strtolower($pathinfo['extension'])) {
 180              case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet
 181              case 'xlsm': // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded)
 182              case 'xltx': // Excel (OfficeOpenXML) Template
 183              case 'xltm': // Excel (OfficeOpenXML) Macro Template (macros will be discarded)
 184                  return 'Xlsx';
 185              case 'xls': // Excel (BIFF) Spreadsheet
 186              case 'xlt': // Excel (BIFF) Template
 187                  return 'Xls';
 188              case 'ods': // Open/Libre Offic Calc
 189              case 'ots': // Open/Libre Offic Calc Template
 190                  return 'Ods';
 191              case 'slk':
 192                  return 'Slk';
 193              case 'xml': // Excel 2003 SpreadSheetML
 194                  return 'Xml';
 195              case 'gnumeric':
 196                  return 'Gnumeric';
 197              case 'htm':
 198              case 'html':
 199                  return 'Html';
 200              case 'csv':
 201                  // Do nothing
 202                  // We must not try to use CSV reader since it loads
 203                  // all files including Excel files etc.
 204                  return null;
 205              default:
 206                  return null;
 207          }
 208      }
 209  
 210      /**
 211       * Register a writer with its type and class name.
 212       */
 213      public static function registerWriter(string $writerType, string $writerClass): void
 214      {
 215          if (!is_a($writerClass, IWriter::class, true)) {
 216              throw new Writer\Exception('Registered writers must implement ' . IWriter::class);
 217          }
 218  
 219          self::$writers[$writerType] = $writerClass;
 220      }
 221  
 222      /**
 223       * Register a reader with its type and class name.
 224       */
 225      public static function registerReader(string $readerType, string $readerClass): void
 226      {
 227          if (!is_a($readerClass, IReader::class, true)) {
 228              throw new Reader\Exception('Registered readers must implement ' . IReader::class);
 229          }
 230  
 231          self::$readers[$readerType] = $readerClass;
 232      }
 233  }