DefaultValueBinder.php 2.7 KB

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