Passed
Pull Request — master (#4323)
by Owen
11:36
created

Parser::matchCellSheetnameQuoted()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
4
5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
8
use PhpOffice\PhpSpreadsheet\Spreadsheet;
9
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet;
10
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
11
12
// Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class):
13
// -----------------------------------------------------------------------------------------
14
// *  Class for parsing Excel formulas
15
// *
16
// *  License Information:
17
// *
18
// *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
19
// *    Copyright (c) 2002-2003 Xavier Noguer [email protected]
20
// *
21
// *    This library is free software; you can redistribute it and/or
22
// *    modify it under the terms of the GNU Lesser General Public
23
// *    License as published by the Free Software Foundation; either
24
// *    version 2.1 of the License, or (at your option) any later version.
25
// *
26
// *    This library is distributed in the hope that it will be useful,
27
// *    but WITHOUT ANY WARRANTY; without even the implied warranty of
28
// *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
29
// *    Lesser General Public License for more details.
30
// *
31
// *    You should have received a copy of the GNU Lesser General Public
32
// *    License along with this library; if not, write to the Free Software
33
// *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
34
// */
35
class Parser
36
{
37
    /**    Constants                */
38
    // Sheet title in unquoted form
39
    // Invalid sheet title characters cannot occur in the sheet title:
40
    //         *:/\?[]
41
    // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
42
    // +-% '^&<>=,;#()"{}
43
    const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
44
45
    // Sheet title in quoted form (without surrounding quotes)
46
    // Invalid sheet title characters cannot occur in the sheet title:
47
    // *:/\?[]                    (usual invalid sheet title characters)
48
    // Single quote is represented as a pair ''
49
    // Former value for this constant led to "catastrophic backtracking",
50
    //     unable to handle double apostrophes.
51
    //     (*COMMIT) should prevent this.
52
    const REGEX_SHEET_TITLE_QUOTED = "([^*:/\\\\?\[\]']|'')+";
53
54
    const REGEX_CELL_TITLE_QUOTED = "~^'"
55
        . self::REGEX_SHEET_TITLE_QUOTED
56
        . '(:' . self::REGEX_SHEET_TITLE_QUOTED . ')?'
57
        . "'!(*COMMIT)"
58
        . '[$]?[A-Ia-i]?[A-Za-z][$]?(\\d+)'
59
        . '$~u';
60
61
    const REGEX_RANGE_TITLE_QUOTED = "~^'"
62
        . self::REGEX_SHEET_TITLE_QUOTED
63
        . '(:' . self::REGEX_SHEET_TITLE_QUOTED . ')?'
64
        . "'!(*COMMIT)"
65
        . '[$]?[A-Ia-i]?[A-Za-z][$]?(\\d+)'
66
        . ':'
67
        . '[$]?[A-Ia-i]?[A-Za-z][$]?(\\d+)'
68
        . '$~u';
69
70
    /**
71
     * The index of the character we are currently looking at.
72
     */
73
    public int $currentCharacter;
74
75
    /**
76
     * The token we are working on.
77
     */
78
    public string $currentToken;
79
80
    /**
81
     * The formula to parse.
82
     */
83
    private string $formula;
84
85
    /**
86
     * The character ahead of the current char.
87
     */
88
    public string $lookAhead;
89
90
    /**
91
     * The parse tree to be generated.
92
     */
93
    public array|string $parseTree;
94
95
    /**
96
     * Array of external sheets.
97
     */
98
    private array $externalSheets;
99
100
    /**
101
     * Array of sheet references in the form of REF structures.
102
     */
103
    public array $references;
104
105
    /**
106
     * The Excel ptg indices.
107
     */
108
    private array $ptg = [
109
        'ptgExp' => 0x01,
110
        'ptgTbl' => 0x02,
111
        'ptgAdd' => 0x03,
112
        'ptgSub' => 0x04,
113
        'ptgMul' => 0x05,
114
        'ptgDiv' => 0x06,
115
        'ptgPower' => 0x07,
116
        'ptgConcat' => 0x08,
117
        'ptgLT' => 0x09,
118
        'ptgLE' => 0x0A,
119
        'ptgEQ' => 0x0B,
120
        'ptgGE' => 0x0C,
121
        'ptgGT' => 0x0D,
122
        'ptgNE' => 0x0E,
123
        'ptgIsect' => 0x0F,
124
        'ptgUnion' => 0x10,
125
        'ptgRange' => 0x11,
126
        'ptgUplus' => 0x12,
127
        'ptgUminus' => 0x13,
128
        'ptgPercent' => 0x14,
129
        'ptgParen' => 0x15,
130
        'ptgMissArg' => 0x16,
131
        'ptgStr' => 0x17,
132
        'ptgAttr' => 0x19,
133
        'ptgSheet' => 0x1A,
134
        'ptgEndSheet' => 0x1B,
135
        'ptgErr' => 0x1C,
136
        'ptgBool' => 0x1D,
137
        'ptgInt' => 0x1E,
138
        'ptgNum' => 0x1F,
139
        'ptgArray' => 0x20,
140
        'ptgFunc' => 0x21,
141
        'ptgFuncVar' => 0x22,
142
        'ptgName' => 0x23,
143
        'ptgRef' => 0x24,
144
        'ptgArea' => 0x25,
145
        'ptgMemArea' => 0x26,
146
        'ptgMemErr' => 0x27,
147
        'ptgMemNoMem' => 0x28,
148
        'ptgMemFunc' => 0x29,
149
        'ptgRefErr' => 0x2A,
150
        'ptgAreaErr' => 0x2B,
151
        'ptgRefN' => 0x2C,
152
        'ptgAreaN' => 0x2D,
153
        'ptgMemAreaN' => 0x2E,
154
        'ptgMemNoMemN' => 0x2F,
155
        'ptgNameX' => 0x39,
156
        'ptgRef3d' => 0x3A,
157
        'ptgArea3d' => 0x3B,
158
        'ptgRefErr3d' => 0x3C,
159
        'ptgAreaErr3d' => 0x3D,
160
        'ptgArrayV' => 0x40,
161
        'ptgFuncV' => 0x41,
162
        'ptgFuncVarV' => 0x42,
163
        'ptgNameV' => 0x43,
164
        'ptgRefV' => 0x44,
165
        'ptgAreaV' => 0x45,
166
        'ptgMemAreaV' => 0x46,
167
        'ptgMemErrV' => 0x47,
168
        'ptgMemNoMemV' => 0x48,
169
        'ptgMemFuncV' => 0x49,
170
        'ptgRefErrV' => 0x4A,
171
        'ptgAreaErrV' => 0x4B,
172
        'ptgRefNV' => 0x4C,
173
        'ptgAreaNV' => 0x4D,
174
        'ptgMemAreaNV' => 0x4E,
175
        'ptgMemNoMemNV' => 0x4F,
176
        'ptgFuncCEV' => 0x58,
177
        'ptgNameXV' => 0x59,
178
        'ptgRef3dV' => 0x5A,
179
        'ptgArea3dV' => 0x5B,
180
        'ptgRefErr3dV' => 0x5C,
181
        'ptgAreaErr3dV' => 0x5D,
182
        'ptgArrayA' => 0x60,
183
        'ptgFuncA' => 0x61,
184
        'ptgFuncVarA' => 0x62,
185
        'ptgNameA' => 0x63,
186
        'ptgRefA' => 0x64,
187
        'ptgAreaA' => 0x65,
188
        'ptgMemAreaA' => 0x66,
189
        'ptgMemErrA' => 0x67,
190
        'ptgMemNoMemA' => 0x68,
191
        'ptgMemFuncA' => 0x69,
192
        'ptgRefErrA' => 0x6A,
193
        'ptgAreaErrA' => 0x6B,
194
        'ptgRefNA' => 0x6C,
195
        'ptgAreaNA' => 0x6D,
196
        'ptgMemAreaNA' => 0x6E,
197
        'ptgMemNoMemNA' => 0x6F,
198
        'ptgFuncCEA' => 0x78,
199
        'ptgNameXA' => 0x79,
200
        'ptgRef3dA' => 0x7A,
201
        'ptgArea3dA' => 0x7B,
202
        'ptgRefErr3dA' => 0x7C,
203
        'ptgAreaErr3dA' => 0x7D,
204
    ];
205
206
    /**
207
     * Thanks to Michael Meeks and Gnumeric for the initial arg values.
208
     *
209
     * The following hash was generated by "function_locale.pl" in the distro.
210
     * Refer to function_locale.pl for non-English function names.
211
     *
212
     * The array elements are as follow:
213
     * ptg:   The Excel function ptg code.
214
     * args:  The number of arguments that the function takes:
215
     *           >=0 is a fixed number of arguments.
216
     *           -1  is a variable  number of arguments.
217
     * class: The reference, value or array class of the function args.
218
     * vol:   The function is volatile.
219
     */
220
    private array $functions = [
221
        // function                  ptg  args  class  vol
222
        'COUNT' => [0, -1, 0, 0],
223
        'IF' => [1, -1, 1, 0],
224
        'ISNA' => [2, 1, 1, 0],
225
        'ISERROR' => [3, 1, 1, 0],
226
        'SUM' => [4, -1, 0, 0],
227
        'AVERAGE' => [5, -1, 0, 0],
228
        'MIN' => [6, -1, 0, 0],
229
        'MAX' => [7, -1, 0, 0],
230
        'ROW' => [8, -1, 0, 0],
231
        'COLUMN' => [9, -1, 0, 0],
232
        'NA' => [10, 0, 0, 0],
233
        'NPV' => [11, -1, 1, 0],
234
        'STDEV' => [12, -1, 0, 0],
235
        'DOLLAR' => [13, -1, 1, 0],
236
        'FIXED' => [14, -1, 1, 0],
237
        'SIN' => [15, 1, 1, 0],
238
        'COS' => [16, 1, 1, 0],
239
        'TAN' => [17, 1, 1, 0],
240
        'ATAN' => [18, 1, 1, 0],
241
        'PI' => [19, 0, 1, 0],
242
        'SQRT' => [20, 1, 1, 0],
243
        'EXP' => [21, 1, 1, 0],
244
        'LN' => [22, 1, 1, 0],
245
        'LOG10' => [23, 1, 1, 0],
246
        'ABS' => [24, 1, 1, 0],
247
        'INT' => [25, 1, 1, 0],
248
        'SIGN' => [26, 1, 1, 0],
249
        'ROUND' => [27, 2, 1, 0],
250
        'LOOKUP' => [28, -1, 0, 0],
251
        'INDEX' => [29, -1, 0, 1],
252
        'REPT' => [30, 2, 1, 0],
253
        'MID' => [31, 3, 1, 0],
254
        'LEN' => [32, 1, 1, 0],
255
        'VALUE' => [33, 1, 1, 0],
256
        'TRUE' => [34, 0, 1, 0],
257
        'FALSE' => [35, 0, 1, 0],
258
        'AND' => [36, -1, 0, 0],
259
        'OR' => [37, -1, 0, 0],
260
        'NOT' => [38, 1, 1, 0],
261
        'MOD' => [39, 2, 1, 0],
262
        'DCOUNT' => [40, 3, 0, 0],
263
        'DSUM' => [41, 3, 0, 0],
264
        'DAVERAGE' => [42, 3, 0, 0],
265
        'DMIN' => [43, 3, 0, 0],
266
        'DMAX' => [44, 3, 0, 0],
267
        'DSTDEV' => [45, 3, 0, 0],
268
        'VAR' => [46, -1, 0, 0],
269
        'DVAR' => [47, 3, 0, 0],
270
        'TEXT' => [48, 2, 1, 0],
271
        'LINEST' => [49, -1, 0, 0],
272
        'TREND' => [50, -1, 0, 0],
273
        'LOGEST' => [51, -1, 0, 0],
274
        'GROWTH' => [52, -1, 0, 0],
275
        'PV' => [56, -1, 1, 0],
276
        'FV' => [57, -1, 1, 0],
277
        'NPER' => [58, -1, 1, 0],
278
        'PMT' => [59, -1, 1, 0],
279
        'RATE' => [60, -1, 1, 0],
280
        'MIRR' => [61, 3, 0, 0],
281
        'IRR' => [62, -1, 0, 0],
282
        'RAND' => [63, 0, 1, 1],
283
        'MATCH' => [64, -1, 0, 0],
284
        'DATE' => [65, 3, 1, 0],
285
        'TIME' => [66, 3, 1, 0],
286
        'DAY' => [67, 1, 1, 0],
287
        'MONTH' => [68, 1, 1, 0],
288
        'YEAR' => [69, 1, 1, 0],
289
        'WEEKDAY' => [70, -1, 1, 0],
290
        'HOUR' => [71, 1, 1, 0],
291
        'MINUTE' => [72, 1, 1, 0],
292
        'SECOND' => [73, 1, 1, 0],
293
        'NOW' => [74, 0, 1, 1],
294
        'AREAS' => [75, 1, 0, 1],
295
        'ROWS' => [76, 1, 0, 1],
296
        'COLUMNS' => [77, 1, 0, 1],
297
        'OFFSET' => [78, -1, 0, 1],
298
        'SEARCH' => [82, -1, 1, 0],
299
        'TRANSPOSE' => [83, 1, 1, 0],
300
        'TYPE' => [86, 1, 1, 0],
301
        'ATAN2' => [97, 2, 1, 0],
302
        'ASIN' => [98, 1, 1, 0],
303
        'ACOS' => [99, 1, 1, 0],
304
        'CHOOSE' => [100, -1, 1, 0],
305
        'HLOOKUP' => [101, -1, 0, 0],
306
        'VLOOKUP' => [102, -1, 0, 0],
307
        'ISREF' => [105, 1, 0, 0],
308
        'LOG' => [109, -1, 1, 0],
309
        'CHAR' => [111, 1, 1, 0],
310
        'LOWER' => [112, 1, 1, 0],
311
        'UPPER' => [113, 1, 1, 0],
312
        'PROPER' => [114, 1, 1, 0],
313
        'LEFT' => [115, -1, 1, 0],
314
        'RIGHT' => [116, -1, 1, 0],
315
        'EXACT' => [117, 2, 1, 0],
316
        'TRIM' => [118, 1, 1, 0],
317
        'REPLACE' => [119, 4, 1, 0],
318
        'SUBSTITUTE' => [120, -1, 1, 0],
319
        'CODE' => [121, 1, 1, 0],
320
        'FIND' => [124, -1, 1, 0],
321
        'CELL' => [125, -1, 0, 1],
322
        'ISERR' => [126, 1, 1, 0],
323
        'ISTEXT' => [127, 1, 1, 0],
324
        'ISNUMBER' => [128, 1, 1, 0],
325
        'ISBLANK' => [129, 1, 1, 0],
326
        'T' => [130, 1, 0, 0],
327
        'N' => [131, 1, 0, 0],
328
        'DATEVALUE' => [140, 1, 1, 0],
329
        'TIMEVALUE' => [141, 1, 1, 0],
330
        'SLN' => [142, 3, 1, 0],
331
        'SYD' => [143, 4, 1, 0],
332
        'DDB' => [144, -1, 1, 0],
333
        'INDIRECT' => [148, -1, 1, 1],
334
        'CALL' => [150, -1, 1, 0],
335
        'CLEAN' => [162, 1, 1, 0],
336
        'MDETERM' => [163, 1, 2, 0],
337
        'MINVERSE' => [164, 1, 2, 0],
338
        'MMULT' => [165, 2, 2, 0],
339
        'IPMT' => [167, -1, 1, 0],
340
        'PPMT' => [168, -1, 1, 0],
341
        'COUNTA' => [169, -1, 0, 0],
342
        'PRODUCT' => [183, -1, 0, 0],
343
        'FACT' => [184, 1, 1, 0],
344
        'DPRODUCT' => [189, 3, 0, 0],
345
        'ISNONTEXT' => [190, 1, 1, 0],
346
        'STDEVP' => [193, -1, 0, 0],
347
        'VARP' => [194, -1, 0, 0],
348
        'DSTDEVP' => [195, 3, 0, 0],
349
        'DVARP' => [196, 3, 0, 0],
350
        'TRUNC' => [197, -1, 1, 0],
351
        'ISLOGICAL' => [198, 1, 1, 0],
352
        'DCOUNTA' => [199, 3, 0, 0],
353
        'USDOLLAR' => [204, -1, 1, 0],
354
        'FINDB' => [205, -1, 1, 0],
355
        'SEARCHB' => [206, -1, 1, 0],
356
        'REPLACEB' => [207, 4, 1, 0],
357
        'LEFTB' => [208, -1, 1, 0],
358
        'RIGHTB' => [209, -1, 1, 0],
359
        'MIDB' => [210, 3, 1, 0],
360
        'LENB' => [211, 1, 1, 0],
361
        'ROUNDUP' => [212, 2, 1, 0],
362
        'ROUNDDOWN' => [213, 2, 1, 0],
363
        'ASC' => [214, 1, 1, 0],
364
        'DBCS' => [215, 1, 1, 0],
365
        'RANK' => [216, -1, 0, 0],
366
        'ADDRESS' => [219, -1, 1, 0],
367
        'DAYS360' => [220, -1, 1, 0],
368
        'TODAY' => [221, 0, 1, 1],
369
        'VDB' => [222, -1, 1, 0],
370
        'MEDIAN' => [227, -1, 0, 0],
371
        'SUMPRODUCT' => [228, -1, 2, 0],
372
        'SINH' => [229, 1, 1, 0],
373
        'COSH' => [230, 1, 1, 0],
374
        'TANH' => [231, 1, 1, 0],
375
        'ASINH' => [232, 1, 1, 0],
376
        'ACOSH' => [233, 1, 1, 0],
377
        'ATANH' => [234, 1, 1, 0],
378
        'DGET' => [235, 3, 0, 0],
379
        'INFO' => [244, 1, 1, 1],
380
        'DB' => [247, -1, 1, 0],
381
        'FREQUENCY' => [252, 2, 0, 0],
382
        'ERROR.TYPE' => [261, 1, 1, 0],
383
        'REGISTER.ID' => [267, -1, 1, 0],
384
        'AVEDEV' => [269, -1, 0, 0],
385
        'BETADIST' => [270, -1, 1, 0],
386
        'GAMMALN' => [271, 1, 1, 0],
387
        'BETAINV' => [272, -1, 1, 0],
388
        'BINOMDIST' => [273, 4, 1, 0],
389
        'CHIDIST' => [274, 2, 1, 0],
390
        'CHIINV' => [275, 2, 1, 0],
391
        'COMBIN' => [276, 2, 1, 0],
392
        'CONFIDENCE' => [277, 3, 1, 0],
393
        'CRITBINOM' => [278, 3, 1, 0],
394
        'EVEN' => [279, 1, 1, 0],
395
        'EXPONDIST' => [280, 3, 1, 0],
396
        'FDIST' => [281, 3, 1, 0],
397
        'FINV' => [282, 3, 1, 0],
398
        'FISHER' => [283, 1, 1, 0],
399
        'FISHERINV' => [284, 1, 1, 0],
400
        'FLOOR' => [285, 2, 1, 0],
401
        'GAMMADIST' => [286, 4, 1, 0],
402
        'GAMMAINV' => [287, 3, 1, 0],
403
        'CEILING' => [288, 2, 1, 0],
404
        'HYPGEOMDIST' => [289, 4, 1, 0],
405
        'LOGNORMDIST' => [290, 3, 1, 0],
406
        'LOGINV' => [291, 3, 1, 0],
407
        'NEGBINOMDIST' => [292, 3, 1, 0],
408
        'NORMDIST' => [293, 4, 1, 0],
409
        'NORMSDIST' => [294, 1, 1, 0],
410
        'NORMINV' => [295, 3, 1, 0],
411
        'NORMSINV' => [296, 1, 1, 0],
412
        'STANDARDIZE' => [297, 3, 1, 0],
413
        'ODD' => [298, 1, 1, 0],
414
        'PERMUT' => [299, 2, 1, 0],
415
        'POISSON' => [300, 3, 1, 0],
416
        'TDIST' => [301, 3, 1, 0],
417
        'WEIBULL' => [302, 4, 1, 0],
418
        'SUMXMY2' => [303, 2, 2, 0],
419
        'SUMX2MY2' => [304, 2, 2, 0],
420
        'SUMX2PY2' => [305, 2, 2, 0],
421
        'CHITEST' => [306, 2, 2, 0],
422
        'CORREL' => [307, 2, 2, 0],
423
        'COVAR' => [308, 2, 2, 0],
424
        'FORECAST' => [309, 3, 2, 0],
425
        'FTEST' => [310, 2, 2, 0],
426
        'INTERCEPT' => [311, 2, 2, 0],
427
        'PEARSON' => [312, 2, 2, 0],
428
        'RSQ' => [313, 2, 2, 0],
429
        'STEYX' => [314, 2, 2, 0],
430
        'SLOPE' => [315, 2, 2, 0],
431
        'TTEST' => [316, 4, 2, 0],
432
        'PROB' => [317, -1, 2, 0],
433
        'DEVSQ' => [318, -1, 0, 0],
434
        'GEOMEAN' => [319, -1, 0, 0],
435
        'HARMEAN' => [320, -1, 0, 0],
436
        'SUMSQ' => [321, -1, 0, 0],
437
        'KURT' => [322, -1, 0, 0],
438
        'SKEW' => [323, -1, 0, 0],
439
        'ZTEST' => [324, -1, 0, 0],
440
        'LARGE' => [325, 2, 0, 0],
441
        'SMALL' => [326, 2, 0, 0],
442
        'QUARTILE' => [327, 2, 0, 0],
443
        'PERCENTILE' => [328, 2, 0, 0],
444
        'PERCENTRANK' => [329, -1, 0, 0],
445
        'MODE' => [330, -1, 2, 0],
446
        'TRIMMEAN' => [331, 2, 0, 0],
447
        'TINV' => [332, 2, 1, 0],
448
        'CONCATENATE' => [336, -1, 1, 0],
449
        'POWER' => [337, 2, 1, 0],
450
        'RADIANS' => [342, 1, 1, 0],
451
        'DEGREES' => [343, 1, 1, 0],
452
        'SUBTOTAL' => [344, -1, 0, 0],
453
        'SUMIF' => [345, -1, 0, 0],
454
        'COUNTIF' => [346, 2, 0, 0],
455
        'COUNTBLANK' => [347, 1, 0, 0],
456
        'ISPMT' => [350, 4, 1, 0],
457
        'DATEDIF' => [351, 3, 1, 0],
458
        'DATESTRING' => [352, 1, 1, 0],
459 116
        'NUMBERSTRING' => [353, 2, 1, 0],
460
        'ROMAN' => [354, -1, 1, 0],
461 116
        'GETPIVOTDATA' => [358, -1, 0, 0],
462
        'HYPERLINK' => [359, -1, 1, 0],
463 116
        'PHONETIC' => [360, 1, 0, 0],
464 116
        'AVERAGEA' => [361, -1, 0, 0],
465 116
        'MAXA' => [362, -1, 0, 0],
466 116
        'MINA' => [363, -1, 0, 0],
467 116
        'STDEVPA' => [364, -1, 0, 0],
468 116
        'VARPA' => [365, -1, 0, 0],
469 116
        'STDEVA' => [366, -1, 0, 0],
470
        'VARA' => [367, -1, 0, 0],
471
        'BAHTTEXT' => [368, 1, 0, 0],
472
    ];
473
474
    private Spreadsheet $spreadsheet;
475
476
    /**
477
     * The class constructor.
478
     */
479 49
    public function __construct(Spreadsheet $spreadsheet)
480
    {
481 49
        $this->spreadsheet = $spreadsheet;
482 21
483
        $this->currentCharacter = 0;
484 49
        $this->currentToken = ''; // The token we are working on.
485 44
        $this->formula = ''; // The formula to parse.
486
        $this->lookAhead = ''; // The character ahead of the current char.
487
        $this->parseTree = ''; // The parse tree to be generated.
488 47
        $this->externalSheets = [];
489 29
        $this->references = [];
490
    }
491
492 47
    /**
493
     * Convert a token to the proper ptg value.
494
     *
495
     * @param string $token the token to convert
496 47
     *
497 6
     * @return string the converted token on success
498
     */
499
    private function convert(string $token): string
500 46
    {
501 25
        if (Preg::isMatch('/"([^"]|""){0,255}"/', $token)) {
502
            return $this->convertString($token);
503
        }
504 45
        if (is_numeric($token)) {
505
            return $this->convertNumber($token);
506
        }
507
        // match references like A1 or $A$1
508 45
        if (Preg::isMatch('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) {
509 4
            return $this->convertRef2d($token);
510
        }
511
        // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
512 45
        if (Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?(\\d+)$/u', $token)) {
513 29
            return $this->convertRef3d($token);
514
        }
515
        // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
516 36
        if (self::matchCellSheetnameQuoted($token)) {
517 1
            return $this->convertRef3d($token);
518
        }
519 36
        // match ranges like A1:B2 or $A$1:$B$2
520 5
        if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
521
            return $this->convertRange2d($token);
522
        }
523
        // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
524
        if (Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)\\:\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)$/u', $token)) {
525
            return $this->convertRange3d($token);
526
        }
527
        // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
528 34
        if (self::matchRangeSheetnameQuoted($token)) {
529 33
            return $this->convertRange3d($token);
530
        }
531 2
        // operators (including parentheses)
532 1
        if (isset($this->ptg[$token])) {
533
            return pack('C', $this->ptg[$token]);
534 2
        }
535 1
        // match error codes
536
        if (Preg::isMatch('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') {
537
            return $this->convertError($token);
538
        }
539 1
        if (Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) {
540
            return $this->convertDefinedName($token);
541
        }
542
        // commented so argument number can be processed correctly. See toReversePolish().
543
        /*if (Preg::isMatch("/[A-Z0-9\xc0-\xdc\.]+/", $token))
544
        {
545
            return($this->convertFunction($token, $this->_func_args));
546
        }*/
547 44
        // if it's an argument, ignore the token (the argument remains)
548
        if ($token == 'arg') {
549
            return '';
550 44
        }
551 44
        if (Preg::isMatch('/^true$/i', $token)) {
552
            return $this->convertBool(1);
553
        }
554
        if (Preg::isMatch('/^false$/i', $token)) {
555 12
            return $this->convertBool(0);
556
        }
557
558
        // TODO: use real error codes
559 12
        throw new WriterException("Unknown token $token");
560
    }
561
562 1
    /**
563
     * Convert a number token to ptgInt or ptgNum.
564 1
     *
565
     * @param float|int|string $num an integer or double for conversion to its ptg value
566
     */
567
    private function convertNumber(mixed $num): string
568
    {
569
        // Integer in the range 0..2**16-1
570
        if ((Preg::isMatch('/^\\d+$/', (string) $num)) && ($num <= 65535)) {
571
            return pack('Cv', $this->ptg['ptgInt'], $num);
572
        }
573
574 21
        // A float
575
        if (BIFFwriter::getByteOrder()) { // if it's Big Endian
576
            $num = strrev((string) $num);
577 21
        }
578 21
579
        return pack('Cd', $this->ptg['ptgNum'], $num);
580
    }
581
582 21
    private function convertBool(int $num): string
583
    {
584
        return pack('CC', $this->ptg['ptgBool'], $num);
585
    }
586
587
    /**
588
     * Convert a string token to ptgStr.
589
     *
590
     * @param string $string a string for conversion to its ptg value
591
     *
592
     * @return string the converted token
593
     */
594 32
    private function convertString(string $string): string
595
    {
596 32
        // chop away beggining and ending quotes
597
        $string = substr($string, 1, -1);
598
        if (strlen($string) > 255) {
599 32
            throw new WriterException('String is too long');
600 13
        }
601
602
        return pack('C', $this->ptg['ptgStr']) . StringHelper::UTF8toBIFF8UnicodeShort($string);
603
    }
604 29
605
    /**
606
     * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
607
     * args that it takes.
608
     *
609
     * @param string $token the name of the function for convertion to ptg value
610
     * @param int $num_args the number of arguments the function receives
611
     *
612 25
     * @return string The packed ptg for the function
613
     */
614
    private function convertFunction(string $token, int $num_args): string
615
    {
616 25
        $args = $this->functions[$token][1];
617 25
618
        // Fixed number of args eg. TIME($i, $j, $k).
619
        if ($args >= 0) {
620
            return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]);
621
        }
622
623 25
        // Variable number of args eg. SUM($i, $j, $k, ..).
624 25
        return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]);
625
    }
626
627 25
    /**
628 25
     * Convert an Excel range such as A1:D4 to a ptgRefV.
629
     *
630
     * @param string $range An Excel range in the A1:A2
631
     */
632
    private function convertRange2d(string $range, int $class = 0): string
633
    {
634
        // TODO: possible class value 0,1,2 check Formula.pm
635
        // Split the range into 2 cell refs
636
        if (Preg::isMatch('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
637
            [$cell1, $cell2] = explode(':', $range);
638 25
        } else {
639
            // TODO: use real error codes
640
            throw new WriterException('Unknown range separator');
641
        }
642
        // Convert the cell references
643
        [$row1, $col1] = $this->cellToPackedRowcol($cell1);
644
        [$row2, $col2] = $this->cellToPackedRowcol($cell2);
645
646
        // The ptg value depends on the class of the ptg.
647
        if ($class == 0) {
648
            $ptgArea = pack('C', $this->ptg['ptgArea']);
649 4
        } elseif ($class == 1) {
650
            $ptgArea = pack('C', $this->ptg['ptgAreaV']);
651
        } elseif ($class == 2) {
652 4
            $ptgArea = pack('C', $this->ptg['ptgAreaA']);
653
        } else {
654
            // TODO: use real error codes
655 4
            throw new WriterException("Unknown class $class");
656
        }
657
658 4
        return $ptgArea . $row1 . $row2 . $col1 . $col2;
659
    }
660
661 4
    /**
662 4
     * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
663 4
     * a ptgArea3d.
664
     *
665
     * @param string $token an Excel range in the Sheet1!A1:A2 format
666
     *
667
     * @return string the packed ptgArea3d token on success
668
     */
669 4
    private function convertRange3d(string $token): string
670
    {
671 4
        // Split the ref at the ! symbol
672
        [$ext_ref, $range] = PhpspreadsheetWorksheet::extractSheetTitle($token, true);
673
674
        // Convert the external reference part (different for BIFF8)
675
        $ext_ref = $this->getRefIndex($ext_ref ?? '');
676
677
        // Split the range into 2 cell refs
678
        [$cell1, $cell2] = explode(':', $range ?? '');
679
680
        // Convert the cell references
681 29
        if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\\d+)$/', $cell1)) {
682
            [$row1, $col1] = $this->cellToPackedRowcol($cell1);
683
            [$row2, $col2] = $this->cellToPackedRowcol($cell2);
684 29
        } else { // It's a rows range (like 26:27)
685 29
            [$row1, $col1, $row2, $col2] = $this->rangeToPackedRange($cell1 . ':' . $cell2);
686
        }
687
688 29
        // The ptg value depends on the class of the ptg.
689
        $ptgArea = pack('C', $this->ptg['ptgArea3d']);
690 29
691
        return $ptgArea . $ext_ref . $row1 . $row2 . $col1 . $col2;
692
    }
693
694
    /**
695
     * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
696
     *
697
     * @param string $cell An Excel cell reference
698
     *
699
     * @return string The cell in packed() format with the corresponding ptg
700
     */
701 6
    private function convertRef2d(string $cell): string
702
    {
703
        // Convert the cell reference
704 6
        $cell_array = $this->cellToPackedRowcol($cell);
705
        [$row, $col] = $cell_array;
706
707 6
        // The ptg value depends on the class of the ptg.
708
        $ptgRef = pack('C', $this->ptg['ptgRefA']);
709
710 5
        return $ptgRef . $row . $col;
711
    }
712
713 5
    /**
714
     * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
715 5
     * ptgRef3d.
716
     *
717
     * @param string $cell An Excel cell reference
718
     *
719
     * @return string the packed ptgRef3d token on success
720
     */
721
    private function convertRef3d(string $cell): string
722
    {
723
        // Split the ref at the ! symbol
724
        [$ext_ref, $cell] = PhpspreadsheetWorksheet::extractSheetTitle($cell, true);
725 1
726
        // Convert the external reference part (different for BIFF8)
727 1
        $ext_ref = $this->getRefIndex($ext_ref ?? '');
728
729
        // Convert the cell reference part
730
        [$row, $col] = $this->cellToPackedRowcol($cell ?? '');
731
732 1
        // The ptg value depends on the class of the ptg.
733
        $ptgRef = pack('C', $this->ptg['ptgRef3dA']);
734
735 1
        return $ptgRef . $ext_ref . $row . $col;
736 1
    }
737
738
    /**
739
     * Convert an error code to a ptgErr.
740
     *
741 5
     * @param string $errorCode The error code for conversion to its ptg value
742
     *
743 5
     * @return string The error code ptgErr
744
     */
745
    private function convertError(string $errorCode): string
746
    {
747 5
        return match ($errorCode) {
748
            '#NULL!' => pack('C', 0x00),
749
            '#DIV/0!' => pack('C', 0x07),
750
            '#VALUE!' => pack('C', 0x0F),
751
            '#REF!' => pack('C', 0x17),
752
            '#NAME?' => pack('C', 0x1D),
753
            '#NUM!' => pack('C', 0x24),
754
            '#N/A' => pack('C', 0x2A),
755
            default => pack('C', 0xFF),
756
        };
757
    }
758
759
    private bool $tryDefinedName = false;
760
761
    private function convertDefinedName(string $name): string
762
    {
763 5
        if (strlen($name) > 255) {
764
            throw new WriterException('Defined Name is too long');
765
        }
766
767
        if ($this->tryDefinedName) {
768
            // @codeCoverageIgnoreStart
769
            $nameReference = 1;
770
            foreach ($this->spreadsheet->getDefinedNames() as $definedName) {
771
                if ($name === $definedName->getName()) {
772
                    break;
773
                }
774
                ++$nameReference;
775 7
            }
776
777 7
            $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference);
778 7
779
            return $ptgRef;
780
            // @codeCoverageIgnoreEnd
781 7
        }
782
783
        throw new WriterException('Cannot yet write formulae with defined names to Xls');
784
    }
785
786
    /**
787
     * Look up the REF index that corresponds to an external sheet name
788
     * (or range). If it doesn't exist yet add it to the workbook's references
789
     * array. It assumes all sheet names given must exist.
790
     *
791
     * @param string $ext_ref The name of the external reference
792
     *
793
     * @return string The reference index in packed() format on success
794
     */
795
    private function getRefIndex(string $ext_ref): string
796
    {
797
        $ext_ref = Preg::replace(["/^'/", "/'$/"], ['', ''], $ext_ref); // Remove leading and trailing ' if any.
798 7
        $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
799 7
800 1
        // Check if there is a sheet range eg., Sheet1:Sheet2.
801
        if (Preg::isMatch('/:/', $ext_ref)) {
802 6
            [$sheet_name1, $sheet_name2] = explode(':', $ext_ref);
803
804
            $sheet1 = $this->getSheetIndex($sheet_name1);
805
            if ($sheet1 == -1) {
806 6
                throw new WriterException("Unknown sheet name $sheet_name1 in formula");
807 6
            }
808 6
            $sheet2 = $this->getSheetIndex($sheet_name2);
809 6
            if ($sheet2 == -1) {
810 6
                throw new WriterException("Unknown sheet name $sheet_name2 in formula");
811 6
            }
812 6
813
            // Reverse max and min sheet numbers if necessary
814 6
            if ($sheet1 > $sheet2) {
815
                [$sheet1, $sheet2] = [$sheet2, $sheet1];
816
            }
817
        } else { // Single sheet name only.
818 6
            $sheet1 = $this->getSheetIndex($ext_ref);
819
            if ($sheet1 == -1) {
820
                throw new WriterException("Unknown sheet name $ext_ref in formula");
821
            }
822
            $sheet2 = $sheet1;
823 6
        }
824
825
        // assume all references belong to this document
826
        $supbook_index = 0x00;
827
        $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
828
        $totalreferences = count($this->references);
829
        $index = -1;
830
        for ($i = 0; $i < $totalreferences; ++$i) {
831
            if ($ref == $this->references[$i]) {
832
                $index = $i;
833
834
                break;
835 7
            }
836
        }
837 7
        // if REF was not found add it to references array
838 1
        if ($index == -1) {
839
            $this->references[$totalreferences] = $ref;
840
            $index = $totalreferences;
841 6
        }
842
843
        return pack('v', $index);
844
    }
845
846
    /**
847
     * Look up the index that corresponds to an external sheet name. The hash of
848
     * sheet names is updated by the addworksheet() method of the
849
     * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
850
     *
851
     * @param string $sheet_name Sheet name
852
     *
853
     * @return int The sheet index, -1 if the sheet was not found
854 111
     */
855
    private function getSheetIndex(string $sheet_name): int
856 111
    {
857
        if (!isset($this->externalSheets[$sheet_name])) {
858
            return -1;
859
        }
860
861
        return $this->externalSheets[$sheet_name];
862
    }
863
864
    /**
865
     * This method is used to update the array of sheet names. It is
866 38
     * called by the addWorksheet() method of the
867
     * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
868 38
     *
869 38
     * @param string $name The name of the worksheet being added
870 38
     * @param int $index The index of the worksheet being added
871
     *
872
     * @see Workbook::addWorksheet
873 38
     */
874
    public function setExtSheet(string $name, int $index): void
875
    {
876
        $this->externalSheets[$name] = $index;
877
    }
878 38
879 38
    /**
880 38
     * pack() row and column into the required 3 or 4 byte format.
881
     *
882 38
     * @param string $cell The Excel cell reference to be packed
883
     *
884 38
     * @return array Array containing the row and column in packed() format
885
     */
886
    private function cellToPackedRowcol(string $cell): array
887
    {
888
        $cell = strtoupper($cell);
889
        [$row, $col, $row_rel, $col_rel] = $this->cellToRowcol($cell);
890
        if ($col >= 256) {
891
            throw new WriterException("Column in: $cell greater than 255");
892
        }
893
        if ($row >= 65536) {
894
            throw new WriterException("Row in: $cell greater than 65536 ");
895
        }
896
897
        // Set the high bits to indicate if row or col are relative.
898
        $col |= $col_rel << 14;
899
        $col |= $row_rel << 15;
900
        $col = pack('v', $col);
901
902
        $row = pack('v', $row);
903
904
        return [$row, $col];
905
    }
906
907
    /**
908
     * pack() row range into the required 3 or 4 byte format.
909
     * Just using maximum col/rows, which is probably not the correct solution.
910
     *
911
     * @param string $range The Excel range to be packed
912
     *
913
     * @return array Array containing (row1,col1,row2,col2) in packed() format
914
     */
915
    private function rangeToPackedRange(string $range): array
916
    {
917
        if (!Preg::isMatch('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match)) {
918
            // @codeCoverageIgnoreStart
919
            throw new WriterException('Regexp failure in rangeToPackedRange');
920
            // @codeCoverageIgnoreEnd
921
        }
922
        // return absolute rows if there is a $ in the ref
923
        $row1_rel = empty($match[1]) ? 1 : 0;
924
        $row1 = $match[2];
925
        $row2_rel = empty($match[3]) ? 1 : 0;
926
        $row2 = $match[4];
927
        // Convert 1-index to zero-index
928
        --$row1;
929
        --$row2;
930
        // Trick poor inocent Excel
931
        $col1 = 0;
932
        $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!)
933
934
        // FIXME: this changes for BIFF8
935
        if (($row1 >= 65536) || ($row2 >= 65536)) {
936
            throw new WriterException("Row in: $range greater than 65536 ");
937
        }
938 38
939
        // Set the high bits to indicate if rows are relative.
940 38
        $col1 |= $row1_rel << 15;
941
        $col2 |= $row2_rel << 15;
942
        $col1 = pack('v', $col1);
943
        $col2 = pack('v', $col2);
944
945
        $row1 = pack('v', $row1);
946 38
        $row2 = pack('v', $row2);
947 38
948 38
        return [$row1, $col1, $row2, $col2];
949 38
    }
950
951
    /**
952 38
     * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
953 38
     * indexed row and column number. Also returns two (0,1) values to indicate
954 38
     * whether the row or column are relative references.
955 38
     *
956 38
     * @param string $cell the Excel cell reference in A1 format
957 38
     */
958
    private function cellToRowcol(string $cell): array
959
    {
960
        if (!Preg::isMatch('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match)) {
961 38
            // @codeCoverageIgnoreStart
962 38
            throw new WriterException('Regexp failure in cellToRowcol');
963
            // @codeCoverageIgnoreEnd
964 38
        }
965
        // return absolute column if there is a $ in the ref
966
        $col_rel = empty($match[1]) ? 1 : 0;
967
        $col_ref = $match[2];
968
        $row_rel = empty($match[3]) ? 1 : 0;
969
        $row = $match[4];
970 47
971
        // Convert base26 column string to a number.
972 47
        $expn = strlen($col_ref) - 1;
973 47
        $col = 0;
974 47
        $col_ref_length = strlen($col_ref);
975
        for ($i = 0; $i < $col_ref_length; ++$i) {
976 47
            $col += (ord($col_ref[$i]) - 64) * 26 ** $expn;
977 47
            --$expn;
978 4
        }
979
980
        // Convert 1-index to zero-index
981 47
        --$row;
982 46
        --$col;
983
984 47
        return [$row, $col, $row_rel, $col_rel];
985
    }
986
987 47
    /**
988 47
     * Advance to the next valid token.
989
     */
990 47
    private function advance(): void
991 46
    {
992
        $token = '';
993 47
        $i = $this->currentCharacter;
994
        $formula_length = strlen($this->formula);
995
        // eat up white spaces
996 47
        if ($i < $formula_length) {
997 47
            while ($this->formula[$i] == ' ') {
998 47
                ++$i;
999
            }
1000 47
1001
            if ($i < ($formula_length - 1)) {
1002
                $this->lookAhead = $this->formula[$i + 1];
1003 46
            }
1004 43
            $token = '';
1005
        }
1006 32
1007
        while ($i < $formula_length) {
1008 46
            $token .= $this->formula[$i];
1009
1010
            if ($i < ($formula_length - 1)) {
1011
                $this->lookAhead = $this->formula[$i + 1];
1012
            } else {
1013
                $this->lookAhead = '';
1014
            }
1015
1016
            if ($this->match($token) != '') {
1017
                $this->currentCharacter = $i + 1;
1018
                $this->currentToken = $token;
1019 47
1020
                return;
1021
            }
1022 47
1023 47
            if ($i < ($formula_length - 2)) {
1024 47
                $this->lookAhead = $this->formula[$i + 2];
1025 47
            } else { // if we run out of characters lookAhead becomes empty
1026 47
                $this->lookAhead = '';
1027 47
            }
1028 47
            ++$i;
1029 47
        }
1030 47
    }
1031 47
1032 47
    /**
1033 47
     * Checks if it's a valid token.
1034 47
     *
1035 47
     * @param string $token the token to check
1036 47
     *
1037 44
     * @return string The checked token or empty string on failure
1038
     */
1039 47
    private function match(string $token): string
1040 2
    {
1041 1
        switch ($token) {
1042
            case '+':
1043
            case '-':
1044 2
            case '*':
1045
            case '/':
1046 47
            case '(':
1047
            case ')':
1048 8
            case ',':
1049 8
            case ';':
1050
            case '>=':
1051
            case '<=':
1052 1
            case '=':
1053
            case '<>':
1054
            case '^':
1055
            case '&':
1056 47
            case '%':
1057 29
                return $token;
1058
1059
            case '>':
1060 47
                if ($this->lookAhead === '=') { // it's a GE token
1061
                    break;
1062
                }
1063
1064 47
                return $token;
1065 6
1066
            case '<':
1067
                // it's a LE or a NE token
1068 47
                if (($this->lookAhead === '=') || ($this->lookAhead === '>')) {
1069 25
                    break;
1070
                }
1071
1072 47
                return $token;
1073
        }
1074
1075
        // if it's a reference A1 or $A$1 or $A1 or A$1
1076 47
        if (
1077 4
            Preg::isMatch('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token)
1078
            && !Preg::isMatch('/\d/', $this->lookAhead)
1079
            && ($this->lookAhead !== ':')
1080 47
            && ($this->lookAhead !== '.')
1081 29
            && ($this->lookAhead !== '!')
1082
        ) {
1083 46
            return $token;
1084
        }
1085 21
        // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1086
        if (
1087
            Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $token)
1088 46
            && !Preg::isMatch('/\d/', $this->lookAhead)
1089 1
            && ($this->lookAhead !== ':')
1090
            && ($this->lookAhead !== '.')
1091
        ) {
1092 46
            return $token;
1093 33
        }
1094
        // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1095 46
        if (
1096 5
            self::matchCellSheetnameQuoted($token)
1097
            && !Preg::isMatch('/\\d/', $this->lookAhead)
1098 46
            && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')
1099 1
        ) {
1100
            return $token;
1101 46
        }
1102 1
        // if it's a range A1:A2 or $A$1:$A$2
1103
        if (
1104 46
            Preg::isMatch(
1105
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1106
                $token
1107 1
            )
1108
            && !Preg::isMatch('/\d/', $this->lookAhead)
1109
        ) {
1110 46
            return $token;
1111
        }
1112
        // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
1113
        if (
1114
            Preg::isMatch(
1115
                '/^'
1116
                . self::REGEX_SHEET_TITLE_UNQUOTED
1117
                . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED
1118
                . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u',
1119
                $token
1120
            )
1121 47
            && !Preg::isMatch('/\d/', $this->lookAhead)
1122
        ) {
1123 47
            return $token;
1124 47
        }
1125 47
        // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
1126 47
        if (
1127 47
            self::matchRangeSheetnameQuoted($token)
1128
            && !Preg::isMatch('/\\d/', $this->lookAhead)
1129 47
        ) {
1130
            return $token;
1131
        }
1132
        // If it's a number (check that it's not a sheet name or range)
1133
        if (is_numeric($token) && (!is_numeric($token . $this->lookAhead) || ($this->lookAhead == '')) && ($this->lookAhead !== '!') && ($this->lookAhead !== ':')) {
1134
            return $token;
1135
        }
1136
        if (
1137
            Preg::isMatch('/"([^"]|""){0,255}"/', $token)
1138 47
            && $this->lookAhead !== '"'
1139
            && (substr_count($token, '"') % 2 == 0)
1140 47
        ) {
1141 47
            // If it's a string (of maximum 255 characters)
1142 1
            return $token;
1143 1
        }
1144 1
        // If it's an error code
1145 47
        if (
1146 2
            Preg::isMatch('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token)
1147 2
            || $token === '#N/A'
1148 2
        ) {
1149 47
            return $token;
1150 2
        }
1151 2
        // if it's a function call
1152 2
        if (
1153 47
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token)
1154 1
            && ($this->lookAhead === '(')
1155 1
        ) {
1156 1
            return $token;
1157 47
        }
1158 4
        if (
1159 4
            Preg::isMatch(
1160 4
                '/^'
1161 47
                . Calculation::CALCULATION_REGEXP_DEFINEDNAME
1162 7
                . '$/miu',
1163 7
                $token
1164 7
            )
1165
            && $this->spreadsheet->getDefinedName($token) !== null
1166
        ) {
1167 47
            return $token;
1168
        }
1169
        if (
1170
            Preg::isMatch('/^true$/i', $token)
1171
            && ($this->lookAhead === ')' || $this->lookAhead === ',')
1172
        ) {
1173
            return $token;
1174
        }
1175
        if (
1176
            Preg::isMatch('/^false$/i', $token)
1177
            && ($this->lookAhead === ')' || $this->lookAhead === ',')
1178
        ) {
1179
            return $token;
1180 47
        }
1181
        if (str_ends_with($token, ')')) {
1182
            //    It's an argument of some description (e.g. a named range),
1183 47
            //        precise nature yet to be determined
1184 21
            return $token;
1185 21
        }
1186
1187 7
        return '';
1188
    }
1189 21
1190 21
    /**
1191
     * The parsing method. It parses a formula.
1192 21
     *
1193 47
     * @param string $formula the formula to parse, without the initial equal
1194 1
     *                        sign (=)
1195 1
     *
1196
     * @return bool true on success
1197 1
     */
1198 47
    public function parse(string $formula): bool
1199
    {
1200 6
        $this->currentCharacter = 0;
1201 6
        $this->formula = (string) $formula;
1202
        $this->lookAhead = $formula[1] ?? '';
1203 6
        $this->advance();
1204 47
        $this->parseTree = $this->condition();
1205
1206 1
        return true;
1207 1
    }
1208
1209 1
    /**
1210
     * It parses a condition. It assumes the following rule:
1211 47
     * Cond -> Expr [(">" | "<") Expr].
1212 47
     *
1213 8
     * @return array The parsed ptg'd tree on success
1214 8
     */
1215 8
    private function condition(): array
1216
    {
1217
        $result = $this->expression();
1218 47
        if ($this->currentToken == '<') {
1219 47
            $this->advance();
1220 47
            $result2 = $this->expression();
1221
            $result = $this->createTree('ptgLT', $result, $result2);
1222 21
        } elseif ($this->currentToken == '>') {
1223 21
            $this->advance();
1224 21
            $result2 = $this->expression();
1225 21
            $result = $this->createTree('ptgGT', $result, $result2);
1226 6
        } elseif ($this->currentToken == '<=') {
1227 6
            $this->advance();
1228 6
            $result2 = $this->expression();
1229 6
            $result = $this->createTree('ptgLE', $result, $result2);
1230
        } elseif ($this->currentToken == '>=') {
1231 1
            $this->advance();
1232 1
            $result2 = $this->expression();
1233 1
            $result = $this->createTree('ptgGE', $result, $result2);
1234
        } elseif ($this->currentToken == '=') {
1235
            $this->advance();
1236
            $result2 = $this->expression();
1237 47
            $result = $this->createTree('ptgEQ', $result, $result2);
1238
        } elseif ($this->currentToken == '<>') {
1239
            $this->advance();
1240
            $result2 = $this->expression();
1241
            $result = $this->createTree('ptgNE', $result, $result2);
1242
        }
1243
1244
        return $result;
1245
    }
1246
1247
    /**
1248 3
     * It parses a expression. It assumes the following rule:
1249
     * Expr -> Term [("+" | "-") Term]
1250 3
     *      -> "string"
1251
     *      -> "-" Term : Negative value
1252
     *      -> "+" Term : Positive value
1253
     *      -> Error code.
1254
     *
1255
     * @return array The parsed ptg'd tree on success
1256
     */
1257
    private function expression(): array
1258
    {
1259 47
        // If it's a string return a string node
1260
        if (Preg::isMatch('/"([^"]|""){0,255}"/', $this->currentToken)) {
1261 47
            $tmp = str_replace('""', '"', $this->currentToken);
1262
            if (($tmp == '"') || ($tmp == '')) {
1263 47
                //    Trap for "" that has been used for an empty string
1264 47
                $tmp = '""';
1265
            }
1266 17
            $result = $this->createTree($tmp, '', '');
1267 16
            $this->advance();
1268 16
1269 16
            return $result;
1270
        }
1271 4
        if (
1272 4
            Preg::isMatch('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $this->currentToken)
1273 4
            || $this->currentToken == '#N/A'
1274
        ) { // error code
1275
            $result = $this->createTree($this->currentToken, 'ptgErr', '');
1276
            $this->advance();
1277 47
1278
            return $result;
1279
        }
1280
        if ($this->currentToken == '-') { // negative value
1281
            // catch "-" Term
1282
            $this->advance();
1283
            $result2 = $this->expression();
1284
1285
            return $this->createTree('ptgUminus', $result2, '');
1286
        } elseif ($this->currentToken == '+') { // positive value
1287
            // catch "+" Term
1288
            $this->advance();
1289
            $result2 = $this->expression();
1290 47
1291
            return $this->createTree('ptgUplus', $result2, '');
1292 47
        }
1293 47
        $result = $this->term();
1294 3
        while ($this->currentToken === '&') {
1295 3
            $this->advance();
1296 3
            $result2 = $this->expression();
1297
            $result = $this->createTree('ptgConcat', $result, $result2);
1298
        }
1299 3
        while (
1300
            ($this->currentToken == '+')
1301 3
            || ($this->currentToken == '-')
1302
            || ($this->currentToken == '^')
1303
        ) {
1304 47
            if ($this->currentToken == '+') {
1305 29
                $this->advance();
1306 29
                $result2 = $this->term();
1307
                $result = $this->createTree('ptgAdd', $result, $result2);
1308 29
            } elseif ($this->currentToken == '-') {
1309
                $this->advance();
1310 44
                $result2 = $this->term();
1311
                $result = $this->createTree('ptgSub', $result, $result2);
1312
            } else {
1313
                $this->advance();
1314
                $result2 = $this->term();
1315
                $result = $this->createTree('ptgPower', $result, $result2);
1316
            }
1317 44
        }
1318
1319 6
        return $result;
1320 6
    }
1321
1322 6
    /**
1323
     * This function just introduces a ptgParen element in the tree, so that Excel
1324
     * doesn't get confused when working with a parenthesized formula afterwards.
1325 43
     *
1326 43
     * @return array The parsed ptg'd tree
1327
     *
1328
     * @see fact()
1329
     */
1330 25
    private function parenthesizedExpression(): array
1331 25
    {
1332
        return $this->createTree('ptgParen', $this->expression(), '');
1333 25
    }
1334
1335 43
    /**
1336
     * It parses a term. It assumes the following rule:
1337
     * Term -> Fact [("*" | "/") Fact].
1338
     *
1339
     * @return array The parsed ptg'd tree on success
1340
     */
1341
    private function term(): array
1342
    {
1343 43
        $result = $this->fact();
1344
        while (
1345
            ($this->currentToken == '*')
1346 4
            || ($this->currentToken == '/')
1347 4
        ) {
1348
            if ($this->currentToken == '*') {
1349 4
                $this->advance();
1350
                $result2 = $this->fact();
1351 43
                $result = $this->createTree('ptgMul', $result, $result2);
1352
            } else {
1353 29
                $this->advance();
1354 1
                $result2 = $this->fact();
1355 1
                $result = $this->createTree('ptgDiv', $result, $result2);
1356
            }
1357 29
        }
1358
1359 29
        return $result;
1360
    }
1361 29
1362
    /**
1363 35
     * It parses a factor. It assumes the following rule:
1364
     * Fact -> ( Expr )
1365 33
     *       | CellRef
1366
     *       | CellRange
1367 7
     *       | Number
1368 5
     *       | Function.
1369 5
     *
1370
     * @return array The parsed ptg'd tree on success
1371 5
     */
1372
    private function fact(): array
1373 2
    {
1374 1
        $currentToken = $this->currentToken;
1375 1
        if ($currentToken === '(') {
1376
            $this->advance(); // eat the "("
1377 1
            $result = $this->parenthesizedExpression();
1378
            if ($this->currentToken !== ')') {
1379
                throw new WriterException("')' token expected.");
1380 1
            }
1381
            $this->advance(); // eat the ")"
1382
1383
            return $result;
1384
        }
1385
        // if it's a reference
1386
        if (Preg::isMatch('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $this->currentToken)) {
1387
            $result = $this->createTree($this->currentToken, '', '');
1388
            $this->advance();
1389 33
1390
            return $result;
1391 33
        }
1392 33
        if (
1393 33
            Preg::isMatch(
1394 33
                '/^'
1395 33
                . self::REGEX_SHEET_TITLE_UNQUOTED
1396 33
                . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED
1397 33
                . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u',
1398 19
                $this->currentToken
1399 19
            )
1400
        ) {
1401
            // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1402
            $result = $this->createTree($this->currentToken, '', '');
1403 19
            $this->advance();
1404 19
1405
            return $result;
1406 33
        }
1407 33
        if (self::matchCellSheetnameQuoted($this->currentToken)) {
1408
            // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1409 33
            $result = $this->createTree($this->currentToken, '', '');
1410
            $this->advance();
1411 33
1412 3
            return $result;
1413
        }
1414 33
        if (
1415
            Preg::isMatch(
1416 33
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1417
                $this->currentToken
1418
            )
1419
            || Preg::isMatch(
1420 33
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1421 33
                $this->currentToken
1422
            )
1423 33
        ) {
1424
            // if it's a range A1:B2 or $A$1:$B$2
1425
            // must be an error?
1426
            $result = $this->createTree($this->currentToken, '', '');
1427
            $this->advance();
1428
1429
            return $result;
1430
        }
1431
        if (
1432
            Preg::isMatch(
1433
                '/^'
1434
                . self::REGEX_SHEET_TITLE_UNQUOTED
1435
                . '(\\:'
1436 47
                . self::REGEX_SHEET_TITLE_UNQUOTED
1437
                . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u',
1438 47
                $this->currentToken
1439
            )
1440
        ) {
1441
            // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2)
1442
            // must be an error?
1443
            $result = $this->createTree($this->currentToken, '', '');
1444
            $this->advance();
1445
1446
            return $result;
1447
        }
1448
        if (self::matchRangeSheetnameQuoted($this->currentToken)) {
1449
            // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2)
1450
            // must be an error?
1451
            $result = $this->createTree($this->currentToken, '', '');
1452
            $this->advance();
1453
1454
            return $result;
1455
        }
1456
        if (is_numeric($this->currentToken)) {
1457
            // If it's a number or a percent
1458
            if ($this->lookAhead === '%') {
1459
                $result = $this->createTree('ptgPercent', $this->currentToken, '');
1460
                $this->advance(); // Skip the percentage operator once we've pre-built that tree
1461
            } else {
1462
                $result = $this->createTree($this->currentToken, '', '');
1463
            }
1464
            $this->advance();
1465
1466
            return $result;
1467
        }
1468 51
        if (
1469
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken)
1470 51
            && ($this->lookAhead === '(')
1471 51
        ) {
1472 48
            // if it's a function call
1473
            return $this->func();
1474 51
        }
1475 2
        if (
1476
            Preg::isMatch(
1477
                '/^'
1478 49
                . Calculation::CALCULATION_REGEXP_DEFINEDNAME
1479 44
                . '$/miu',
1480 44
                $this->currentToken
1481 49
            )
1482 8
            && $this->spreadsheet->getDefinedName($this->currentToken) !== null
1483 3
        ) {
1484
            $result = $this->createTree('ptgName', $this->currentToken, '');
1485 49
            $this->advance();
1486 43
1487 42
            return $result;
1488 49
        }
1489 34
        if (Preg::isMatch('/^true|false$/i', $this->currentToken)) {
1490 34
            $result = $this->createTree($this->currentToken, '', '');
1491
            $this->advance();
1492
1493
            return $result;
1494 49
        }
1495 49
1496 49
        throw new WriterException('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter);
1497 49
    }
1498 49
1499
    /**
1500
     * It parses a function call. It assumes the following rule:
1501 32
     * Func -> ( Expr [,Expr]* ).
1502 32
     *
1503
     * @return array The parsed ptg'd tree on success
1504 8
     */
1505
    private function func(): array
1506
    {
1507
        $num_args = 0; // number of arguments received
1508 32
        $function = strtoupper($this->currentToken);
1509
        $result = ''; // initialize result
1510 49
        $this->advance();
1511
        $this->advance(); // eat the "("
1512 47
        while ($this->currentToken !== ')') {
1513
            if ($num_args > 0) {
1514
                if ($this->currentToken === ',' || $this->currentToken === ';') {
1515
                    $this->advance(); // eat the "," or ";"
1516
                } else {
1517
                    throw new WriterException("Syntax error: comma expected in function $function, arg #{$num_args}");
1518
                }
1519
                $result2 = $this->condition();
1520
                $result = $this->createTree('arg', $result, $result2);
1521
            } else { // first argument
1522
                $result2 = $this->condition();
1523
                $result = $this->createTree('arg', '', $result2);
1524
            }
1525
            ++$num_args;
1526
        }
1527
        if (!isset($this->functions[$function])) {
1528
            throw new WriterException("Function $function() doesn't exist");
1529
        }
1530
        $args = $this->functions[$function][1];
1531
        // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid.
1532
        if (($args >= 0) && ($args != $num_args)) {
1533
            throw new WriterException("Incorrect number of arguments in function $function() ");
1534
        }
1535
1536
        $result = $this->createTree($function, $result, $num_args);
1537
        $this->advance(); // eat the ")"
1538
1539
        return $result;
1540
    }
1541
1542
    /**
1543
     * Creates a tree. In fact an array which may have one or two arrays (sub-trees)
1544
     * as elements.
1545
     *
1546
     * @param mixed $value the value of this node
1547
     * @param mixed $left the left array (sub-tree) or a final node
1548
     * @param mixed $right the right array (sub-tree) or a final node
1549
     *
1550
     * @return array A tree
1551
     */
1552
    private function createTree(mixed $value, mixed $left, mixed $right): array
1553
    {
1554
        return ['value' => $value, 'left' => $left, 'right' => $right];
1555
    }
1556
1557
    /**
1558
     * Builds a string containing the tree in reverse polish notation (What you
1559
     * would use in a HP calculator stack).
1560
     * The following tree:.
1561
     *
1562
     *    +
1563
     *   / \
1564
     *  2   3
1565
     *
1566
     * produces: "23+"
1567
     *
1568
     * The following tree:
1569
     *
1570
     *    +
1571
     *   / \
1572
     *  3   *
1573
     *     / \
1574
     *    6   A1
1575
     *
1576
     * produces: "36A1*+"
1577
     *
1578
     * In fact all operands, functions, references, etc... are written as ptg's
1579
     *
1580
     * @param array $tree the optional tree to convert
1581
     *
1582
     * @return string The tree in reverse polish notation
1583
     */
1584
    public function toReversePolish(array $tree = []): string
1585
    {
1586
        $polish = ''; // the string we are going to return
1587
        if (empty($tree)) { // If it's the first call use parseTree
1588
            $tree = $this->parseTree;
1589
        }
1590
        if (!is_array($tree) || !isset($tree['left'], $tree['right'], $tree['value'])) {
1591
            throw new WriterException('Unexpected non-array');
1592
        }
1593
1594
        if (is_array($tree['left'])) {
1595
            $converted_tree = $this->toReversePolish($tree['left']);
1596
            $polish .= $converted_tree;
1597
        } elseif ($tree['left'] != '') { // It's a final node
1598
            $converted_tree = $this->convert($tree['left']);
1599
            $polish .= $converted_tree;
1600
        }
1601
        if (is_array($tree['right'])) {
1602
            $converted_tree = $this->toReversePolish($tree['right']);
1603
            $polish .= $converted_tree;
1604
        } elseif ($tree['right'] != '') { // It's a final node
1605
            $converted_tree = $this->convert($tree['right']);
1606
            $polish .= $converted_tree;
1607
        }
1608
        // if it's a function convert it here (so we can set it's arguments)
1609
        if (
1610
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/", $tree['value'])
1611
            && !Preg::isMatch('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value'])
1612
            && !Preg::isMatch(
1613
                '/^[A-Ia-i]?[A-Za-z](\\d+)\\.\\.[A-Ia-i]?[A-Za-z](\\d+)$/',
1614
                $tree['value']
1615
            )
1616
            && !is_numeric($tree['value'])
1617
            && !isset($this->ptg[$tree['value']])
1618
        ) {
1619
            // left subtree for a function is always an array.
1620
            if ($tree['left'] != '') {
1621
                $left_tree = $this->toReversePolish($tree['left']);
1622
            } else {
1623
                $left_tree = '';
1624
            }
1625
1626
            // add its left subtree and return.
1627
            return $left_tree . $this->convertFunction($tree['value'], $tree['right']);
1628
        }
1629
        $converted_tree = $this->convert($tree['value']);
1630
1631
        return $polish . $converted_tree;
1632
    }
1633
1634
    public static function matchCellSheetnameQuoted(string $token): bool
1635
    {
1636
        return Preg::isMatch(
1637
            self::REGEX_CELL_TITLE_QUOTED,
1638
            $token
1639
        );
1640
    }
1641
1642
    public static function matchRangeSheetnameQuoted(string $token): bool
1643
    {
1644
        return Preg::isMatch(
1645
            self::REGEX_RANGE_TITLE_QUOTED,
1646
            $token
1647
        );
1648
    }
1649
}
1650