DefaultValueBinder.Class.php 2.5 KB

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