Completed
Pull Request — develop_3.0 (#460)
by Adrien
02:25
created

StyleManager::getStylesAttributes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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