Completed
Push — master ( a6a6b1...104cd9 )
by Adrien
02:44
created

StyleHelper   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 267
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 97.83%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 29
c 4
b 0
f 0
lcom 1
cbo 2
dl 0
loc 267
ccs 90
cts 92
cp 0.9783
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A doesNumFmtIdIndicateGeneralFormat() 0 4 1
A isNumFmtIdBuiltInDateFormat() 0 5 1
A __construct() 0 4 1
B extractRelevantInfo() 0 23 5
A extractNumberFormats() 0 8 2
A extractStyleAttributes() 0 9 2
A getCustomNumberFormats() 0 8 2
A getStylesAttributes() 0 8 2
A shouldFormatNumericValueAsDate() 0 21 4
A doesNumFmtIdIndicateDate() 0 10 3
B isNumFmtIdCustomDateFormat() 0 33 4
A getNumberFormat() 0 15 2
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 78
    public function __construct($filePath)
65
    {
66 78
        $this->filePath = $filePath;
67 78
    }
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
        $stylesXmlFilePath = $this->filePath .'#' . self::STYLES_XML_FILE_PATH;
80 27
        $xmlReader = new XMLReader();
81
82 27
        if ($xmlReader->open('zip://' . $stylesXmlFilePath)) {
83 27
            while ($xmlReader->read()) {
84 27
                if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMTS)) {
85 18
                    $numFmtsNode = new SimpleXMLElement($xmlReader->readOuterXml());
86 18
                    $this->extractNumberFormats($numFmtsNode);
87
88 27
                } else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) {
89 27
                    $cellXfsNode = new SimpleXMLElement($xmlReader->readOuterXml());
90 27
                    $this->extractStyleAttributes($cellXfsNode);
91 27
                }
92 27
            }
93
94 27
            $xmlReader->close();
95 27
        }
96 27
    }
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
     * @return void
105
     */
106 18
    protected function extractNumberFormats($numFmtsNode)
107
    {
108 18
        foreach ($numFmtsNode->children() as $numFmtNode) {
109 18
            $numFmtId = intval($numFmtNode->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID));
110 18
            $formatCode = $numFmtNode->getAttribute(self::XML_ATTRIBUTE_FORMAT_CODE);
111 18
            $this->customNumberFormats[$numFmtId] = $formatCode;
112 18
        }
113 18
    }
114
115
    /**
116
     * Extracts style attributes from the "xf" nodes, inside the "cellXfs" section.
117
     * 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
     *
120
     * @param SimpleXMLElement $cellXfsNode The "cellXfs" node
121
     * @return void
122
     */
123 27
    protected function extractStyleAttributes($cellXfsNode)
124
    {
125 27
        foreach ($cellXfsNode->children() as $xfNode) {
126 27
            $this->stylesAttributes[] = [
127 27
                self::XML_ATTRIBUTE_NUM_FMT_ID => intval($xfNode->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID)),
128 27
                self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT => !!($xfNode->getAttribute(self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT)),
129
            ];
130 27
        }
131 27
    }
132
133
    /**
134
     * @return array The custom number formats
135
     */
136 12
    protected function getCustomNumberFormats()
137
    {
138 12
        if (!isset($this->customNumberFormats)) {
139
            $this->extractRelevantInfo();
140
        }
141
142 12
        return $this->customNumberFormats;
143
    }
144
145
    /**
146
     * @return array The styles attributes
147
     */
148 27
    protected function getStylesAttributes()
149
    {
150 27
        if (!isset($this->stylesAttributes)) {
151 27
            $this->extractRelevantInfo();
152 27
        }
153
154 27
        return $this->stylesAttributes;
155
    }
156
157
    /**
158
     * Returns whether the style with the given ID should consider
159
     * numeric values as timestamps and format the cell as a date.
160
     *
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
     */
164 108
    public function shouldFormatNumericValueAsDate($styleId)
165
    {
166 108
        $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 108
        if ($styleId === self::DEFAULT_STYLE_ID || !isset($stylesAttributes[$styleId])) {
172 21
            return false;
173
        }
174
175 87
        $styleAttributes = $stylesAttributes[$styleId];
176
177 87
        $applyNumberFormat = $styleAttributes[self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT];
178 87
        if (!$applyNumberFormat) {
179 3
            return false;
180
        }
181
182 84
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
183 84
        return $this->doesNumFmtIdIndicateDate($numFmtId);
184
    }
185
186
    /**
187
     * @param int $numFmtId
188
     * @return bool Whether the number format ID indicates that the number is a timestamp
189
     */
190 84
    protected function doesNumFmtIdIndicateDate($numFmtId)
191
    {
192
        return (
193 84
            !$this->doesNumFmtIdIndicateGeneralFormat($numFmtId) &&
194
            (
195 81
                $this->isNumFmtIdBuiltInDateFormat($numFmtId) ||
196 78
                $this->isNumFmtIdCustomDateFormat($numFmtId)
197 78
            )
198 84
        );
199
    }
200
201
    /**
202
     * @param int $numFmtId
203
     * @return bool Whether the number format ID indicates the "General" format (0 by convention)
204
     */
205 84
    protected function doesNumFmtIdIndicateGeneralFormat($numFmtId)
206
    {
207 84
        return ($numFmtId === 0);
208
    }
209
210
    /**
211
     * @param int $numFmtId
212
     * @return bool Whether the number format ID indicates that the number is a timestamp
213
     */
214 81
    protected function isNumFmtIdBuiltInDateFormat($numFmtId)
215
    {
216 81
        $builtInDateFormatIds = array_keys(self::$builtinNumFmtIdToNumFormatMapping);
217 81
        return in_array($numFmtId, $builtInDateFormatIds);
218
    }
219
220
    /**
221
     * @param int $numFmtId
222
     * @return bool Whether the number format ID indicates that the number is a timestamp
223
     */
224 78
    protected function isNumFmtIdCustomDateFormat($numFmtId)
225
    {
226 78
        $customNumberFormats = $this->getCustomNumberFormats();
227
228
        // Using isset here because it is way faster than array_key_exists...
229 78
        if (!isset($customNumberFormats[$numFmtId])) {
230 3
            return false;
231
        }
232
233 75
        $customNumberFormat = $customNumberFormats[$numFmtId];
234
235
        // Remove extra formatting (what's between [ ], the brackets should not be preceded by a "\")
236 75
        $pattern = '((?<!\\\)\[.+?(?<!\\\)\])';
237 75
        $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 75
        $dateFormatCharacters = ['e', 'yy', 'm', 'd', 'h', 's'];
243
244 75
        $hasFoundDateFormatCharacter = false;
245 75
        foreach ($dateFormatCharacters as $dateFormatCharacter) {
246
            // character not preceded by "\"
247 75
            $pattern = '/(?<!\\\)' . $dateFormatCharacter . '/';
248
249 75
            if (preg_match($pattern, $customNumberFormat)) {
250 66
                $hasFoundDateFormatCharacter = true;
251 66
                break;
252
            }
253 75
        }
254
255 75
        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 3
    public function getNumberFormat($styleId)
266
    {
267 3
        $stylesAttributes = $this->getStylesAttributes();
268 3
        $styleAttributes = $stylesAttributes[$styleId];
269 3
        $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
270
271 3
        if ($this->isNumFmtIdBuiltInDateFormat($numFmtId)) {
272 3
            $numberFormat = self::$builtinNumFmtIdToNumFormatMapping[$numFmtId];
273 3
        } else {
274 3
            $customNumberFormats = $this->getCustomNumberFormats();
275 3
            $numberFormat = $customNumberFormats[$numFmtId];
276
        }
277
278 3
        return $numberFormat;
279
    }
280
}
281