| 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 |
public function isValid(Cell $cell) |
| 22 |
{ |
| 23 |
if (!$cell->hasDataValidation()) { |
| 24 |
return true; |
| 25 |
} |
| 26 |
|
| 27 |
$cellValue = $cell->getValue(); |
| 28 |
$dataValidation = $cell->getDataValidation(); |
| 29 |
|
| 30 |
if (!$dataValidation->getAllowBlank() && ($cellValue === null || $cellValue === '')) { |
| 31 |
return false; |
| 32 |
} |
| 33 |
|
| 34 |
// TODO: write check on all cases |
| 35 |
switch ($dataValidation->getType()) { |
| 36 |
case DataValidation::TYPE_LIST: |
| 37 |
return $this->isValueInList($cell); |
| 38 |
} |
| 39 |
|
| 40 |
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 |
private function isValueInList(Cell $cell) |
| 51 |
{ |
| 52 |
$cellValue = $cell->getValue(); |
| 53 |
$dataValidation = $cell->getDataValidation(); |
| 54 |
|
| 55 |
$formula1 = $dataValidation->getFormula1(); |
| 56 |
if (!empty($formula1)) { |
| 57 |
// inline values list |
| 58 |
if ($formula1[0] === '"') { |
| 59 |
return in_array(strtolower($cellValue), explode(',', strtolower(trim($formula1, '"'))), true); |
| 60 |
} elseif (strpos($formula1, ':') > 0) { |
| 61 |
// values list cells |
| 62 |
$matchFormula = '=MATCH(' . $cell->getCoordinate() . ', ' . $formula1 . ', 0)'; |
| 63 |
$calculation = Calculation::getInstance($cell->getWorksheet()->getParent()); |
| 64 |
|
| 65 |
try { |
| 66 |
$result = $calculation->calculateFormula($matchFormula, $cell->getCoordinate(), $cell); |
| 67 |
|
| 68 |
return $result !== Functions::NA(); |
| 69 |
} catch (Exception $ex) { |
| 70 |
return false; |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
return true; |
| 76 |
} |
| 77 |
} |
| 78 |
|