<?php
/**
 * Wrap an OpenDocument spreadsheet cell
 *
 * Requires PHP 5.0.3
 *
 * @version $Id: Calc_Cell.php,v 1.1 2005-02-27 10:58:44 marand Exp $
 * @license CeCILL 2.0
 * @copyright 2005 Ouest Systemes Informatiques
 */

/**
 * OpenDocument Spreadsheet cell
 */
$erCalc_Cell = error_reporting(E_ALL | E_STRICT);

class Calc_Cell
  {
  /**
   * Values of the 'office:value-type' attribute
   */
  const TYPE_STRING = 'string';
  const TYPE_FLOAT  = 'float';
  const TYPE_EMPTY  = 'empty'; // used if attribute is missing
  
  public $dataType;
  public $dataValue;
  public $displayValue;
  
  /**
   * @param DOMNode $cellNode
   */
  function __construct(DOMNode $cellNode)
    {
    if (is_a($cellNode, 'DOMElement'))
      {
      $this->dataType  = $cellNode->getAttributeNS(Calc_Reader::NS_OFFICE, 'value-type');
      /**
       * Note: cells with office:value-type==string don't have a office:value 
       * attribute, but it is clearer to just fetch it and get NULL than test.
       * Maybe more sophistication will be needed in the future
       */
      $this->dataValue = $cellNode->getAttributeNS(Calc_Reader::NS_OFFICE, 'value');
      $p = $cellNode->childNodes->item(0); 
      $this->displayValue = $p->textContent;
      unset($p);     
      }
    else
      {
      $this->dataType  = Calc_Cell::TYPE_EMPTY;
      $this->dataValue = NULL;
      $this->displayValue = '';
      }
    }
    
  /**
   * Convert a PHP value to a wrapped OpenDocument cell value
   * 
   * @param mixed $x
   */
  function set($x = NULL)
    {
    $type = gettype($x);
    switch ($type)
      {
      case 'NULL':
        $this->dataType = Calc_Cell::TYPE_EMPTY; 
        $this->dataValue = NULL;
        $this->displayValue = NULL;
        break;
      case 'string':
        $this->dataType = Calc_Cell::TYPE_STRING;
        $this->dataValue = NULL;
        $this->displayValue = $x;
        break;
      case 'double':
        $this->dataType = Calc_Cell::TYPE_FLOAT;
        $this->dataValue = $x;
        $this->displayValue = number_format($x);
        break;
      default:
        $this->set();
        throw new Exception('Calc_Cell::set unsupported value type ', $type);
        break;
      }
    }
   
  /**
   * implement magic method __toString
   * 
   * @return string
   */
  function __toString()
    {
    return (string) $this->displayValue;
    }
  }

error_reporting($erCalc_Cell);
unset($erCalc_Cell);