Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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