| 1441 |
ariadna |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef;
|
|
|
4 |
|
|
|
5 |
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
|
|
|
6 |
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
|
|
|
7 |
|
|
|
8 |
abstract class LookupBase
|
|
|
9 |
{
|
|
|
10 |
protected static function validateLookupArray(mixed $lookup_array): void
|
|
|
11 |
{
|
|
|
12 |
if (!is_array($lookup_array)) {
|
|
|
13 |
throw new Exception(ExcelError::REF());
|
|
|
14 |
}
|
|
|
15 |
}
|
|
|
16 |
|
|
|
17 |
/** @param float|int|string $index_number */
|
|
|
18 |
protected static function validateIndexLookup(array $lookup_array, $index_number): int
|
|
|
19 |
{
|
|
|
20 |
// index_number must be a number greater than or equal to 1.
|
|
|
21 |
// Excel results are inconsistent when index is non-numeric.
|
|
|
22 |
// VLOOKUP(whatever, whatever, SQRT(-1)) yields NUM error, but
|
|
|
23 |
// VLOOKUP(whatever, whatever, cellref) yields REF error
|
|
|
24 |
// when cellref is '=SQRT(-1)'. So just try our best here.
|
|
|
25 |
// Similar results if string (literal yields VALUE, cellRef REF).
|
|
|
26 |
if (!is_numeric($index_number)) {
|
|
|
27 |
throw new Exception(ExcelError::throwError($index_number));
|
|
|
28 |
}
|
|
|
29 |
if ($index_number < 1) {
|
|
|
30 |
throw new Exception(ExcelError::VALUE());
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
// index_number must be less than or equal to the number of columns in lookup_array
|
|
|
34 |
if (empty($lookup_array)) {
|
|
|
35 |
throw new Exception(ExcelError::REF());
|
|
|
36 |
}
|
|
|
37 |
|
|
|
38 |
return (int) $index_number;
|
|
|
39 |
}
|
|
|
40 |
|
|
|
41 |
protected static function checkMatch(
|
|
|
42 |
bool $bothNumeric,
|
|
|
43 |
bool $bothNotNumeric,
|
|
|
44 |
bool $notExactMatch,
|
|
|
45 |
int $rowKey,
|
|
|
46 |
string $cellDataLower,
|
|
|
47 |
string $lookupLower,
|
|
|
48 |
?int $rowNumber
|
|
|
49 |
): ?int {
|
|
|
50 |
// remember the last key, but only if datatypes match
|
|
|
51 |
if ($bothNumeric || $bothNotNumeric) {
|
|
|
52 |
// Spreadsheets software returns first exact match,
|
|
|
53 |
// we have sorted and we might have broken key orders
|
|
|
54 |
// we want the first one (by its initial index)
|
|
|
55 |
if ($notExactMatch) {
|
|
|
56 |
$rowNumber = $rowKey;
|
|
|
57 |
} elseif (($cellDataLower == $lookupLower) && (($rowNumber === null) || ($rowKey < $rowNumber))) {
|
|
|
58 |
$rowNumber = $rowKey;
|
|
|
59 |
}
|
|
|
60 |
}
|
|
|
61 |
|
|
|
62 |
return $rowNumber;
|
|
|
63 |
}
|
|
|
64 |
}
|