1
0

Cell.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Wrap an OpenDocument spreadsheet cell
  4. *
  5. * @license CeCILL 2.0
  6. * @copyright 2005-2012,2020 Ouest Systemes Informatiques
  7. */
  8. namespace Osinet\OpenDocument\Calc;
  9. /**
  10. * OpenDocument Spreadsheet cell
  11. */
  12. class Cell {
  13. /**
  14. * Values of the 'office:value-type' attribute
  15. */
  16. const TYPE_STRING = 'string';
  17. const TYPE_FLOAT = 'float';
  18. const TYPE_EMPTY = 'empty'; // used if attribute is missing
  19. public string $dataType;
  20. public ?string $dataValue;
  21. public ?string $displayValue;
  22. /**
  23. * @param \DOMNode $cellNode
  24. */
  25. function __construct(\DOMNode $cellNode) {
  26. if ($cellNode instanceof \DOMElement) {
  27. $this->dataType = $cellNode->getAttributeNS(Reader::NS_OFFICE, 'value-type');
  28. if ($cellNode->childNodes->length == 0) {
  29. $this->dataType = self::TYPE_EMPTY;
  30. $this->dataValue = NULL;
  31. $this->displayValue = '';
  32. }
  33. else {
  34. $p = $cellNode->childNodes->item(0);
  35. $this->displayValue = $p->textContent;
  36. unset($p);
  37. /**
  38. * Note: cells with office:value-type==string don't have a office:value
  39. */
  40. if ($this->dataType == self::TYPE_STRING) {
  41. //$this->dataValue = $this->displayValue;
  42. }
  43. else {
  44. $this->dataValue = $cellNode->getAttributeNS(Reader::NS_OFFICE, 'value');
  45. }
  46. }
  47. }
  48. /* echo "children: " . $cellNode->childNodes->length
  49. . ", type = " . $this->dataType
  50. . ", value = " . substr($this->dataValue, 0, 20)
  51. . ", display = <" . substr($this->displayValue, 0, 20)
  52. . ">" . PHP_EOL; */
  53. }
  54. /**
  55. * Convert a PHP value to a wrapped OpenDocument cell value
  56. *
  57. * @param mixed $x
  58. */
  59. function set($x = NULL): void {
  60. $type = gettype($x);
  61. switch ($type) {
  62. case 'NULL':
  63. $this->dataType = self::TYPE_EMPTY;
  64. $this->dataValue = NULL;
  65. $this->displayValue = NULL;
  66. break;
  67. case 'string':
  68. $this->dataType = self::TYPE_STRING;
  69. $this->dataValue = NULL;
  70. $this->displayValue = $x;
  71. break;
  72. case 'double':
  73. $this->dataType = self::TYPE_FLOAT;
  74. $this->dataValue = $x;
  75. $this->displayValue = number_format($x);
  76. break;
  77. default:
  78. $this->set();
  79. throw new \Exception("Cell::set unsupported value type ${type}");
  80. }
  81. }
  82. /**
  83. * implement magic method __toString
  84. *
  85. * @return string
  86. */
  87. function __toString() {
  88. return (string) $this->displayValue;
  89. }
  90. }