DefaultValueBinder.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. $value = (string) $value;
  27. }
  28. }
  29. // Set value explicit
  30. $cell->setValueExplicit($value, self::dataTypeForValue($value));
  31. // Done!
  32. return true;
  33. }
  34. /**
  35. * DataType for value.
  36. *
  37. * @param mixed $pValue
  38. *
  39. * @return string
  40. */
  41. public static function dataTypeForValue($pValue)
  42. {
  43. // Match the value against a few data types
  44. if ($pValue === null) {
  45. return DataType::TYPE_NULL;
  46. } elseif ($pValue === '') {
  47. return DataType::TYPE_STRING;
  48. } elseif ($pValue instanceof RichText) {
  49. return DataType::TYPE_INLINE;
  50. } elseif ($pValue[0] === '=' && strlen($pValue) > 1) {
  51. return DataType::TYPE_FORMULA;
  52. } elseif (is_bool($pValue)) {
  53. return DataType::TYPE_BOOL;
  54. } elseif (is_float($pValue) || is_int($pValue)) {
  55. return DataType::TYPE_NUMERIC;
  56. } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) {
  57. $tValue = ltrim($pValue, '+-');
  58. if (is_string($pValue) && $tValue[0] === '0' && strlen($tValue) > 1 && $tValue[1] !== '.') {
  59. return DataType::TYPE_STRING;
  60. } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) {
  61. return DataType::TYPE_STRING;
  62. }
  63. return DataType::TYPE_NUMERIC;
  64. } elseif (is_string($pValue)) {
  65. $errorCodes = DataType::getErrorCodes();
  66. if (isset($errorCodes[$pValue])) {
  67. return DataType::TYPE_ERROR;
  68. }
  69. }
  70. return DataType::TYPE_STRING;
  71. }
  72. }