Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace OpenSpout\Writer\Common\Creator;
   6  
   7  use OpenSpout\Common\Exception\UnsupportedTypeException;
   8  use OpenSpout\Writer\CSV\Writer as CSVWriter;
   9  use OpenSpout\Writer\ODS\Writer as ODSWriter;
  10  use OpenSpout\Writer\WriterInterface;
  11  use OpenSpout\Writer\XLSX\Writer as XLSXWriter;
  12  
  13  /**
  14   * This factory is used to create writers, based on the type of the file to be read.
  15   * It supports CSV, XLSX and ODS formats.
  16   */
  17  final class WriterFactory
  18  {
  19      /**
  20       * This creates an instance of the appropriate writer, given the extension of the file to be written.
  21       *
  22       * @param string $path The path to the spreadsheet file. Supported extensions are .csv,.ods and .xlsx
  23       *
  24       * @throws \OpenSpout\Common\Exception\UnsupportedTypeException
  25       */
  26      public static function createFromFile(string $path): WriterInterface
  27      {
  28          $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
  29  
  30          return match ($extension) {
  31              'csv' => new CSVWriter(),
  32              'xlsx' => new XLSXWriter(),
  33              'ods' => new ODSWriter(),
  34              default => throw new UnsupportedTypeException('No writers supporting the given type: '.$extension),
  35          };
  36      }
  37  }