1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PhpOffice\PhpSpreadsheet\Cell; |
4
|
|
|
|
5
|
|
|
use PhpOffice\PhpSpreadsheet\Calculation\Calculation; |
6
|
|
|
use PhpOffice\PhpSpreadsheet\Calculation\Functions; |
7
|
|
|
use PhpOffice\PhpSpreadsheet\Exception; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Validate a cell value according to its validation rules. |
11
|
|
|
*/ |
12
|
|
|
class DataValidator |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Does this cell contain valid value? |
16
|
|
|
* |
17
|
|
|
* @param Cell $cell Cell to check the value |
18
|
|
|
* |
19
|
|
|
* @return bool |
20
|
|
|
*/ |
21
|
3 |
|
public function isValid(Cell $cell) |
22
|
|
|
{ |
23
|
3 |
|
if (!$cell->hasDataValidation()) { |
24
|
1 |
|
return true; |
25
|
|
|
} |
26
|
|
|
|
27
|
2 |
|
$cellValue = $cell->getValue(); |
28
|
2 |
|
$dataValidation = $cell->getDataValidation(); |
29
|
|
|
|
30
|
2 |
|
if (!$dataValidation->getAllowBlank() && ($cellValue === null || $cellValue === '')) { |
31
|
1 |
|
return false; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
// TODO: write check on all cases |
35
|
2 |
|
switch ($dataValidation->getType()) { |
36
|
2 |
|
case DataValidation::TYPE_LIST: |
37
|
1 |
|
return $this->isValueInList($cell); |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
return false; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Does this cell contain valid value, based on list? |
45
|
|
|
* |
46
|
|
|
* @param Cell $cell Cell to check the value |
47
|
|
|
* |
48
|
|
|
* @return bool |
49
|
|
|
*/ |
50
|
1 |
|
private function isValueInList(Cell $cell) |
51
|
|
|
{ |
52
|
1 |
|
$cellValue = $cell->getValue(); |
53
|
1 |
|
$dataValidation = $cell->getDataValidation(); |
54
|
|
|
|
55
|
1 |
|
$formula1 = $dataValidation->getFormula1(); |
56
|
1 |
|
if (!empty($formula1)) { |
57
|
|
|
// inline values list |
58
|
1 |
|
if ($formula1[0] === '"') { |
59
|
1 |
|
return in_array(strtolower($cellValue), explode(',', strtolower(trim($formula1, '"'))), true); |
60
|
1 |
|
} elseif (strpos($formula1, ':') > 0) { |
61
|
|
|
// values list cells |
62
|
1 |
|
$matchFormula = '=MATCH(' . $cell->getCoordinate() . ', ' . $formula1 . ', 0)'; |
63
|
1 |
|
$calculation = Calculation::getInstance($cell->getWorksheet()->getParent()); |
64
|
|
|
|
65
|
|
|
try { |
66
|
1 |
|
$result = $calculation->calculateFormula($matchFormula, $cell->getCoordinate(), $cell); |
67
|
|
|
|
68
|
1 |
|
return $result !== Functions::NA(); |
69
|
1 |
|
} catch (Exception $ex) { |
70
|
1 |
|
return false; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
return true; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|