Completed
Push — master ( 03866a...251c0b )
by Adrien
03:24
created

StyleHelper   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 266
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 97.8%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 29
c 5
b 0
f 0
lcom 1
cbo 2
dl 0
loc 266
ccs 89
cts 91
cp 0.978
rs 10

12 Methods

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