1 |
efrain |
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 |
* @deprecated Guessing mechanisms are brittle by nature and won't be provided by this library anymore
|
|
|
19 |
*/
|
|
|
20 |
final class ReaderFactory
|
|
|
21 |
{
|
|
|
22 |
/**
|
|
|
23 |
* Creates a reader by file extension.
|
|
|
24 |
*
|
|
|
25 |
* @param string $path The path to the spreadsheet file. Supported extensions are .csv,.ods and .xlsx
|
|
|
26 |
*
|
|
|
27 |
* @throws UnsupportedTypeException
|
|
|
28 |
*/
|
|
|
29 |
public static function createFromFile(string $path): ReaderInterface
|
|
|
30 |
{
|
|
|
31 |
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
|
|
|
32 |
|
|
|
33 |
return match ($extension) {
|
|
|
34 |
'csv' => new CSVReader(),
|
|
|
35 |
'xlsx' => new XLSXReader(),
|
|
|
36 |
'ods' => new ODSReader(),
|
|
|
37 |
default => throw new UnsupportedTypeException('No readers supporting the given type: '.$extension),
|
|
|
38 |
};
|
|
|
39 |
}
|
|
|
40 |
|
|
|
41 |
/**
|
|
|
42 |
* Creates a reader by mime type.
|
|
|
43 |
*
|
|
|
44 |
* @param string $path the path to the spreadsheet file
|
|
|
45 |
*
|
|
|
46 |
* @throws UnsupportedTypeException
|
|
|
47 |
* @throws IOException
|
|
|
48 |
*/
|
|
|
49 |
public static function createFromFileByMimeType(string $path): ReaderInterface
|
|
|
50 |
{
|
|
|
51 |
if (!file_exists($path)) {
|
|
|
52 |
throw new IOException("Could not open {$path} for reading! File does not exist.");
|
|
|
53 |
}
|
|
|
54 |
|
|
|
55 |
$mime_type = mime_content_type($path);
|
|
|
56 |
|
|
|
57 |
return match ($mime_type) {
|
|
|
58 |
'application/csv', 'text/csv', 'text/plain' => new CSVReader(),
|
|
|
59 |
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => new XLSXReader(),
|
|
|
60 |
'application/vnd.oasis.opendocument.spreadsheet' => new ODSReader(),
|
|
|
61 |
default => throw new UnsupportedTypeException('No readers supporting the given type: '.$mime_type),
|
|
|
62 |
};
|
|
|
63 |
}
|
|
|
64 |
}
|