Completed
Push — prefix_in_styles_xml ( 317159...2de5b9 )
by Adrien
02:33
created

StyleHelper::shouldFormatNumericValueAsDate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 21
rs 9.0534
ccs 10
cts 10
cp 1
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\SimpleXMLElement;
6
use Box\Spout\Reader\Wrapper\XMLReader;
7
8
/**
9
 * Class StyleHelper
10
 * This class provides helper functions related to XLSX styles
11
 *
12
 * @package Box\Spout\Reader\XLSX\Helper
13
 */
14
class StyleHelper
15
{
16
    /** Paths of XML files relative to the XLSX file root */
17
    const STYLES_XML_FILE_PATH = 'xl/styles.xml';
18
19
    /** Nodes used to find relevant information in the styles XML file */
20
    const XML_NODE_NUM_FMTS = 'numFmts';
21
    const XML_NODE_NUM_FMT = 'numFmt';
22
    const XML_NODE_CELL_XFS = 'cellXfs';
23
    const XML_NODE_XF = 'xf';
24
25
    /** Attributes used to find relevant information in the styles XML file */
26
    const XML_ATTRIBUTE_NUM_FMT_ID = 'numFmtId';
27
    const XML_ATTRIBUTE_FORMAT_CODE = 'formatCode';
28
    const XML_ATTRIBUTE_APPLY_NUMBER_FORMAT = 'applyNumberFormat';
29
30
    /** By convention, default style ID is 0 */
31
    const DEFAULT_STYLE_ID = 0;
32
33
    /**
34
     * @see https://msdn.microsoft.com/en-us/library/ff529597(v=office.12).aspx
35
     * @var array Mapping between built-in numFmtId and the associated format - for dates only
36
     */
37
    protected static $builtinNumFmtIdToNumFormatMapping = [
38
        14 => 'm/d/yyyy', // @NOTE: ECMA spec is 'mm-dd-yy'
39
        15 => 'd-mmm-yy',
40
        16 => 'd-mmm',
41
        17 => 'mmm-yy',
42
        18 => 'h:mm AM/PM',
43
        19 => 'h:mm:ss AM/PM',
44
        20 => 'h:mm',
45
        21 => 'h:mm:ss',
46
        22 => 'm/d/yyyy h:mm', // @NOTE: ECMA spec is 'm/d/yy h:mm',
47
        45 => 'mm:ss',
48
        46 => '[h]:mm:ss',
49
        47 => 'mm:ss.0',  // @NOTE: ECMA spec is 'mmss.0',
50
    ];
51
52
    /** @var string Path of the XLSX file being read */
53
    protected $filePath;
54
55
    /** @var array Array containing a mapping NUM_FMT_ID => FORMAT_CODE */
56
    protected $customNumberFormats;
57
58
    /** @var array Array containing a mapping STYLE_ID => [STYLE_ATTRIBUTES] */
59
    protected $stylesAttributes;
60
61
    /**
62
     * @param string $filePath Path of the XLSX file being read
63
     */
64 90
    public function __construct($filePath)
65
    {
66 90
        $this->filePath = $filePath;
67 90
    }
68
69
    /**
70
     * Reads the styles.xml file and extract the relevant information from the file.
71
     *
72
     * @return void
73
     */
74 27
    protected function extractRelevantInfo()
75
    {
76 27
        $this->customNumberFormats = [];
77 27
        $this->stylesAttributes = [];
78
79 27
        $xmlReader = new XMLReader();
80
81 27
        if ($xmlReader->openFileInZip($this->filePath, self::STYLES_XML_FILE_PATH)) {
82 27
            while ($xmlReader->read()) {
83 27
                if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMTS)) {
84 18
                    $this->extractNumberFormats($xmlReader);
85
86 27
                } else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) {
87 27
                    $this->extractStyleAttributes($xmlReader);
88 27
                }
89 27
            }
90
91 27
            $xmlReader->close();
92 27
        }
93 27
    }
94
95
    /**
96
     * Extracts number formats from the "numFmt" nodes.
97
     * For simplicity, the styles attributes are kept in memory. This is possible thanks
98
     * to the reuse of formats. So 1 million cells should not use 1 million formats.
99
     *
100
     * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XML Reader positioned on the "numFmts" node
101
     * @return void
102
     */
103 18
    protected function extractNumberFormats($xmlReader)
104
    {
105 18
        while ($xmlReader->read()) {
106 18
            if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMT)) {
107 18
                $numFmtId = intval($xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID));
108 18
                $formatCode = $xmlReader->getAttribute(self::XML_ATTRIBUTE_FORMAT_CODE);
109 18
                $this->customNumberFormats[$numFmtId] = $formatCode;
110 18
            } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_NUM_FMTS)) {
111
                // Once done reading "numFmts" node's children
112 18
                break;
113
            }
114 18
        }
115 18
    }
116
117
    /**
118
     * Extracts style attributes from the "xf" nodes, inside the "cellXfs" section.
119
     * For simplicity, the styles attributes are kept in memory. This is possible thanks
120
     * to the reuse of styles. So 1 million cells should not use 1 million styles.
121
     *
122
     * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XML Reader positioned on the "cellXfs" node
123
     * @return void
124
     */
125 27
    protected function extractStyleAttributes($xmlReader)
126
    {
127 27
        while ($xmlReader->read()) {
128 27
            if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_XF)) {
129 27
                $this->stylesAttributes[] = [
130 27
                    self::XML_ATTRIBUTE_NUM_FMT_ID => intval($xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID)),
131 27
                    self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT => !!($xmlReader->getAttribute(self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT)),
132
                ];
133 27
            } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_CELL_XFS)) {
134
                // Once done reading "cellXfs" node's children
135 27
                break;
136
            }
137 27
        }
138 27
    }
139
140
    /**
141
     * @return array The custom number formats
142
     */
143 12
    protected function getCustomNumberFormats()
144
    {
145 12
        if (!isset($this->customNumberFormats)) {
146
            $this->extractRelevantInfo();
147
        }
148
149 12
        return $this->customNumberFormats;
150
    }
151
152
    /**
153
     * @return array The styles attributes
154
     */
155 27
    protected function getStylesAttributes()
156
    {
157 27
        if (!isset($this->stylesAttributes)) {
158 27
            $this->extractRelevantInfo();
159 27
        }
160
161 27
        return $this->stylesAttributes;
162
    }
163
164
    /**
165
     * Returns whether the style with the given ID should consider
166
     * numeric values as timestamps and format the cell as a date.
167
     *
168
     * @param int $styleId Zero-based style ID
169
     * @return bool Whether the cell with the given cell should display a date instead of a numeric value
170
     */
171 108
    public function shouldFormatNumericValueAsDate($styleId)
172
    {
173 108
        $stylesAttributes = $this->getStylesAttributes();
174
175
        // Default style (0) does not format numeric values as timestamps. Only custom styles do.
176
        // Also if the style ID does not exist in the styles.xml file, format as numeric value.
177
        // Using isset here because it is way faster than array_key_exists...
178 108
        if ($styleId === self::DEFAULT_STYLE_ID || !isset($stylesAttributes[$styleId])) {
179 21
            return false;
180
        }
181
182 87
        $styleAttributes = $stylesAttributes[$styleId];
183
184 87
        $applyNumberFormat = $styleAttributes[self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT];
185 87
        if (!$applyNumberFormat) {
186 3
            return false;
187
        }
188
189 84
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
190 84
        return $this->doesNumFmtIdIndicateDate($numFmtId);
191
    }
192
193
    /**
194
     * @param int $numFmtId
195
     * @return bool Whether the number format ID indicates that the number is a timestamp
196
     */
197 84
    protected function doesNumFmtIdIndicateDate($numFmtId)
198
    {
199
        return (
200 84
            !$this->doesNumFmtIdIndicateGeneralFormat($numFmtId) &&
201
            (
202 81
                $this->isNumFmtIdBuiltInDateFormat($numFmtId) ||
203 78
                $this->isNumFmtIdCustomDateFormat($numFmtId)
204 78
            )
205 84
        );
206
    }
207
208
    /**
209
     * @param int $numFmtId
210
     * @return bool Whether the number format ID indicates the "General" format (0 by convention)
211
     */
212 84
    protected function doesNumFmtIdIndicateGeneralFormat($numFmtId)
213
    {
214 84
        return ($numFmtId === 0);
215
    }
216
217
    /**
218
     * @param int $numFmtId
219
     * @return bool Whether the number format ID indicates that the number is a timestamp
220
     */
221 81
    protected function isNumFmtIdBuiltInDateFormat($numFmtId)
222
    {
223 81
        $builtInDateFormatIds = array_keys(self::$builtinNumFmtIdToNumFormatMapping);
224 81
        return in_array($numFmtId, $builtInDateFormatIds);
225
    }
226
227
    /**
228
     * @param int $numFmtId
229
     * @return bool Whether the number format ID indicates that the number is a timestamp
230
     */
231 78
    protected function isNumFmtIdCustomDateFormat($numFmtId)
232
    {
233 78
        $customNumberFormats = $this->getCustomNumberFormats();
234
235
        // Using isset here because it is way faster than array_key_exists...
236 78
        if (!isset($customNumberFormats[$numFmtId])) {
237 3
            return false;
238
        }
239
240 75
        $customNumberFormat = $customNumberFormats[$numFmtId];
241
242
        // Remove extra formatting (what's between [ ], the brackets should not be preceded by a "\")
243 75
        $pattern = '((?<!\\\)\[.+?(?<!\\\)\])';
244 75
        $customNumberFormat = preg_replace($pattern, '', $customNumberFormat);
245
246
        // custom date formats contain specific characters to represent the date:
247
        // e - yy - m - d - h - s
248
        // and all of their variants (yyyy - mm - dd...)
249 75
        $dateFormatCharacters = ['e', 'yy', 'm', 'd', 'h', 's'];
250
251 75
        $hasFoundDateFormatCharacter = false;
252 75
        foreach ($dateFormatCharacters as $dateFormatCharacter) {
253
            // character not preceded by "\"
254 75
            $pattern = '/(?<!\\\)' . $dateFormatCharacter . '/';
255
256 75
            if (preg_match($pattern, $customNumberFormat)) {
257 66
                $hasFoundDateFormatCharacter = true;
258 66
                break;
259
            }
260 75
        }
261
262 75
        return $hasFoundDateFormatCharacter;
263
    }
264
265
    /**
266
     * Returns the format as defined in "styles.xml" of the given style.
267
     * NOTE: It is assumed that the style DOES have a number format associated to it.
268
     *
269
     * @param int $styleId Zero-based style ID
270
     * @return string The number format associated with the given style
271
     */
272 3
    public function getNumberFormat($styleId)
273
    {
274 3
        $stylesAttributes = $this->getStylesAttributes();
275 3
        $styleAttributes = $stylesAttributes[$styleId];
276 3
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
277
278 3
        if ($this->isNumFmtIdBuiltInDateFormat($numFmtId)) {
279 3
            $numberFormat = self::$builtinNumFmtIdToNumFormatMapping[$numFmtId];
280 3
        } else {
281 3
            $customNumberFormats = $this->getCustomNumberFormats();
282 3
            $numberFormat = $customNumberFormats[$numFmtId];
283
        }
284
285 3
        return $numberFormat;
286
    }
287
}
288