DefaultValueBinder.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Cell;
  3. require_once DOL_DOCUMENT_ROOT . '/includes/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/IValueBinder.php';
  4. use DateTimeInterface;
  5. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  6. use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
  7. class DefaultValueBinder implements IValueBinder
  8. {
  9. /**
  10. * Bind value to a cell.
  11. *
  12. * @param Cell $cell Cell to bind value to
  13. * @param mixed $value Value to bind in cell
  14. *
  15. * @throws \PhpOffice\PhpSpreadsheet\Exception
  16. *
  17. * @return bool
  18. */
  19. public function bindValue(Cell $cell, $value)
  20. {
  21. // sanitize UTF-8 strings
  22. if (is_string($value)) {
  23. $value = StringHelper::sanitizeUTF8($value);
  24. } elseif (is_object($value)) {
  25. // Handle any objects that might be injected
  26. if ($value instanceof DateTimeInterface) {
  27. $value = $value->format('Y-m-d H:i:s');
  28. } elseif (!($value instanceof RichText)) {
  29. $value = (string) $value;
  30. }
  31. }
  32. // Set value explicit
  33. $cell->setValueExplicit($value, static::dataTypeForValue($value));
  34. // Done!
  35. return true;
  36. }
  37. /**
  38. * DataType for value.
  39. *
  40. * @param mixed $pValue
  41. *
  42. * @return string
  43. */
  44. public static function dataTypeForValue($pValue)
  45. {
  46. // Match the value against a few data types
  47. if ($pValue === null) {
  48. return DataType::TYPE_NULL;
  49. } elseif ($pValue === '') {
  50. return DataType::TYPE_STRING;
  51. } elseif ($pValue instanceof RichText) {
  52. return DataType::TYPE_INLINE;
  53. } elseif ($pValue[0] === '=' && strlen($pValue) > 1) {
  54. return DataType::TYPE_FORMULA;
  55. } elseif (is_bool($pValue)) {
  56. return DataType::TYPE_BOOL;
  57. } elseif (is_float($pValue) || is_int($pValue)) {
  58. return DataType::TYPE_NUMERIC;
  59. } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) {
  60. $tValue = ltrim($pValue, '+-');
  61. if (is_string($pValue) && $tValue[0] === '0' && strlen($tValue) > 1 && $tValue[1] !== '.') {
  62. return DataType::TYPE_STRING;
  63. } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) {
  64. return DataType::TYPE_STRING;
  65. }
  66. return DataType::TYPE_NUMERIC;
  67. } elseif (is_string($pValue)) {
  68. $errorCodes = DataType::getErrorCodes();
  69. if (isset($errorCodes[$pValue])) {
  70. return DataType::TYPE_ERROR;
  71. }
  72. }
  73. return DataType::TYPE_STRING;
  74. }
  75. }