Failed Conditions
Push — master ( bf4629...7712d5 )
by Adrien
27:59 queued 18:08
created

Parser::convertBool()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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