Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace OpenSpout\Reader\Common\Creator;
   6  
   7  use OpenSpout\Common\Exception\IOException;
   8  use OpenSpout\Common\Exception\UnsupportedTypeException;
   9  use OpenSpout\Reader\CSV\Reader as CSVReader;
  10  use OpenSpout\Reader\ODS\Reader as ODSReader;
  11  use OpenSpout\Reader\ReaderInterface;
  12  use OpenSpout\Reader\XLSX\Reader as XLSXReader;
  13  
  14  /**
  15   * This factory is used to create readers, based on the type of the file to be read.
  16   * It supports CSV, XLSX and ODS formats.
  17   */
  18  final class ReaderFactory
  19  {
  20      /**
  21       * Creates a reader by file extension.
  22       *
  23       * @param string $path The path to the spreadsheet file. Supported extensions are .csv,.ods and .xlsx
  24       *
  25       * @throws \OpenSpout\Common\Exception\UnsupportedTypeException
  26       */
  27      public static function createFromFile(string $path): ReaderInterface
  28      {
  29          $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
  30  
  31          return match ($extension) {
  32              'csv' => new CSVReader(),
  33              'xlsx' => new XLSXReader(),
  34              'ods' => new ODSReader(),
  35              default => throw new UnsupportedTypeException('No readers supporting the given type: '.$extension),
  36          };
  37      }
  38  
  39      /**
  40       * Creates a reader by mime type.
  41       *
  42       * @param string $path the path to the spreadsheet file
  43       *
  44       * @throws \OpenSpout\Common\Exception\UnsupportedTypeException
  45       * @throws \OpenSpout\Common\Exception\IOException
  46       */
  47      public static function createFromFileByMimeType(string $path): ReaderInterface
  48      {
  49          if (!file_exists($path)) {
  50              throw new IOException("Could not open {$path} for reading! File does not exist.");
  51          }
  52  
  53          $mime_type = mime_content_type($path);
  54  
  55          return match ($mime_type) {
  56              'application/csv', 'text/csv', 'text/plain' => new CSVReader(),
  57              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => new XLSXReader(),
  58              'application/vnd.oasis.opendocument.spreadsheet' => new ODSReader(),
  59              default => throw new UnsupportedTypeException('No readers supporting the given type: '.$mime_type),
  60          };
  61      }
  62  }