Completed
Pull Request — master (#226)
by Adrien
02:44
created

StyleHelper::shouldFormatNumericValueAsDate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

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