DataValidator.php 2.1 KB

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