Completed
Push — better_date_custom_format_supp... ( 281692 )
by Adrien
02:59
created

StyleHelper::shouldFormatNumericValueAsDate()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 10
cts 10
cp 1
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 10
nc 3
nop 1
crap 4
1
<?php
2
3
namespace Box\Spout\Reader\XLSX\Helper;
4
5
use Box\Spout\Reader\Wrapper\XMLReader;
6
7
/**
8
 * Class StyleHelper
9
 * This class provides helper functions related to XLSX styles
10
 *
11
 * @package Box\Spout\Reader\XLSX\Helper
12
 */
13
class StyleHelper
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 int[] Array containing the IDs of built-in number formats indicating a date */
57
    protected $builtinNumFmtIdIndicatingDates;
58
59
    /** @var array Array containing a mapping NUM_FMT_ID => FORMAT_CODE */
60
    protected $customNumberFormats;
61
62
    /** @var array Array containing a mapping STYLE_ID => [STYLE_ATTRIBUTES] */
63
    protected $stylesAttributes;
64
65
    /** @var array Cache containing a mapping NUM_FMT_ID => IS_DATE_FORMAT. Used to avoid lots of recalculations */
66
    protected $numFmtIdToIsDateFormatCache = [];
67
68
    /**
69
     * @param string $filePath Path of the XLSX file being read
70
     */
71 192
    public function __construct($filePath)
72
    {
73 192
        $this->filePath = $filePath;
74 192
        $this->builtinNumFmtIdIndicatingDates = array_keys(self::$builtinNumFmtIdToNumFormatMapping);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_keys(self::$builti...mtIdToNumFormatMapping) of type array<integer,integer|string> is incompatible with the declared type array<integer,integer> of property $builtinNumFmtIdIndicatingDates.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
75 192
    }
76
77
    /**
78
     * Returns whether the style with the given ID should consider
79
     * numeric values as timestamps and format the cell as a date.
80
     *
81
     * @param int $styleId Zero-based style ID
82
     * @return bool Whether the cell with the given cell should display a date instead of a numeric value
83
     */
84 129
    public function shouldFormatNumericValueAsDate($styleId)
85
    {
86 129
        $stylesAttributes = $this->getStylesAttributes();
87
88
        // Default style (0) does not format numeric values as timestamps. Only custom styles do.
89
        // Also if the style ID does not exist in the styles.xml file, format as numeric value.
90
        // Using isset here because it is way faster than array_key_exists...
91 129
        if ($styleId === self::DEFAULT_STYLE_ID || !isset($stylesAttributes[$styleId])) {
92 18
            return false;
93
        }
94
95 111
        $styleAttributes = $stylesAttributes[$styleId];
96
97 111
        $applyNumberFormat = $styleAttributes[self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT];
98 111
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
99
100 111
        if (!$this->areStyleAttributesPossiblyIndicatingDate($applyNumberFormat, $numFmtId)) {
101 6
            return false;
102
        }
103
104 105
        return $this->doesNumFmtIdIndicateDate($numFmtId);
105
    }
106
107
    /**
108
     * Reads the styles.xml file and extract the relevant information from the file.
109
     *
110
     * @return void
111
     */
112 30
    protected function extractRelevantInfo()
113
    {
114 30
        $this->customNumberFormats = [];
115 30
        $this->stylesAttributes = [];
116
117 30
        $xmlReader = new XMLReader();
118
119 30
        if ($xmlReader->openFileInZip($this->filePath, self::STYLES_XML_FILE_PATH)) {
120 30
            while ($xmlReader->read()) {
121 30
                if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMTS)) {
122 21
                    $this->extractNumberFormats($xmlReader);
123
124 30
                } else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) {
125 30
                    $this->extractStyleAttributes($xmlReader);
126 30
                }
127 30
            }
128
129 30
            $xmlReader->close();
130 30
        }
131 30
    }
132
133
    /**
134
     * Extracts number formats from the "numFmt" nodes.
135
     * For simplicity, the styles attributes are kept in memory. This is possible thanks
136
     * to the reuse of formats. So 1 million cells should not use 1 million formats.
137
     *
138
     * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XML Reader positioned on the "numFmts" node
139
     * @return void
140
     */
141 21
    protected function extractNumberFormats($xmlReader)
142
    {
143 21
        while ($xmlReader->read()) {
144 21
            if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMT)) {
145 21
                $numFmtId = intval($xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID));
146 21
                $formatCode = $xmlReader->getAttribute(self::XML_ATTRIBUTE_FORMAT_CODE);
147 21
                $this->customNumberFormats[$numFmtId] = $formatCode;
148 21
            } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_NUM_FMTS)) {
149
                // Once done reading "numFmts" node's children
150 21
                break;
151
            }
152 21
        }
153 21
    }
154
155
    /**
156
     * Extracts style attributes from the "xf" nodes, inside the "cellXfs" section.
157
     * For simplicity, the styles attributes are kept in memory. This is possible thanks
158
     * to the reuse of styles. So 1 million cells should not use 1 million styles.
159
     *
160
     * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XML Reader positioned on the "cellXfs" node
161
     * @return void
162
     */
163 30
    protected function extractStyleAttributes($xmlReader)
164
    {
165 30
        while ($xmlReader->read()) {
166 30
            if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_XF)) {
167 30
                $numFmtId = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID);
168 30
                $normalizedNumFmtId = ($numFmtId !== null) ? intval($numFmtId) : null;
169
170 30
                $applyNumberFormat = $xmlReader->getAttribute(self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT);
171 30
                $normalizedApplyNumberFormat = ($applyNumberFormat !== null) ? !!$applyNumberFormat : null;
172
173 30
                $this->stylesAttributes[] = [
174 30
                    self::XML_ATTRIBUTE_NUM_FMT_ID => $normalizedNumFmtId,
175 30
                    self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT => $normalizedApplyNumberFormat,
176
                ];
177 30
            } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_CELL_XFS)) {
178
                // Once done reading "cellXfs" node's children
179 30
                break;
180
            }
181 30
        }
182 30
    }
183
184
    /**
185
     * @return array The custom number formats
186
     */
187 15
    protected function getCustomNumberFormats()
188
    {
189 15
        if (!isset($this->customNumberFormats)) {
190
            $this->extractRelevantInfo();
191
        }
192
193 15
        return $this->customNumberFormats;
194
    }
195
196
    /**
197
     * @return array The styles attributes
198
     */
199 30
    protected function getStylesAttributes()
200
    {
201 30
        if (!isset($this->stylesAttributes)) {
202 30
            $this->extractRelevantInfo();
203 30
        }
204
205 30
        return $this->stylesAttributes;
206
    }
207
208
    /**
209
     * A style may apply a date format if it has:
210
     *  - "applyNumberFormat" attribute not set to "false"
211
     *  - "numFmtId" attribute set
212
     *
213
     * This is a preliminary check, as having "numFmtId" set just means the style should apply a specific number format,
214
     * but this is not necessarily a date.
215
     *
216
     * @param bool|null $applyNumberFormat
217
     * @param int|null $numFmtId
218
     * @return bool Whether the given style attributes can indicate that the style applies a date format
219
     */
220 111
    protected function areStyleAttributesPossiblyIndicatingDate($applyNumberFormat, $numFmtId)
221
    {
222 111
        return ($applyNumberFormat !== false && $numFmtId !== null);
223
    }
224
225
    /**
226
     * Returns whether the number format ID indicates that the number is a date.
227
     * The result is cached to avoid recomputing the same thing over and over, as
228
     * "numFmtId" attributes can be shared between multiple styles.
229
     *
230
     * @param int $numFmtId
231
     * @return bool Whether the number format ID indicates that the number is a date
232
     */
233 105
    protected function doesNumFmtIdIndicateDate($numFmtId)
234
    {
235 105
        if (!isset($this->numFmtIdToIsDateFormatCache[$numFmtId])) {
236 105
            $this->numFmtIdToIsDateFormatCache[$numFmtId] = (
237 105
                $this->isNumFmtIdBuiltInDateFormat($numFmtId) ||
238 99
                $this->isNumFmtIdCustomDateFormat($numFmtId)
239 99
            );
240 105
        }
241
242 105
        return $this->numFmtIdToIsDateFormatCache[$numFmtId];
243
    }
244
245
    /**
246
     * @param int $numFmtId
247
     * @return bool Whether the number format ID indicates that the number is a timestamp
248
     */
249 105
    protected function isNumFmtIdBuiltInDateFormat($numFmtId)
250
    {
251 105
        return in_array($numFmtId, $this->builtinNumFmtIdIndicatingDates);
252
    }
253
254
    /**
255
     * @param int $numFmtId
256
     * @return bool Whether the number format ID indicates that the number is a timestamp
257
     */
258 99
    protected function isNumFmtIdCustomDateFormat($numFmtId)
259
    {
260 99
        $customNumberFormat = $this->getCustomNumberFormatForNumFmtId($numFmtId);
261
262
        // if no associated number format or if using the default "General" format
263 99
        if ($customNumberFormat === null || strcasecmp($customNumberFormat, self::NUMBER_FORMAT_GENERAL) === 0) {
264 21
            return false;
265
        }
266
267
        // Remove extra formatting (what's between [ ], the brackets should not be preceded by a "\")
268 81
        $pattern = '((?<!\\\)\[.+?(?<!\\\)\])';
269 81
        $customNumberFormat = preg_replace($pattern, '', $customNumberFormat);
270
271
        // custom date formats contain specific characters to represent the date:
272
        // e - yy - m - d - h - s
273
        // and all of their variants (yyyy - mm - dd...)
274 81
        $dateFormatCharacters = ['e', 'yy', 'm', 'd', 'h', 's'];
275
276 81
        $hasFoundDateFormatCharacter = false;
277 81
        foreach ($dateFormatCharacters as $dateFormatCharacter) {
278
            // character not preceded by "\" (case insensitive)
279 81
            $pattern = '/(?<!\\\)' . $dateFormatCharacter . '/i';
280
281 81
            if (preg_match($pattern, $customNumberFormat)) {
282 75
                $hasFoundDateFormatCharacter = true;
283 75
                break;
284
            }
285 81
        }
286
287 81
        return $hasFoundDateFormatCharacter;
288
    }
289
290
    /**
291
     * @param $numFmtId
292
     * @return string|null The custom number format or NULL if none defined for the given numFmtId
293
     */
294 99
    protected function getCustomNumberFormatForNumFmtId($numFmtId)
295
    {
296 99
        $customNumberFormats = $this->getCustomNumberFormats();
297
298
        // Using isset here because it is way faster than array_key_exists...
299 99
        return (isset($customNumberFormats[$numFmtId])) ? $customNumberFormats[$numFmtId] : null;
300
    }
301
302
    /**
303
     * Returns the format as defined in "styles.xml" of the given style.
304
     * NOTE: It is assumed that the style DOES have a number format associated to it.
305
     *
306
     * @param int $styleId Zero-based style ID
307
     * @return string The number format associated with the given style
308
     */
309 6
    public function getNumberFormat($styleId)
310
    {
311 6
        $stylesAttributes = $this->getStylesAttributes();
312 6
        $styleAttributes = $stylesAttributes[$styleId];
313 6
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
314
315 6
        if ($this->isNumFmtIdBuiltInDateFormat($numFmtId)) {
316 3
            $numberFormat = self::$builtinNumFmtIdToNumFormatMapping[$numFmtId];
317 3
        } else {
318 6
            $customNumberFormats = $this->getCustomNumberFormats();
319 6
            $numberFormat = $customNumberFormats[$numFmtId];
320
        }
321
322 6
        return $numberFormat;
323
    }
324
}
325