DefaultValueBinder.php 2.5 KB

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