Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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