Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace OpenSpout\Reader\XLSX\Manager;
6
 
7
use OpenSpout\Reader\Wrapper\XMLReader;
8
 
9
class StyleManager implements StyleManagerInterface
10
{
11
    /**
12
     * Nodes used to find relevant information in the styles XML file.
13
     */
14
    final public const XML_NODE_NUM_FMTS = 'numFmts';
15
    final public const XML_NODE_NUM_FMT = 'numFmt';
16
    final public const XML_NODE_CELL_XFS = 'cellXfs';
17
    final public const XML_NODE_XF = 'xf';
18
 
19
    /**
20
     * Attributes used to find relevant information in the styles XML file.
21
     */
22
    final public const XML_ATTRIBUTE_NUM_FMT_ID = 'numFmtId';
23
    final public const XML_ATTRIBUTE_FORMAT_CODE = 'formatCode';
24
    final public const XML_ATTRIBUTE_APPLY_NUMBER_FORMAT = 'applyNumberFormat';
25
    final public const XML_ATTRIBUTE_COUNT = 'count';
26
 
27
    /**
28
     * By convention, default style ID is 0.
29
     */
30
    final public const DEFAULT_STYLE_ID = 0;
31
 
32
    final public const NUMBER_FORMAT_GENERAL = 'General';
33
 
34
    /**
35
     * Mapping between built-in numFmtId and the associated format - for dates only.
36
     *
37
     * @see https://msdn.microsoft.com/en-us/library/ff529597(v=office.12).aspx
38
     */
39
    private const builtinNumFmtIdToNumFormatMapping = [
40
        14 => 'm/d/yyyy', // @NOTE: ECMA spec is 'mm-dd-yy'
41
        15 => 'd-mmm-yy',
42
        16 => 'd-mmm',
43
        17 => 'mmm-yy',
44
        18 => 'h:mm AM/PM',
45
        19 => 'h:mm:ss AM/PM',
46
        20 => 'h:mm',
47
        21 => 'h:mm:ss',
48
        22 => 'm/d/yyyy h:mm', // @NOTE: ECMA spec is 'm/d/yy h:mm',
49
        45 => 'mm:ss',
50
        46 => '[h]:mm:ss',
51
        47 => 'mm:ss.0',  // @NOTE: ECMA spec is 'mmss.0',
52
    ];
53
 
54
    /** @var string Path of the XLSX file being read */
55
    private readonly string $filePath;
56
 
57
    /** @var null|string Path of the styles XML file */
58
    private readonly ?string $stylesXMLFilePath;
59
 
60
    /** @var array<int, string> Array containing a mapping NUM_FMT_ID => FORMAT_CODE */
61
    private array $customNumberFormats;
62
 
63
    /** @var array<array-key, array<string, null|bool|int>> Array containing a mapping STYLE_ID => [STYLE_ATTRIBUTES] */
64
    private array $stylesAttributes;
65
 
66
    /** @var array<int, bool> Cache containing a mapping NUM_FMT_ID => IS_DATE_FORMAT. Used to avoid lots of recalculations */
67
    private array $numFmtIdToIsDateFormatCache = [];
68
 
69
    /**
1441 ariadna 70
     * @param string $filePath Path of the XLSX file being read
1 efrain 71
     */
72
    public function __construct(string $filePath, ?string $stylesXMLFilePath)
73
    {
74
        $this->filePath = $filePath;
75
        $this->stylesXMLFilePath = $stylesXMLFilePath;
76
    }
77
 
78
    public function shouldFormatNumericValueAsDate(int $styleId): bool
79
    {
80
        if (null === $this->stylesXMLFilePath) {
81
            return false;
82
        }
83
 
84
        $stylesAttributes = $this->getStylesAttributes();
85
 
86
        // Default style (0) does not format numeric values as timestamps. Only custom styles do.
87
        // Also if the style ID does not exist in the styles.xml file, format as numeric value.
88
        // Using isset here because it is way faster than array_key_exists...
89
        if (self::DEFAULT_STYLE_ID === $styleId || !isset($stylesAttributes[$styleId])) {
90
            return false;
91
        }
92
 
93
        $styleAttributes = $stylesAttributes[$styleId];
94
 
95
        return $this->doesStyleIndicateDate($styleAttributes);
96
    }
97
 
98
    public function getNumberFormatCode(int $styleId): string
99
    {
1441 ariadna 100
        if (null === $this->stylesXMLFilePath) {
101
            return '';
102
        }
103
 
1 efrain 104
        $stylesAttributes = $this->getStylesAttributes();
1441 ariadna 105
 
106
        if (!isset($stylesAttributes[$styleId])) {
107
            return '';
108
        }
109
 
1 efrain 110
        $styleAttributes = $stylesAttributes[$styleId];
111
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
112
        \assert(\is_int($numFmtId));
113
 
114
        if ($this->isNumFmtIdBuiltInDateFormat($numFmtId)) {
115
            $numberFormatCode = self::builtinNumFmtIdToNumFormatMapping[$numFmtId];
116
        } else {
117
            $customNumberFormats = $this->getCustomNumberFormats();
118
            $numberFormatCode = $customNumberFormats[$numFmtId] ?? '';
119
        }
120
 
121
        return $numberFormatCode;
122
    }
123
 
124
    /**
125
     * @return array<int, string> The custom number formats
126
     */
127
    protected function getCustomNumberFormats(): array
128
    {
129
        if (!isset($this->customNumberFormats)) {
130
            $this->extractRelevantInfo();
131
        }
132
 
133
        return $this->customNumberFormats;
134
    }
135
 
136
    /**
137
     * @return array<array-key, array<string, null|bool|int>> The styles attributes
138
     */
139
    protected function getStylesAttributes(): array
140
    {
141
        if (!isset($this->stylesAttributes)) {
142
            $this->extractRelevantInfo();
143
        }
144
 
145
        return $this->stylesAttributes;
146
    }
147
 
148
    /**
149
     * Reads the styles.xml file and extract the relevant information from the file.
150
     */
151
    private function extractRelevantInfo(): void
152
    {
153
        $this->customNumberFormats = [];
154
        $this->stylesAttributes = [];
155
 
156
        $xmlReader = new XMLReader();
157
 
158
        if ($xmlReader->openFileInZip($this->filePath, $this->stylesXMLFilePath)) {
159
            while ($xmlReader->read()) {
160
                if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMTS)
161
                    && '0' !== $xmlReader->getAttribute(self::XML_ATTRIBUTE_COUNT)) {
162
                    $this->extractNumberFormats($xmlReader);
163
                } elseif ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) {
164
                    $this->extractStyleAttributes($xmlReader);
165
                }
166
            }
167
 
168
            $xmlReader->close();
169
        }
170
    }
171
 
172
    /**
173
     * Extracts number formats from the "numFmt" nodes.
174
     * For simplicity, the styles attributes are kept in memory. This is possible thanks
175
     * to the reuse of formats. So 1 million cells should not use 1 million formats.
176
     *
177
     * @param XMLReader $xmlReader XML Reader positioned on the "numFmts" node
178
     */
179
    private function extractNumberFormats(XMLReader $xmlReader): void
180
    {
181
        while ($xmlReader->read()) {
182
            if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMT)) {
183
                $numFmtId = (int) $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID);
184
                $formatCode = $xmlReader->getAttribute(self::XML_ATTRIBUTE_FORMAT_CODE);
185
                \assert(null !== $formatCode);
186
                $this->customNumberFormats[$numFmtId] = $formatCode;
187
            } elseif ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_NUM_FMTS)) {
188
                // Once done reading "numFmts" node's children
189
                break;
190
            }
191
        }
192
    }
193
 
194
    /**
195
     * Extracts style attributes from the "xf" nodes, inside the "cellXfs" section.
196
     * For simplicity, the styles attributes are kept in memory. This is possible thanks
197
     * to the reuse of styles. So 1 million cells should not use 1 million styles.
198
     *
199
     * @param XMLReader $xmlReader XML Reader positioned on the "cellXfs" node
200
     */
201
    private function extractStyleAttributes(XMLReader $xmlReader): void
202
    {
203
        while ($xmlReader->read()) {
204
            if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_XF)) {
205
                $numFmtId = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID);
206
                $normalizedNumFmtId = (null !== $numFmtId) ? (int) $numFmtId : null;
207
 
208
                $applyNumberFormat = $xmlReader->getAttribute(self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT);
209
                $normalizedApplyNumberFormat = (null !== $applyNumberFormat) ? (bool) $applyNumberFormat : null;
210
 
211
                $this->stylesAttributes[] = [
212
                    self::XML_ATTRIBUTE_NUM_FMT_ID => $normalizedNumFmtId,
213
                    self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT => $normalizedApplyNumberFormat,
214
                ];
215
            } elseif ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_CELL_XFS)) {
216
                // Once done reading "cellXfs" node's children
217
                break;
218
            }
219
        }
220
    }
221
 
222
    /**
223
     * @param array<string, null|bool|int> $styleAttributes Array containing the style attributes (2 keys: "applyNumberFormat" and "numFmtId")
224
     *
225
     * @return bool Whether the style with the given attributes indicates that the number is a date
226
     */
227
    private function doesStyleIndicateDate(array $styleAttributes): bool
228
    {
229
        $applyNumberFormat = $styleAttributes[self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT];
230
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
231
 
232
        // A style may apply a date format if it has:
233
        //  - "applyNumberFormat" attribute not set to "false"
234
        //  - "numFmtId" attribute set
235
        // This is a preliminary check, as having "numFmtId" set just means the style should apply a specific number format,
236
        // but this is not necessarily a date.
237
        if (false === $applyNumberFormat || !\is_int($numFmtId)) {
238
            return false;
239
        }
240
 
241
        return $this->doesNumFmtIdIndicateDate($numFmtId);
242
    }
243
 
244
    /**
245
     * Returns whether the number format ID indicates that the number is a date.
246
     * The result is cached to avoid recomputing the same thing over and over, as
247
     * "numFmtId" attributes can be shared between multiple styles.
248
     *
249
     * @return bool Whether the number format ID indicates that the number is a date
250
     */
251
    private function doesNumFmtIdIndicateDate(int $numFmtId): bool
252
    {
253
        if (!isset($this->numFmtIdToIsDateFormatCache[$numFmtId])) {
254
            $formatCode = $this->getFormatCodeForNumFmtId($numFmtId);
255
 
256
            $this->numFmtIdToIsDateFormatCache[$numFmtId] = (
257
                $this->isNumFmtIdBuiltInDateFormat($numFmtId)
258
                || $this->isFormatCodeCustomDateFormat($formatCode)
259
            );
260
        }
261
 
262
        return $this->numFmtIdToIsDateFormatCache[$numFmtId];
263
    }
264
 
265
    /**
266
     * @return null|string The custom number format or NULL if none defined for the given numFmtId
267
     */
268
    private function getFormatCodeForNumFmtId(int $numFmtId): ?string
269
    {
270
        $customNumberFormats = $this->getCustomNumberFormats();
271
 
272
        // Using isset here because it is way faster than array_key_exists...
273
        return $customNumberFormats[$numFmtId] ?? null;
274
    }
275
 
276
    /**
277
     * @return bool Whether the number format ID indicates that the number is a date
278
     */
279
    private function isNumFmtIdBuiltInDateFormat(int $numFmtId): bool
280
    {
281
        return \array_key_exists($numFmtId, self::builtinNumFmtIdToNumFormatMapping);
282
    }
283
 
284
    /**
285
     * @return bool Whether the given format code indicates that the number is a date
286
     */
287
    private function isFormatCodeCustomDateFormat(?string $formatCode): bool
288
    {
289
        // if no associated format code or if using the default "General" format
290
        if (null === $formatCode || 0 === strcasecmp($formatCode, self::NUMBER_FORMAT_GENERAL)) {
291
            return false;
292
        }
293
 
294
        return $this->isFormatCodeMatchingDateFormatPattern($formatCode);
295
    }
296
 
297
    /**
298
     * @return bool Whether the given format code matches a date format pattern
299
     */
300
    private function isFormatCodeMatchingDateFormatPattern(string $formatCode): bool
301
    {
302
        // Remove extra formatting (what's between [ ], the brackets should not be preceded by a "\")
303
        $pattern = '((?<!\\\)\[.+?(?<!\\\)\])';
304
        $formatCode = preg_replace($pattern, '', $formatCode);
305
        \assert(null !== $formatCode);
306
 
307
        // Remove strings in double quotes, as they won't be interpreted as date format characters
308
        $formatCode = preg_replace('/"[^"]+"/', '', $formatCode);
309
        \assert(null !== $formatCode);
310
 
311
        // custom date formats contain specific characters to represent the date:
312
        // e - yy - m - d - h - s
313
        // and all of their variants (yyyy - mm - dd...)
314
        $dateFormatCharacters = ['e', 'yy', 'm', 'd', 'h', 's'];
315
 
316
        $hasFoundDateFormatCharacter = false;
317
        foreach ($dateFormatCharacters as $dateFormatCharacter) {
318
            // character not preceded by "\" (case insensitive)
319
            $pattern = '/(?<!\\\)'.$dateFormatCharacter.'/i';
320
 
321
            if (1 === preg_match($pattern, $formatCode)) {
322
                $hasFoundDateFormatCharacter = true;
323
 
324
                break;
325
            }
326
        }
327
 
328
        return $hasFoundDateFormatCharacter;
329
    }
330
}