Passed
Pull Request — master (#4323)
by Owen
17:30 queued 06:07
created

Parser::matchCellSheetnameQuoted()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
rs 10
ccs 4
cts 4
cp 1
cc 1
nc 1
nop 1
crap 1
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
        'NUMBERSTRING' => [353, 2, 1, 0],
460
        'ROMAN' => [354, -1, 1, 0],
461
        'GETPIVOTDATA' => [358, -1, 0, 0],
462
        'HYPERLINK' => [359, -1, 1, 0],
463
        'PHONETIC' => [360, 1, 0, 0],
464
        'AVERAGEA' => [361, -1, 0, 0],
465
        'MAXA' => [362, -1, 0, 0],
466
        'MINA' => [363, -1, 0, 0],
467
        'STDEVPA' => [364, -1, 0, 0],
468
        'VARPA' => [365, -1, 0, 0],
469
        '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 116
    public function __construct(Spreadsheet $spreadsheet)
480
    {
481 116
        $this->spreadsheet = $spreadsheet;
482
483 116
        $this->currentCharacter = 0;
484 116
        $this->currentToken = ''; // The token we are working on.
485 116
        $this->formula = ''; // The formula to parse.
486 116
        $this->lookAhead = ''; // The character ahead of the current char.
487 116
        $this->parseTree = ''; // The parse tree to be generated.
488 116
        $this->externalSheets = [];
489 116
        $this->references = [];
490
    }
491
492
    /**
493
     * Convert a token to the proper ptg value.
494
     *
495
     * @param string $token the token to convert
496
     *
497
     * @return string the converted token on success
498
     */
499 49
    private function convert(string $token): string
500
    {
501 49
        if (Preg::isMatch('/"([^"]|""){0,255}"/', $token)) {
502 21
            return $this->convertString($token);
503
        }
504 49
        if (is_numeric($token)) {
505 44
            return $this->convertNumber($token);
506
        }
507
        // match references like A1 or $A$1
508 47
        if (Preg::isMatch('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) {
509 29
            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 47
        if (Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?(\\d+)$/u', $token)) {
513
            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 47
        if (self::matchCellSheetnameQuoted($token)) {
517 6
            return $this->convertRef3d($token);
518
        }
519
        // match ranges like A1:B2 or $A$1:$B$2
520 46
        if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
521 25
            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 45
        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 45
        if (self::matchRangeSheetnameQuoted($token)) {
529 4
            return $this->convertRange3d($token);
530
        }
531
        // operators (including parentheses)
532 45
        if (isset($this->ptg[$token])) {
533 29
            return pack('C', $this->ptg[$token]);
534
        }
535
        // match error codes
536 36
        if (Preg::isMatch('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') {
537 1
            return $this->convertError($token);
538
        }
539 36
        if (Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) {
540 5
            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
        // if it's an argument, ignore the token (the argument remains)
548 34
        if ($token == 'arg') {
549 33
            return '';
550
        }
551 2
        if (Preg::isMatch('/^true$/i', $token)) {
552 1
            return $this->convertBool(1);
553
        }
554 2
        if (Preg::isMatch('/^false$/i', $token)) {
555 1
            return $this->convertBool(0);
556
        }
557
558
        // TODO: use real error codes
559 1
        throw new WriterException("Unknown token $token");
560
    }
561
562
    /**
563
     * Convert a number token to ptgInt or ptgNum.
564
     *
565
     * @param float|int|string $num an integer or double for conversion to its ptg value
566
     */
567 44
    private function convertNumber(mixed $num): string
568
    {
569
        // Integer in the range 0..2**16-1
570 44
        if ((Preg::isMatch('/^\\d+$/', (string) $num)) && ($num <= 65535)) {
571 44
            return pack('Cv', $this->ptg['ptgInt'], $num);
572
        }
573
574
        // A float
575 12
        if (BIFFwriter::getByteOrder()) { // if it's Big Endian
576
            $num = strrev((string) $num);
577
        }
578
579 12
        return pack('Cd', $this->ptg['ptgNum'], $num);
580
    }
581
582 1
    private function convertBool(int $num): string
583
    {
584 1
        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 21
    private function convertString(string $string): string
595
    {
596
        // chop away beggining and ending quotes
597 21
        $string = substr($string, 1, -1);
598 21
        if (strlen($string) > 255) {
599
            throw new WriterException('String is too long');
600
        }
601
602 21
        return pack('C', $this->ptg['ptgStr']) . StringHelper::UTF8toBIFF8UnicodeShort($string);
603
    }
604
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
     * @return string The packed ptg for the function
613
     */
614 32
    private function convertFunction(string $token, int $num_args): string
615
    {
616 32
        $args = $this->functions[$token][1];
617
618
        // Fixed number of args eg. TIME($i, $j, $k).
619 32
        if ($args >= 0) {
620 13
            return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]);
621
        }
622
623
        // Variable number of args eg. SUM($i, $j, $k, ..).
624 29
        return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]);
625
    }
626
627
    /**
628
     * 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 25
    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 25
        if (Preg::isMatch('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
637 25
            [$cell1, $cell2] = explode(':', $range);
638
        } else {
639
            // TODO: use real error codes
640
            throw new WriterException('Unknown range separator');
641
        }
642
        // Convert the cell references
643 25
        [$row1, $col1] = $this->cellToPackedRowcol($cell1);
644 25
        [$row2, $col2] = $this->cellToPackedRowcol($cell2);
645
646
        // The ptg value depends on the class of the ptg.
647 25
        if ($class == 0) {
648 25
            $ptgArea = pack('C', $this->ptg['ptgArea']);
649
        } elseif ($class == 1) {
650
            $ptgArea = pack('C', $this->ptg['ptgAreaV']);
651
        } elseif ($class == 2) {
652
            $ptgArea = pack('C', $this->ptg['ptgAreaA']);
653
        } else {
654
            // TODO: use real error codes
655
            throw new WriterException("Unknown class $class");
656
        }
657
658 25
        return $ptgArea . $row1 . $row2 . $col1 . $col2;
659
    }
660
661
    /**
662
     * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
663
     * 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
        // Split the ref at the ! symbol
672 4
        [$ext_ref, $range] = PhpspreadsheetWorksheet::extractSheetTitle($token, true);
673
674
        // Convert the external reference part (different for BIFF8)
675 4
        $ext_ref = $this->getRefIndex($ext_ref ?? '');
676
677
        // Split the range into 2 cell refs
678 4
        [$cell1, $cell2] = explode(':', $range ?? '');
679
680
        // Convert the cell references
681 4
        if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\\d+)$/', $cell1)) {
682 4
            [$row1, $col1] = $this->cellToPackedRowcol($cell1);
683 4
            [$row2, $col2] = $this->cellToPackedRowcol($cell2);
684
        } else { // It's a rows range (like 26:27)
685
            [$row1, $col1, $row2, $col2] = $this->rangeToPackedRange($cell1 . ':' . $cell2);
686
        }
687
688
        // The ptg value depends on the class of the ptg.
689 4
        $ptgArea = pack('C', $this->ptg['ptgArea3d']);
690
691 4
        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 29
    private function convertRef2d(string $cell): string
702
    {
703
        // Convert the cell reference
704 29
        $cell_array = $this->cellToPackedRowcol($cell);
705 29
        [$row, $col] = $cell_array;
706
707
        // The ptg value depends on the class of the ptg.
708 29
        $ptgRef = pack('C', $this->ptg['ptgRefA']);
709
710 29
        return $ptgRef . $row . $col;
711
    }
712
713
    /**
714
     * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
715
     * ptgRef3d.
716
     *
717
     * @param string $cell An Excel cell reference
718
     *
719
     * @return string the packed ptgRef3d token on success
720
     */
721 6
    private function convertRef3d(string $cell): string
722
    {
723
        // Split the ref at the ! symbol
724 6
        [$ext_ref, $cell] = PhpspreadsheetWorksheet::extractSheetTitle($cell, true);
725
726
        // Convert the external reference part (different for BIFF8)
727 6
        $ext_ref = $this->getRefIndex($ext_ref ?? '');
728
729
        // Convert the cell reference part
730 5
        [$row, $col] = $this->cellToPackedRowcol($cell ?? '');
731
732
        // The ptg value depends on the class of the ptg.
733 5
        $ptgRef = pack('C', $this->ptg['ptgRef3dA']);
734
735 5
        return $ptgRef . $ext_ref . $row . $col;
736
    }
737
738
    /**
739
     * Convert an error code to a ptgErr.
740
     *
741
     * @param string $errorCode The error code for conversion to its ptg value
742
     *
743
     * @return string The error code ptgErr
744
     */
745 1
    private function convertError(string $errorCode): string
746
    {
747 1
        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 1
            '#NAME?' => pack('C', 0x1D),
753
            '#NUM!' => pack('C', 0x24),
754
            '#N/A' => pack('C', 0x2A),
755 1
            default => pack('C', 0xFF),
756 1
        };
757
    }
758
759
    private bool $tryDefinedName = false;
760
761 5
    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 5
        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
            }
776
777
            $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference);
778
779
            return $ptgRef;
780
            // @codeCoverageIgnoreEnd
781
        }
782
783 5
        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 7
    private function getRefIndex(string $ext_ref): string
796
    {
797 7
        $ext_ref = Preg::replace(["/^'/", "/'$/"], ['', ''], $ext_ref); // Remove leading and trailing ' if any.
798 7
        $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
799
800
        // Check if there is a sheet range eg., Sheet1:Sheet2.
801 7
        if (Preg::isMatch('/:/', $ext_ref)) {
802
            [$sheet_name1, $sheet_name2] = explode(':', $ext_ref);
803
804
            $sheet1 = $this->getSheetIndex($sheet_name1);
805
            if ($sheet1 == -1) {
806
                throw new WriterException("Unknown sheet name $sheet_name1 in formula");
807
            }
808
            $sheet2 = $this->getSheetIndex($sheet_name2);
809
            if ($sheet2 == -1) {
810
                throw new WriterException("Unknown sheet name $sheet_name2 in formula");
811
            }
812
813
            // Reverse max and min sheet numbers if necessary
814
            if ($sheet1 > $sheet2) {
815
                [$sheet1, $sheet2] = [$sheet2, $sheet1];
816
            }
817
        } else { // Single sheet name only.
818 7
            $sheet1 = $this->getSheetIndex($ext_ref);
819 7
            if ($sheet1 == -1) {
820 1
                throw new WriterException("Unknown sheet name $ext_ref in formula");
821
            }
822 6
            $sheet2 = $sheet1;
823
        }
824
825
        // assume all references belong to this document
826 6
        $supbook_index = 0x00;
827 6
        $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
828 6
        $totalreferences = count($this->references);
829 6
        $index = -1;
830 6
        for ($i = 0; $i < $totalreferences; ++$i) {
831 6
            if ($ref == $this->references[$i]) {
832 6
                $index = $i;
833
834 6
                break;
835
            }
836
        }
837
        // if REF was not found add it to references array
838 6
        if ($index == -1) {
839
            $this->references[$totalreferences] = $ref;
840
            $index = $totalreferences;
841
        }
842
843 6
        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
     */
855 7
    private function getSheetIndex(string $sheet_name): int
856
    {
857 7
        if (!isset($this->externalSheets[$sheet_name])) {
858 1
            return -1;
859
        }
860
861 6
        return $this->externalSheets[$sheet_name];
862
    }
863
864
    /**
865
     * This method is used to update the array of sheet names. It is
866
     * called by the addWorksheet() method of the
867
     * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
868
     *
869
     * @param string $name The name of the worksheet being added
870
     * @param int $index The index of the worksheet being added
871
     *
872
     * @see Workbook::addWorksheet
873
     */
874 111
    public function setExtSheet(string $name, int $index): void
875
    {
876 111
        $this->externalSheets[$name] = $index;
877
    }
878
879
    /**
880
     * pack() row and column into the required 3 or 4 byte format.
881
     *
882
     * @param string $cell The Excel cell reference to be packed
883
     *
884
     * @return array Array containing the row and column in packed() format
885
     */
886 38
    private function cellToPackedRowcol(string $cell): array
887
    {
888 38
        $cell = strtoupper($cell);
889 38
        [$row, $col, $row_rel, $col_rel] = $this->cellToRowcol($cell);
890 38
        if ($col >= 256) {
891
            throw new WriterException("Column in: $cell greater than 255");
892
        }
893 38
        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 38
        $col |= $col_rel << 14;
899 38
        $col |= $row_rel << 15;
900 38
        $col = pack('v', $col);
901
902 38
        $row = pack('v', $row);
903
904 38
        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
939
        // Set the high bits to indicate if rows are relative.
940
        $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
        $row2 = pack('v', $row2);
947
948
        return [$row1, $col1, $row2, $col2];
949
    }
950
951
    /**
952
     * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
953
     * indexed row and column number. Also returns two (0,1) values to indicate
954
     * whether the row or column are relative references.
955
     *
956
     * @param string $cell the Excel cell reference in A1 format
957
     */
958 38
    private function cellToRowcol(string $cell): array
959
    {
960 38
        if (!Preg::isMatch('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match)) {
961
            // @codeCoverageIgnoreStart
962
            throw new WriterException('Regexp failure in cellToRowcol');
963
            // @codeCoverageIgnoreEnd
964
        }
965
        // return absolute column if there is a $ in the ref
966 38
        $col_rel = empty($match[1]) ? 1 : 0;
967 38
        $col_ref = $match[2];
968 38
        $row_rel = empty($match[3]) ? 1 : 0;
969 38
        $row = $match[4];
970
971
        // Convert base26 column string to a number.
972 38
        $expn = strlen($col_ref) - 1;
973 38
        $col = 0;
974 38
        $col_ref_length = strlen($col_ref);
975 38
        for ($i = 0; $i < $col_ref_length; ++$i) {
976 38
            $col += (ord($col_ref[$i]) - 64) * 26 ** $expn;
977 38
            --$expn;
978
        }
979
980
        // Convert 1-index to zero-index
981 38
        --$row;
982 38
        --$col;
983
984 38
        return [$row, $col, $row_rel, $col_rel];
985
    }
986
987
    /**
988
     * Advance to the next valid token.
989
     */
990 47
    private function advance(): void
991
    {
992 47
        $token = '';
993 47
        $i = $this->currentCharacter;
994 47
        $formula_length = strlen($this->formula);
995
        // eat up white spaces
996 47
        if ($i < $formula_length) {
997 47
            while ($this->formula[$i] == ' ') {
998 4
                ++$i;
999
            }
1000
1001 47
            if ($i < ($formula_length - 1)) {
1002 46
                $this->lookAhead = $this->formula[$i + 1];
1003
            }
1004 47
            $token = '';
1005
        }
1006
1007 47
        while ($i < $formula_length) {
1008 47
            $token .= $this->formula[$i];
1009
1010 47
            if ($i < ($formula_length - 1)) {
1011 46
                $this->lookAhead = $this->formula[$i + 1];
1012
            } else {
1013 47
                $this->lookAhead = '';
1014
            }
1015
1016 47
            if ($this->match($token) != '') {
1017 47
                $this->currentCharacter = $i + 1;
1018 47
                $this->currentToken = $token;
1019
1020 47
                return;
1021
            }
1022
1023 46
            if ($i < ($formula_length - 2)) {
1024 43
                $this->lookAhead = $this->formula[$i + 2];
1025
            } else { // if we run out of characters lookAhead becomes empty
1026 32
                $this->lookAhead = '';
1027
            }
1028 46
            ++$i;
1029
        }
1030
    }
1031
1032
    /**
1033
     * Checks if it's a valid token.
1034
     *
1035
     * @param string $token the token to check
1036
     *
1037
     * @return string The checked token or empty string on failure
1038
     */
1039 47
    private function match(string $token): string
1040
    {
1041
        switch ($token) {
1042 47
            case '+':
1043 47
            case '-':
1044 47
            case '*':
1045 47
            case '/':
1046 47
            case '(':
1047 47
            case ')':
1048 47
            case ',':
1049 47
            case ';':
1050 47
            case '>=':
1051 47
            case '<=':
1052 47
            case '=':
1053 47
            case '<>':
1054 47
            case '^':
1055 47
            case '&':
1056 47
            case '%':
1057 44
                return $token;
1058
1059 47
            case '>':
1060 2
                if ($this->lookAhead === '=') { // it's a GE token
1061 1
                    break;
1062
                }
1063
1064 2
                return $token;
1065
1066 47
            case '<':
1067
                // it's a LE or a NE token
1068 8
                if (($this->lookAhead === '=') || ($this->lookAhead === '>')) {
1069 8
                    break;
1070
                }
1071
1072 1
                return $token;
1073
        }
1074
1075
        // if it's a reference A1 or $A$1 or $A1 or A$1
1076
        if (
1077 47
            Preg::isMatch('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token)
1078 47
            && !Preg::isMatch('/\d/', $this->lookAhead)
1079 47
            && ($this->lookAhead !== ':')
1080 47
            && ($this->lookAhead !== '.')
1081 47
            && ($this->lookAhead !== '!')
1082
        ) {
1083 29
            return $token;
1084
        }
1085
        // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1086
        if (
1087 47
            Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $token)
1088 47
            && !Preg::isMatch('/\d/', $this->lookAhead)
1089 47
            && ($this->lookAhead !== ':')
1090 47
            && ($this->lookAhead !== '.')
1091
        ) {
1092
            return $token;
1093
        }
1094
        // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1095
        if (
1096 47
            self::matchCellSheetnameQuoted($token)
1097 47
            && !Preg::isMatch('/\\d/', $this->lookAhead)
1098 47
            && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')
1099
        ) {
1100 6
            return $token;
1101
        }
1102
        // if it's a range A1:A2 or $A$1:$A$2
1103
        if (
1104 47
            Preg::isMatch(
1105 47
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1106 47
                $token
1107 47
            )
1108 47
            && !Preg::isMatch('/\d/', $this->lookAhead)
1109
        ) {
1110 25
            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 47
            Preg::isMatch(
1115 47
                '/^'
1116 47
                . self::REGEX_SHEET_TITLE_UNQUOTED
1117 47
                . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED
1118 47
                . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u',
1119 47
                $token
1120 47
            )
1121 47
            && !Preg::isMatch('/\d/', $this->lookAhead)
1122
        ) {
1123
            return $token;
1124
        }
1125
        // 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
        if (
1127 47
            self::matchRangeSheetnameQuoted($token)
1128 47
            && !Preg::isMatch('/\\d/', $this->lookAhead)
1129
        ) {
1130 4
            return $token;
1131
        }
1132
        // If it's a number (check that it's not a sheet name or range)
1133 47
        if (is_numeric($token) && (!is_numeric($token . $this->lookAhead) || ($this->lookAhead == '')) && ($this->lookAhead !== '!') && ($this->lookAhead !== ':')) {
1134 29
            return $token;
1135
        }
1136
        if (
1137 46
            Preg::isMatch('/"([^"]|""){0,255}"/', $token)
1138 46
            && $this->lookAhead !== '"'
1139 46
            && (substr_count($token, '"') % 2 == 0)
1140
        ) {
1141
            // If it's a string (of maximum 255 characters)
1142 21
            return $token;
1143
        }
1144
        // If it's an error code
1145
        if (
1146 46
            Preg::isMatch('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token)
1147 46
            || $token === '#N/A'
1148
        ) {
1149 1
            return $token;
1150
        }
1151
        // if it's a function call
1152
        if (
1153 46
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token)
1154 46
            && ($this->lookAhead === '(')
1155
        ) {
1156 33
            return $token;
1157
        }
1158
        if (
1159 46
            Preg::isMatch(
1160 46
                '/^'
1161 46
                . Calculation::CALCULATION_REGEXP_DEFINEDNAME
1162 46
                . '$/miu',
1163 46
                $token
1164 46
            )
1165 46
            && $this->spreadsheet->getDefinedName($token) !== null
1166
        ) {
1167 5
            return $token;
1168
        }
1169
        if (
1170 46
            Preg::isMatch('/^true$/i', $token)
1171 46
            && ($this->lookAhead === ')' || $this->lookAhead === ',')
1172
        ) {
1173 1
            return $token;
1174
        }
1175
        if (
1176 46
            Preg::isMatch('/^false$/i', $token)
1177 46
            && ($this->lookAhead === ')' || $this->lookAhead === ',')
1178
        ) {
1179 1
            return $token;
1180
        }
1181 46
        if (str_ends_with($token, ')')) {
1182
            //    It's an argument of some description (e.g. a named range),
1183
            //        precise nature yet to be determined
1184 1
            return $token;
1185
        }
1186
1187 46
        return '';
1188
    }
1189
1190
    /**
1191
     * The parsing method. It parses a formula.
1192
     *
1193
     * @param string $formula the formula to parse, without the initial equal
1194
     *                        sign (=)
1195
     *
1196
     * @return bool true on success
1197
     */
1198 47
    public function parse(string $formula): bool
1199
    {
1200 47
        $this->currentCharacter = 0;
1201 47
        $this->formula = (string) $formula;
1202 47
        $this->lookAhead = $formula[1] ?? '';
1203 47
        $this->advance();
1204 47
        $this->parseTree = $this->condition();
1205
1206 47
        return true;
1207
    }
1208
1209
    /**
1210
     * It parses a condition. It assumes the following rule:
1211
     * Cond -> Expr [(">" | "<") Expr].
1212
     *
1213
     * @return array The parsed ptg'd tree on success
1214
     */
1215 47
    private function condition(): array
1216
    {
1217 47
        $result = $this->expression();
1218 47
        if ($this->currentToken == '<') {
1219 1
            $this->advance();
1220 1
            $result2 = $this->expression();
1221 1
            $result = $this->createTree('ptgLT', $result, $result2);
1222 47
        } elseif ($this->currentToken == '>') {
1223 2
            $this->advance();
1224 2
            $result2 = $this->expression();
1225 2
            $result = $this->createTree('ptgGT', $result, $result2);
1226 47
        } elseif ($this->currentToken == '<=') {
1227 2
            $this->advance();
1228 2
            $result2 = $this->expression();
1229 2
            $result = $this->createTree('ptgLE', $result, $result2);
1230 47
        } elseif ($this->currentToken == '>=') {
1231 1
            $this->advance();
1232 1
            $result2 = $this->expression();
1233 1
            $result = $this->createTree('ptgGE', $result, $result2);
1234 47
        } elseif ($this->currentToken == '=') {
1235 4
            $this->advance();
1236 4
            $result2 = $this->expression();
1237 4
            $result = $this->createTree('ptgEQ', $result, $result2);
1238 47
        } elseif ($this->currentToken == '<>') {
1239 7
            $this->advance();
1240 7
            $result2 = $this->expression();
1241 7
            $result = $this->createTree('ptgNE', $result, $result2);
1242
        }
1243
1244 47
        return $result;
1245
    }
1246
1247
    /**
1248
     * It parses a expression. It assumes the following rule:
1249
     * Expr -> Term [("+" | "-") Term]
1250
     *      -> "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 47
    private function expression(): array
1258
    {
1259
        // If it's a string return a string node
1260 47
        if (Preg::isMatch('/"([^"]|""){0,255}"/', $this->currentToken)) {
1261 21
            $tmp = str_replace('""', '"', $this->currentToken);
1262 21
            if (($tmp == '"') || ($tmp == '')) {
1263
                //    Trap for "" that has been used for an empty string
1264 7
                $tmp = '""';
1265
            }
1266 21
            $result = $this->createTree($tmp, '', '');
1267 21
            $this->advance();
1268
1269 21
            return $result;
1270
        }
1271
        if (
1272 47
            Preg::isMatch('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $this->currentToken)
1273 47
            || $this->currentToken == '#N/A'
1274
        ) { // error code
1275 1
            $result = $this->createTree($this->currentToken, 'ptgErr', '');
1276 1
            $this->advance();
1277
1278 1
            return $result;
1279
        }
1280 47
        if ($this->currentToken == '-') { // negative value
1281
            // catch "-" Term
1282 6
            $this->advance();
1283 6
            $result2 = $this->expression();
1284
1285 6
            return $this->createTree('ptgUminus', $result2, '');
1286 47
        } elseif ($this->currentToken == '+') { // positive value
1287
            // catch "+" Term
1288 1
            $this->advance();
1289 1
            $result2 = $this->expression();
1290
1291 1
            return $this->createTree('ptgUplus', $result2, '');
1292
        }
1293 47
        $result = $this->term();
1294 47
        while ($this->currentToken === '&') {
1295 8
            $this->advance();
1296 8
            $result2 = $this->expression();
1297 8
            $result = $this->createTree('ptgConcat', $result, $result2);
1298
        }
1299
        while (
1300 47
            ($this->currentToken == '+')
1301 47
            || ($this->currentToken == '-')
1302 47
            || ($this->currentToken == '^')
1303
        ) {
1304 21
            if ($this->currentToken == '+') {
1305 21
                $this->advance();
1306 21
                $result2 = $this->term();
1307 21
                $result = $this->createTree('ptgAdd', $result, $result2);
1308 6
            } elseif ($this->currentToken == '-') {
1309 6
                $this->advance();
1310 6
                $result2 = $this->term();
1311 6
                $result = $this->createTree('ptgSub', $result, $result2);
1312
            } else {
1313 1
                $this->advance();
1314 1
                $result2 = $this->term();
1315 1
                $result = $this->createTree('ptgPower', $result, $result2);
1316
            }
1317
        }
1318
1319 47
        return $result;
1320
    }
1321
1322
    /**
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
     *
1326
     * @return array The parsed ptg'd tree
1327
     *
1328
     * @see fact()
1329
     */
1330 3
    private function parenthesizedExpression(): array
1331
    {
1332 3
        return $this->createTree('ptgParen', $this->expression(), '');
1333
    }
1334
1335
    /**
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 47
    private function term(): array
1342
    {
1343 47
        $result = $this->fact();
1344
        while (
1345 47
            ($this->currentToken == '*')
1346 47
            || ($this->currentToken == '/')
1347
        ) {
1348 17
            if ($this->currentToken == '*') {
1349 16
                $this->advance();
1350 16
                $result2 = $this->fact();
1351 16
                $result = $this->createTree('ptgMul', $result, $result2);
1352
            } else {
1353 4
                $this->advance();
1354 4
                $result2 = $this->fact();
1355 4
                $result = $this->createTree('ptgDiv', $result, $result2);
1356
            }
1357
        }
1358
1359 47
        return $result;
1360
    }
1361
1362
    /**
1363
     * It parses a factor. It assumes the following rule:
1364
     * Fact -> ( Expr )
1365
     *       | CellRef
1366
     *       | CellRange
1367
     *       | Number
1368
     *       | Function.
1369
     *
1370
     * @return array The parsed ptg'd tree on success
1371
     */
1372 47
    private function fact(): array
1373
    {
1374 47
        $currentToken = $this->currentToken;
1375 47
        if ($currentToken === '(') {
1376 3
            $this->advance(); // eat the "("
1377 3
            $result = $this->parenthesizedExpression();
1378 3
            if ($this->currentToken !== ')') {
1379
                throw new WriterException("')' token expected.");
1380
            }
1381 3
            $this->advance(); // eat the ")"
1382
1383 3
            return $result;
1384
        }
1385
        // if it's a reference
1386 47
        if (Preg::isMatch('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $this->currentToken)) {
1387 29
            $result = $this->createTree($this->currentToken, '', '');
1388 29
            $this->advance();
1389
1390 29
            return $result;
1391
        }
1392
        if (
1393 44
            Preg::isMatch(
1394 44
                '/^'
1395 44
                . self::REGEX_SHEET_TITLE_UNQUOTED
1396 44
                . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED
1397 44
                . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u',
1398 44
                $this->currentToken
1399 44
            )
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
            $this->advance();
1404
1405
            return $result;
1406
        }
1407 44
        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 6
            $result = $this->createTree($this->currentToken, '', '');
1410 6
            $this->advance();
1411
1412 6
            return $result;
1413
        }
1414
        if (
1415 43
            Preg::isMatch(
1416 43
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1417 43
                $this->currentToken
1418 43
            )
1419 43
            || Preg::isMatch(
1420 43
                '/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/',
1421 43
                $this->currentToken
1422 43
            )
1423
        ) {
1424
            // if it's a range A1:B2 or $A$1:$B$2
1425
            // must be an error?
1426 25
            $result = $this->createTree($this->currentToken, '', '');
1427 25
            $this->advance();
1428
1429 25
            return $result;
1430
        }
1431
        if (
1432 43
            Preg::isMatch(
1433 43
                '/^'
1434 43
                . self::REGEX_SHEET_TITLE_UNQUOTED
1435 43
                . '(\\:'
1436 43
                . self::REGEX_SHEET_TITLE_UNQUOTED
1437 43
                . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u',
1438 43
                $this->currentToken
1439 43
            )
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 43
        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 4
            $result = $this->createTree($this->currentToken, '', '');
1452 4
            $this->advance();
1453
1454 4
            return $result;
1455
        }
1456 43
        if (is_numeric($this->currentToken)) {
1457
            // If it's a number or a percent
1458 29
            if ($this->lookAhead === '%') {
1459 1
                $result = $this->createTree('ptgPercent', $this->currentToken, '');
1460 1
                $this->advance(); // Skip the percentage operator once we've pre-built that tree
1461
            } else {
1462 29
                $result = $this->createTree($this->currentToken, '', '');
1463
            }
1464 29
            $this->advance();
1465
1466 29
            return $result;
1467
        }
1468
        if (
1469 35
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken)
1470 35
            && ($this->lookAhead === '(')
1471
        ) {
1472
            // if it's a function call
1473 33
            return $this->func();
1474
        }
1475
        if (
1476 7
            Preg::isMatch(
1477 7
                '/^'
1478 7
                . Calculation::CALCULATION_REGEXP_DEFINEDNAME
1479 7
                . '$/miu',
1480 7
                $this->currentToken
1481 7
            )
1482 7
            && $this->spreadsheet->getDefinedName($this->currentToken) !== null
1483
        ) {
1484 5
            $result = $this->createTree('ptgName', $this->currentToken, '');
1485 5
            $this->advance();
1486
1487 5
            return $result;
1488
        }
1489 2
        if (Preg::isMatch('/^true|false$/i', $this->currentToken)) {
1490 1
            $result = $this->createTree($this->currentToken, '', '');
1491 1
            $this->advance();
1492
1493 1
            return $result;
1494
        }
1495
1496 1
        throw new WriterException('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter);
1497
    }
1498
1499
    /**
1500
     * It parses a function call. It assumes the following rule:
1501
     * Func -> ( Expr [,Expr]* ).
1502
     *
1503
     * @return array The parsed ptg'd tree on success
1504
     */
1505 33
    private function func(): array
1506
    {
1507 33
        $num_args = 0; // number of arguments received
1508 33
        $function = strtoupper($this->currentToken);
1509 33
        $result = ''; // initialize result
1510 33
        $this->advance();
1511 33
        $this->advance(); // eat the "("
1512 33
        while ($this->currentToken !== ')') {
1513 33
            if ($num_args > 0) {
1514 19
                if ($this->currentToken === ',' || $this->currentToken === ';') {
1515 19
                    $this->advance(); // eat the "," or ";"
1516
                } else {
1517
                    throw new WriterException("Syntax error: comma expected in function $function, arg #{$num_args}");
1518
                }
1519 19
                $result2 = $this->condition();
1520 19
                $result = $this->createTree('arg', $result, $result2);
1521
            } else { // first argument
1522 33
                $result2 = $this->condition();
1523 33
                $result = $this->createTree('arg', '', $result2);
1524
            }
1525 33
            ++$num_args;
1526
        }
1527 33
        if (!isset($this->functions[$function])) {
1528 3
            throw new WriterException("Function $function() doesn't exist");
1529
        }
1530 33
        $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 33
        if (($args >= 0) && ($args != $num_args)) {
1533
            throw new WriterException("Incorrect number of arguments in function $function() ");
1534
        }
1535
1536 33
        $result = $this->createTree($function, $result, $num_args);
1537 33
        $this->advance(); // eat the ")"
1538
1539 33
        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 47
    private function createTree(mixed $value, mixed $left, mixed $right): array
1553
    {
1554 47
        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 51
    public function toReversePolish(array $tree = []): string
1585
    {
1586 51
        $polish = ''; // the string we are going to return
1587 51
        if (empty($tree)) { // If it's the first call use parseTree
1588 48
            $tree = $this->parseTree;
1589
        }
1590 51
        if (!is_array($tree) || !isset($tree['left'], $tree['right'], $tree['value'])) {
1591 2
            throw new WriterException('Unexpected non-array');
1592
        }
1593
1594 49
        if (is_array($tree['left'])) {
1595 44
            $converted_tree = $this->toReversePolish($tree['left']);
1596 44
            $polish .= $converted_tree;
1597 49
        } elseif ($tree['left'] != '') { // It's a final node
1598 8
            $converted_tree = $this->convert($tree['left']);
1599 3
            $polish .= $converted_tree;
1600
        }
1601 49
        if (is_array($tree['right'])) {
1602 43
            $converted_tree = $this->toReversePolish($tree['right']);
1603 42
            $polish .= $converted_tree;
1604 49
        } elseif ($tree['right'] != '') { // It's a final node
1605 34
            $converted_tree = $this->convert($tree['right']);
1606 34
            $polish .= $converted_tree;
1607
        }
1608
        // if it's a function convert it here (so we can set it's arguments)
1609
        if (
1610 49
            Preg::isMatch("/^[A-Z0-9\xc0-\xdc\\.]+$/", $tree['value'])
1611 49
            && !Preg::isMatch('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value'])
1612 49
            && !Preg::isMatch(
1613 49
                '/^[A-Ia-i]?[A-Za-z](\\d+)\\.\\.[A-Ia-i]?[A-Za-z](\\d+)$/',
1614 49
                $tree['value']
1615 49
            )
1616 49
            && !is_numeric($tree['value'])
1617 49
            && !isset($this->ptg[$tree['value']])
1618
        ) {
1619
            // left subtree for a function is always an array.
1620 32
            if ($tree['left'] != '') {
1621 32
                $left_tree = $this->toReversePolish($tree['left']);
1622
            } else {
1623 8
                $left_tree = '';
1624
            }
1625
1626
            // add its left subtree and return.
1627 32
            return $left_tree . $this->convertFunction($tree['value'], $tree['right']);
1628
        }
1629 49
        $converted_tree = $this->convert($tree['value']);
1630
1631 47
        return $polish . $converted_tree;
1632
    }
1633
1634 58
    public static function matchCellSheetnameQuoted(string $token): bool
1635
    {
1636 58
        return Preg::isMatch(
1637 58
            self::REGEX_CELL_TITLE_QUOTED,
1638 58
            $token
1639 58
        );
1640
    }
1641
1642 58
    public static function matchRangeSheetnameQuoted(string $token): bool
1643
    {
1644 58
        return Preg::isMatch(
1645 58
            self::REGEX_RANGE_TITLE_QUOTED,
1646 58
            $token
1647 58
        );
1648
    }
1649
}
1650