Unit tests for Cell static methods and creation of PHPExcel_Exception

rather than use of standard Exception
This commit is contained in:
Mark Baker 2012-07-29 20:56:35 +01:00
parent 8f3dc270a6
commit 6a14bdce4c
12 changed files with 606 additions and 211 deletions

View File

@ -1,108 +1,112 @@
<?php <?php
/** /**
* PHPExcel * PHPExcel
* *
* Copyright (c) 2006 - 2012 PHPExcel * Copyright (c) 2006 - 2012 PHPExcel
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* *
* @category PHPExcel * @category PHPExcel
* @package PHPExcel_Cell * @package PHPExcel_Cell
* @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel) * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE## * @version ##VERSION##, ##DATE##
*/ */
/** /**
* PHPExcel_Cell * PHPExcel_Cell
* *
* @category PHPExcel * @category PHPExcel
* @package PHPExcel_Cell * @package PHPExcel_Cell
* @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel) * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
*/ */
class PHPExcel_Cell class PHPExcel_Cell
{ {
/** /**
* Value binder to use * Value binder to use
* *
* @var PHPExcel_Cell_IValueBinder * @var PHPExcel_Cell_IValueBinder
*/ */
private static $_valueBinder = null; private static $_valueBinder = NULL;
/** /**
* Column of the cell * Column of the cell
* *
* @var string * @var string
*/ */
private $_column; private $_column;
/** /**
* Row of the cell * Row of the cell
* *
* @var int * @var int
*/ */
private $_row; private $_row;
/** /**
* Value of the cell * Value of the cell
* *
* @var mixed * @var mixed
*/ */
private $_value; private $_value;
/** /**
* Calculated value of the cell (used for caching) * Calculated value of the cell (used for caching)
* This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
* create the original spreadsheet file.
* Note that this value is not guaranteed to reflect the actual calculated value because it is
* possible that auto-calculation was disabled in the original spreadsheet, and underlying data
* values used by the formula have changed since it was last calculated.
* *
* @var mixed * @var mixed
*/ */
private $_calculatedValue = null; private $_calculatedValue = NULL;
/** /**
* Type of the cell data * Type of the cell data
* *
* @var string * @var string
*/ */
private $_dataType; private $_dataType;
/** /**
* Parent worksheet * Parent worksheet
* *
* @var PHPExcel_Worksheet * @var PHPExcel_Worksheet
*/ */
private $_parent; private $_parent;
/** /**
* Index to cellXf * Index to cellXf
* *
* @var int * @var int
*/ */
private $_xfIndex; private $_xfIndex;
/** /**
* Attributes of the formula * Attributes of the formula
*
* *
*/ */
private $_formulaAttributes; private $_formulaAttributes;
/** /**
* Send notification to the cache controller * Send notification to the cache controller
* *
* @return void * @return void
**/ **/
public function notifyCacheController() { public function notifyCacheController() {
$this->_parent->getCellCacheController()->updateCacheData($this); $this->_parent->getCellCacheController()->updateCacheData($this);
@ -110,7 +114,7 @@ class PHPExcel_Cell
} }
public function detach() { public function detach() {
$this->_parent = null; $this->_parent = NULL;
} }
public function attach($parent) { public function attach($parent) {
@ -119,16 +123,16 @@ class PHPExcel_Cell
/** /**
* Create a new Cell * Create a new Cell
* *
* @param string $pColumn * @param string $pColumn
* @param int $pRow * @param int $pRow
* @param mixed $pValue * @param mixed $pValue
* @param string $pDataType * @param string $pDataType
* @param PHPExcel_Worksheet $pSheet * @param PHPExcel_Worksheet $pSheet
* @throws Exception * @throws PHPExcel_Exception
*/ */
public function __construct($pColumn = 'A', $pRow = 1, $pValue = null, $pDataType = null, PHPExcel_Worksheet $pSheet = null) public function __construct($pColumn = 'A', $pRow = 1, $pValue = NULL, $pDataType = NULL, PHPExcel_Worksheet $pSheet = NULL)
{ {
// Initialise cell coordinate // Initialise cell coordinate
$this->_column = strtoupper($pColumn); $this->_column = strtoupper($pColumn);
@ -141,13 +145,13 @@ class PHPExcel_Cell
$this->_parent = $pSheet; $this->_parent = $pSheet;
// Set datatype? // Set datatype?
if ($pDataType !== null) { if ($pDataType !== NULL) {
if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2)
$pDataType = PHPExcel_Cell_DataType::TYPE_STRING; $pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
$this->_dataType = $pDataType; $this->_dataType = $pDataType;
} else { } else {
if (!self::getValueBinder()->bindValue($this, $pValue)) { if (!self::getValueBinder()->bindValue($this, $pValue)) {
throw new Exception("Value could not be bound to cell."); throw new PHPExcel_Exception("Value could not be bound to cell.");
} }
} }
@ -156,9 +160,9 @@ class PHPExcel_Cell
} }
/** /**
* Get cell coordinate column * Get cell coordinate column
* *
* @return string * @return string
*/ */
public function getColumn() public function getColumn()
{ {
@ -166,9 +170,9 @@ class PHPExcel_Cell
} }
/** /**
* Get cell coordinate row * Get cell coordinate row
* *
* @return int * @return int
*/ */
public function getRow() public function getRow()
{ {
@ -176,9 +180,9 @@ class PHPExcel_Cell
} }
/** /**
* Get cell coordinate * Get cell coordinate
* *
* @return string * @return string
*/ */
public function getCoordinate() public function getCoordinate()
{ {
@ -186,9 +190,9 @@ class PHPExcel_Cell
} }
/** /**
* Get cell value * Get cell value
* *
* @return mixed * @return mixed
*/ */
public function getValue() public function getValue()
{ {
@ -196,42 +200,45 @@ class PHPExcel_Cell
} }
/** /**
* Get cell value with formatting * Get cell value with formatting
* *
* @return string * @return string
*/ */
public function getFormattedValue() public function getFormattedValue()
{ {
return (string) PHPExcel_Style_NumberFormat::toFormattedString( $this->getCalculatedValue(), return (string) PHPExcel_Style_NumberFormat::toFormattedString(
$this->_parent->getParent()->getCellXfByIndex($this->getXfIndex())->getNumberFormat()->getFormatCode() $this->getCalculatedValue(),
); $this->_parent->getParent()->getCellXfByIndex($this->getXfIndex())
->getNumberFormat()->getFormatCode()
);
} }
/** /**
* Set cell value * Set cell value
* *
* Sets the value for a cell, automatically determining the datatype using the value binder * Sets the value for a cell, automatically determining the datatype using the value binder
* *
* @param mixed $pValue Value * @param mixed $pValue Value
* @return PHPExcel_Cell * @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/ */
public function setValue($pValue = null) public function setValue($pValue = NULL)
{ {
if (!self::getValueBinder()->bindValue($this, $pValue)) { if (!self::getValueBinder()->bindValue($this, $pValue)) {
throw new Exception("Value could not be bound to cell."); throw new PHPExcel_Exception("Value could not be bound to cell.");
} }
return $this; return $this;
} }
/** /**
* Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder) * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder)
* *
* @param mixed $pValue Value * @param mixed $pValue Value
* @param string $pDataType Explicit data type * @param string $pDataType Explicit data type
* @return PHPExcel_Cell * @return PHPExcel_Cell
* @throws Exception * @throws PHPExcel_Exception
*/ */
public function setValueExplicit($pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING) public function setValueExplicit($pValue = NULL, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING)
{ {
// set the value according to data type // set the value according to data type
switch ($pDataType) { switch ($pDataType) {
@ -242,25 +249,20 @@ class PHPExcel_Cell
case PHPExcel_Cell_DataType::TYPE_INLINE: case PHPExcel_Cell_DataType::TYPE_INLINE:
$this->_value = PHPExcel_Cell_DataType::checkString($pValue); $this->_value = PHPExcel_Cell_DataType::checkString($pValue);
break; break;
case PHPExcel_Cell_DataType::TYPE_NUMERIC: case PHPExcel_Cell_DataType::TYPE_NUMERIC:
$this->_value = (float)$pValue; $this->_value = (float)$pValue;
break; break;
case PHPExcel_Cell_DataType::TYPE_FORMULA: case PHPExcel_Cell_DataType::TYPE_FORMULA:
$this->_value = (string)$pValue; $this->_value = (string)$pValue;
break; break;
case PHPExcel_Cell_DataType::TYPE_BOOL: case PHPExcel_Cell_DataType::TYPE_BOOL:
$this->_value = (bool)$pValue; $this->_value = (bool)$pValue;
break; break;
case PHPExcel_Cell_DataType::TYPE_ERROR: case PHPExcel_Cell_DataType::TYPE_ERROR:
$this->_value = PHPExcel_Cell_DataType::checkErrorCode($pValue); $this->_value = PHPExcel_Cell_DataType::checkErrorCode($pValue);
break; break;
default: default:
throw new Exception('Invalid datatype: ' . $pDataType); throw new PHPExcel_Exception('Invalid datatype: ' . $pDataType);
break; break;
} }
@ -271,13 +273,14 @@ class PHPExcel_Cell
} }
/** /**
* Get calculated cell value * Get calculated cell value
* *
* @deprecated Since version 1.7.8 for planned changes to cell for array formula handling * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling
* *
* @return mixed * @return mixed
* @throws PHPExcel_Exception
*/ */
public function getCalculatedValue($resetLog=true) public function getCalculatedValue($resetLog = TRUE)
{ {
// echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().'<br />'; // echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().'<br />';
if ($this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) { if ($this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) {
@ -292,7 +295,11 @@ class PHPExcel_Cell
} }
// echo 'Calculation Exception: '.$ex->getMessage().'<br />'; // echo 'Calculation Exception: '.$ex->getMessage().'<br />';
$result = '#N/A'; $result = '#N/A';
throw(new Exception($this->getParent()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage())); throw(
new PHPExcel_Exception(
$this->getParent()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage()
)
);
} }
if ($result === '#Not Yet Implemented') { if ($result === '#Not Yet Implemented') {
@ -305,21 +312,19 @@ class PHPExcel_Cell
// if ($this->_value === NULL) { // if ($this->_value === NULL) {
// echo 'Cell '.$this->getCoordinate().' has no value, formula or otherwise<br />'; // echo 'Cell '.$this->getCoordinate().' has no value, formula or otherwise<br />';
// return null; // return NULL;
// } // }
// echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'<br />'; // echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'<br />';
return $this->_value; return $this->_value;
} }
/** /**
* Set calculated value (used for caching) * Set old calculated value (cached)
* *
* @deprecated Since version 1.7.8 for planned changes to cell for array formula handling * @param mixed $pValue Value
* * @return PHPExcel_Cell
* @param mixed $pValue Value
* @return PHPExcel_Cell
*/ */
public function setCalculatedValue($pValue = null) public function setCalculatedValue($pValue = NULL)
{ {
if ($pValue !== NULL) { if ($pValue !== NULL) {
$this->_calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; $this->_calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue;
@ -329,9 +334,14 @@ class PHPExcel_Cell
} }
/** /**
* Get old calculated value (cached) * Get old calculated value (cached)
* This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
* create the original spreadsheet file.
* Note that this value is not guaranteed to refelect the actual calculated value because it is
* possible that auto-calculation was disabled in the original spreadsheet, and underlying data
* values used by the formula have changed since it was last calculated.
* *
* @return mixed * @return mixed
*/ */
public function getOldCalculatedValue() public function getOldCalculatedValue()
{ {
@ -339,9 +349,9 @@ class PHPExcel_Cell
} }
/** /**
* Get cell data type * Get cell data type
* *
* @return string * @return string
*/ */
public function getDataType() public function getDataType()
{ {
@ -349,10 +359,10 @@ class PHPExcel_Cell
} }
/** /**
* Set cell data type * Set cell data type
* *
* @param string $pDataType * @param string $pDataType
* @return PHPExcel_Cell * @return PHPExcel_Cell
*/ */
public function setDataType($pDataType = PHPExcel_Cell_DataType::TYPE_STRING) public function setDataType($pDataType = PHPExcel_Cell_DataType::TYPE_STRING)
{ {
@ -365,44 +375,46 @@ class PHPExcel_Cell
} }
/** /**
* Has Data validation? * Does this cell contain Data validation rules?
* *
* @return boolean * @return boolean
* @throws PHPExcel_Exception
*/ */
public function hasDataValidation() public function hasDataValidation()
{ {
if (!isset($this->_parent)) { if (!isset($this->_parent)) {
throw new Exception('Cannot check for data validation when cell is not bound to a worksheet'); throw new PHPExcel_Exception('Cannot check for data validation when cell is not bound to a worksheet');
} }
return $this->_parent->dataValidationExists($this->getCoordinate()); return $this->_parent->dataValidationExists($this->getCoordinate());
} }
/** /**
* Get Data validation * Get Data validation rules
* *
* @return PHPExcel_Cell_DataValidation * @return PHPExcel_Cell_DataValidation
* @throws PHPExcel_Exception
*/ */
public function getDataValidation() public function getDataValidation()
{ {
if (!isset($this->_parent)) { if (!isset($this->_parent)) {
throw new Exception('Cannot get data validation for cell that is not bound to a worksheet'); throw new PHPExcel_Exception('Cannot get data validation for cell that is not bound to a worksheet');
} }
return $this->_parent->getDataValidation($this->getCoordinate()); return $this->_parent->getDataValidation($this->getCoordinate());
} }
/** /**
* Set Data validation * Set Data validation rules
* *
* @param PHPExcel_Cell_DataValidation $pDataValidation * @param PHPExcel_Cell_DataValidation $pDataValidation
* @throws Exception * @return PHPExcel_Cell
* @return PHPExcel_Cell * @throws PHPExcel_Exception
*/ */
public function setDataValidation(PHPExcel_Cell_DataValidation $pDataValidation = null) public function setDataValidation(PHPExcel_Cell_DataValidation $pDataValidation = NULL)
{ {
if (!isset($this->_parent)) { if (!isset($this->_parent)) {
throw new Exception('Cannot set data validation for cell that is not bound to a worksheet'); throw new PHPExcel_Exception('Cannot set data validation for cell that is not bound to a worksheet');
} }
$this->_parent->setDataValidation($this->getCoordinate(), $pDataValidation); $this->_parent->setDataValidation($this->getCoordinate(), $pDataValidation);
@ -411,45 +423,46 @@ class PHPExcel_Cell
} }
/** /**
* Has Hyperlink * Does this cell contain a Hyperlink?
* *
* @return boolean * @return boolean
* @throws PHPExcel_Exception
*/ */
public function hasHyperlink() public function hasHyperlink()
{ {
if (!isset($this->_parent)) { if (!isset($this->_parent)) {
throw new Exception('Cannot check for hyperlink when cell is not bound to a worksheet'); throw new PHPExcel_Exception('Cannot check for hyperlink when cell is not bound to a worksheet');
} }
return $this->_parent->hyperlinkExists($this->getCoordinate()); return $this->_parent->hyperlinkExists($this->getCoordinate());
} }
/** /**
* Get Hyperlink * Get Hyperlink
* *
* @throws Exception * @return PHPExcel_Cell_Hyperlink
* @return PHPExcel_Cell_Hyperlink * @throws PHPExcel_Exception
*/ */
public function getHyperlink() public function getHyperlink()
{ {
if (!isset($this->_parent)) { if (!isset($this->_parent)) {
throw new Exception('Cannot get hyperlink for cell that is not bound to a worksheet'); throw new PHPExcel_Exception('Cannot get hyperlink for cell that is not bound to a worksheet');
} }
return $this->_parent->getHyperlink($this->getCoordinate()); return $this->_parent->getHyperlink($this->getCoordinate());
} }
/** /**
* Set Hyperlink * Set Hyperlink
* *
* @param PHPExcel_Cell_Hyperlink $pHyperlink * @param PHPExcel_Cell_Hyperlink $pHyperlink
* @throws Exception * @return PHPExcel_Cell
* @return PHPExcel_Cell * @throws PHPExcel_Exception
*/ */
public function setHyperlink(PHPExcel_Cell_Hyperlink $pHyperlink = null) public function setHyperlink(PHPExcel_Cell_Hyperlink $pHyperlink = NULL)
{ {
if (!isset($this->_parent)) { if (!isset($this->_parent)) {
throw new Exception('Cannot set hyperlink for cell that is not bound to a worksheet'); throw new PHPExcel_Exception('Cannot set hyperlink for cell that is not bound to a worksheet');
} }
$this->_parent->setHyperlink($this->getCoordinate(), $pHyperlink); $this->_parent->setHyperlink($this->getCoordinate(), $pHyperlink);
@ -458,19 +471,19 @@ class PHPExcel_Cell
} }
/** /**
* Get parent * Get parent worksheet
* *
* @return PHPExcel_Worksheet * @return PHPExcel_Worksheet
*/ */
public function getParent() { public function getParent() {
return $this->_parent; return $this->_parent;
} }
/** /**
* Re-bind parent * Re-bind parent
* *
* @param PHPExcel_Worksheet $parent * @param PHPExcel_Worksheet $parent
* @return PHPExcel_Cell * @return PHPExcel_Cell
*/ */
public function rebindParent(PHPExcel_Worksheet $parent) { public function rebindParent(PHPExcel_Worksheet $parent) {
$this->_parent = $parent; $this->_parent = $parent;
@ -479,17 +492,17 @@ class PHPExcel_Cell
} }
/** /**
* Is cell in a specific range? * Is cell in a specific range?
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $pRange Cell range (e.g. A1:A1)
* @return boolean * @return boolean
*/ */
public function isInRange($pRange = 'A1:A1') public function isInRange($pRange = 'A1:A1')
{ {
list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange); list($rangeStart,$rangeEnd) = self::rangeBoundaries($pRange);
// Translate properties // Translate properties
$myColumn = PHPExcel_Cell::columnIndexFromString($this->getColumn()); $myColumn = self::columnIndexFromString($this->getColumn());
$myRow = $this->getRow(); $myRow = $this->getRow();
// Verify if cell is in range // Verify if cell is in range
@ -499,80 +512,90 @@ class PHPExcel_Cell
} }
/** /**
* Coordinate from string * Coordinate from string
* *
* @param string $pCoordinateString * @param string $pCoordinateString
* @return array Array containing column and row (indexes 0 and 1) * @return array Array containing column and row (indexes 0 and 1)
* @throws Exception * @throws PHPExcel_Exception
*/ */
public static function coordinateFromString($pCoordinateString = 'A1') public static function coordinateFromString($pCoordinateString = 'A1')
{ {
if (preg_match("/^([$]?[A-Z]{1,3})([$]?\d{1,7})$/", $pCoordinateString, $matches)) { if (preg_match("/^([$]?[A-Z]{1,3})([$]?\d{1,7})$/", $pCoordinateString, $matches)) {
return array($matches[1],$matches[2]); return array($matches[1],$matches[2]);
} elseif ((strpos($pCoordinateString,':') !== false) || (strpos($pCoordinateString,',') !== false)) { } elseif ((strpos($pCoordinateString,':') !== FALSE) || (strpos($pCoordinateString,',') !== FALSE)) {
throw new Exception('Cell coordinate string can not be a range of cells.'); throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
} elseif ($pCoordinateString == '') { } elseif ($pCoordinateString == '') {
throw new Exception('Cell coordinate can not be zero-length string.'); throw new PHPExcel_Exception('Cell coordinate can not be zero-length string');
} else {
throw new Exception('Invalid cell coordinate '.$pCoordinateString);
} }
throw new PHPExcel_Exception('Invalid cell coordinate '.$pCoordinateString);
} }
/** /**
* Make string row, column or cell coordinate absolute * Make string row, column or cell coordinate absolute
* *
* @param string $pCoordinateString e.g. 'A' or '1' or 'A1' * @param string $pCoordinateString e.g. 'A' or '1' or 'A1'
* @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' * Note that this value can be a row or column reference as well as a cell reference
* @throws Exception * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
* @throws PHPExcel_Exception
*/ */
public static function absoluteReference($pCoordinateString = 'A1') public static function absoluteReference($pCoordinateString = 'A1')
{ {
if (strpos($pCoordinateString,':') === false && strpos($pCoordinateString,',') === false) { if (strpos($pCoordinateString,':') === FALSE && strpos($pCoordinateString,',') === FALSE) {
// Split out any worksheet name from the reference
$worksheet = '';
$cellAddress = explode('!',$pCoordinateString);
if (count($cellAddress) > 1) {
list($worksheet,$pCoordinateString) = $cellAddress;
}
if ($worksheet > '') $worksheet .= '!';
// Create absolute coordinate // Create absolute coordinate
if (ctype_digit($pCoordinateString)) { if (ctype_digit($pCoordinateString)) {
return '$'.$pCoordinateString; return $worksheet . '$' . $pCoordinateString;
} elseif (ctype_alpha($pCoordinateString)) { } elseif (ctype_alpha($pCoordinateString)) {
return '$'.strtoupper($pCoordinateString); return $worksheet . '$' . strtoupper($pCoordinateString);
} }
return self::absoluteCoordinate($pCoordinateString); return $worksheet . self::absoluteCoordinate($pCoordinateString);
} else {
throw new Exception("Coordinate string should not be a cell range.");
} }
throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
} }
/** /**
* Make string coordinate absolute * Make string coordinate absolute
* *
* @param string $pCoordinateString e.g. 'A1' * @param string $pCoordinateString e.g. 'A1'
* @return string Absolute coordinate e.g. '$A$1' * @return string Absolute coordinate e.g. '$A$1'
* @throws Exception * @throws PHPExcel_Exception
*/ */
public static function absoluteCoordinate($pCoordinateString = 'A1') public static function absoluteCoordinate($pCoordinateString = 'A1')
{ {
if (strpos($pCoordinateString,':') === false && strpos($pCoordinateString,',') === false) { if (strpos($pCoordinateString,':') === FALSE && strpos($pCoordinateString,',') === FALSE) {
// Create absolute coordinate // Split out any worksheet name from the coordinate
$worksheet = ''; $worksheet = '';
$cellAddress = explode('!',$pCoordinateString); $cellAddress = explode('!',$pCoordinateString);
if (count($cellAddress) == 2) { if (count($cellAddress) > 1) {
list($worksheet,$pCoordinateString) = $cellAddress; list($worksheet,$pCoordinateString) = $cellAddress;
} }
if ($worksheet > '') $worksheet .= '!';
list($column, $row) = PHPExcel_Cell::coordinateFromString($pCoordinateString); // Create absolute coordinate
if ($column[0] == '$') $column = substr($column,1); list($column, $row) = self::coordinateFromString($pCoordinateString);
if ($row[0] == '$') $row = substr($row,1); $column = ltrim($column,'$');
if ($worksheet > '') $row = ltrim($row,'$');
$worksheet .= '!';
return $worksheet . '$' . $column . '$' . $row; return $worksheet . '$' . $column . '$' . $row;
} else {
throw new Exception("Coordinate string should not be a cell range.");
} }
throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
} }
/** /**
* Split range into coordinate strings * Split range into coordinate strings
* *
* @param string $pRange * @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11'
* @return array Array containg one or more arrays containing one or two coordinate strings * @return array Array containg one or more arrays containing one or two coordinate strings
* e.g. array('B4','D9') or array(array('B4','D9'),array('H2','O11'))
*/ */
public static function splitRange($pRange = 'A1:A1') public static function splitRange($pRange = 'A1:A1')
{ {
@ -585,17 +608,17 @@ class PHPExcel_Cell
} }
/** /**
* Build range from coordinate strings * Build range from coordinate strings
* *
* @param array $pRange Array containg one or more arrays containing one or two coordinate strings * @param array $pRange Array containg one or more arrays containing one or two coordinate strings
* @return string String representation of $pRange * @return string String representation of $pRange
* @throws Exception * @throws PHPExcel_Exception
*/ */
public static function buildRange($pRange) public static function buildRange($pRange)
{ {
// Verify range // Verify range
if (!is_array($pRange) || empty($pRange) || !is_array($pRange[0])) { if (!is_array($pRange) || empty($pRange) || !is_array($pRange[0])) {
throw new Exception('Range does not contain any information.'); throw new PHPExcel_Exception('Range does not contain any information');
} }
// Build range // Build range
@ -610,10 +633,10 @@ class PHPExcel_Cell
} }
/** /**
* Calculate range boundaries * Calculate range boundaries
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $pRange Cell range (e.g. A1:A1)
* @return array Range coordinates (Start Cell, End Cell) where Start Cell and End Cell are arrays (Column Number, Row Number) * @return array Range coordinates (Start Cell, End Cell) where Start Cell and End Cell are arrays (Column Number, Row Number)
*/ */
public static function rangeBoundaries($pRange = 'A1:A1') public static function rangeBoundaries($pRange = 'A1:A1')
{ {
@ -621,42 +644,42 @@ class PHPExcel_Cell
$pRange = strtoupper($pRange); $pRange = strtoupper($pRange);
// Extract range // Extract range
if (strpos($pRange, ':') === false) { if (strpos($pRange, ':') === FALSE) {
$rangeA = $rangeB = $pRange; $rangeA = $rangeB = $pRange;
} else { } else {
list($rangeA, $rangeB) = explode(':', $pRange); list($rangeA, $rangeB) = explode(':', $pRange);
} }
// Calculate range outer borders // Calculate range outer borders
$rangeStart = PHPExcel_Cell::coordinateFromString($rangeA); $rangeStart = self::coordinateFromString($rangeA);
$rangeEnd = PHPExcel_Cell::coordinateFromString($rangeB); $rangeEnd = self::coordinateFromString($rangeB);
// Translate column into index // Translate column into index
$rangeStart[0] = PHPExcel_Cell::columnIndexFromString($rangeStart[0]); $rangeStart[0] = self::columnIndexFromString($rangeStart[0]);
$rangeEnd[0] = PHPExcel_Cell::columnIndexFromString($rangeEnd[0]); $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]);
return array($rangeStart, $rangeEnd); return array($rangeStart, $rangeEnd);
} }
/** /**
* Calculate range dimension * Calculate range dimension
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $pRange Cell range (e.g. A1:A1)
* @return array Range dimension (width, height) * @return array Range dimension (width, height)
*/ */
public static function rangeDimension($pRange = 'A1:A1') public static function rangeDimension($pRange = 'A1:A1')
{ {
// Calculate range outer borders // Calculate range outer borders
list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange); list($rangeStart,$rangeEnd) = self::rangeBoundaries($pRange);
return array( ($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1) ); return array( ($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1) );
} }
/** /**
* Calculate range boundaries * Calculate range boundaries
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $pRange Cell range (e.g. A1:A1)
* @return array Range boundaries (staring Column, starting Row, Final Column, Final Row) * @return array Range boundaries (staring Column, starting Row, Final Column, Final Row)
*/ */
public static function getRangeBoundaries($pRange = 'A1:A1') public static function getRangeBoundaries($pRange = 'A1:A1')
{ {
@ -664,7 +687,7 @@ class PHPExcel_Cell
$pRange = strtoupper($pRange); $pRange = strtoupper($pRange);
// Extract range // Extract range
if (strpos($pRange, ':') === false) { if (strpos($pRange, ':') === FALSE) {
$rangeA = $rangeB = $pRange; $rangeA = $rangeB = $pRange;
} else { } else {
list($rangeA, $rangeB) = explode(':', $pRange); list($rangeA, $rangeB) = explode(':', $pRange);
@ -674,11 +697,11 @@ class PHPExcel_Cell
} }
/** /**
* Column index from string * Column index from string
* *
* @param string $pString * @param string $pString
* @return int Column index (base 1 !!!) * @return int Column index (base 1 !!!)
* @throws Exception * @throws Exception
*/ */
public static function columnIndexFromString($pString = 'A') public static function columnIndexFromString($pString = 'A')
{ {
@ -714,14 +737,14 @@ class PHPExcel_Cell
return $_indexCache[$pString]; return $_indexCache[$pString];
} }
} }
throw new Exception("Column string index can not be " . ((isset($pString{0})) ? "longer than 3 characters" : "empty") . "."); throw new PHPExcel_Exception("Column string index can not be " . ((isset($pString{0})) ? "longer than 3 characters" : "empty"));
} }
/** /**
* String from columnindex * String from columnindex
* *
* @param int $pColumnIndex Column index (base 0 !!!) * @param int $pColumnIndex Column index (base 0 !!!)
* @return string * @return string
*/ */
public static function stringFromColumnIndex($pColumnIndex = 0) public static function stringFromColumnIndex($pColumnIndex = 0)
{ {
@ -747,10 +770,10 @@ class PHPExcel_Cell
} }
/** /**
* Extract all cell references in range * Extract all cell references in range
* *
* @param string $pRange Range (e.g. A1 or A1:A10 or A1:A10 A100:A1000) * @param string $pRange Range (e.g. A1 or A1:A10 or A1:A10 A100:A1000)
* @return array Array containing single cell references * @return array Array containing single cell references
*/ */
public static function extractAllCellReferencesInRange($pRange = 'A1') { public static function extractAllCellReferencesInRange($pRange = 'A1') {
// Returnvalue // Returnvalue
@ -760,13 +783,13 @@ class PHPExcel_Cell
$cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange))); $cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange)));
foreach ($cellBlocks as $cellBlock) { foreach ($cellBlocks as $cellBlock) {
// Single cell? // Single cell?
if (strpos($cellBlock,':') === false && strpos($cellBlock,',') === false) { if (strpos($cellBlock,':') === FALSE && strpos($cellBlock,',') === FALSE) {
$returnValue[] = $cellBlock; $returnValue[] = $cellBlock;
continue; continue;
} }
// Range... // Range...
$ranges = PHPExcel_Cell::splitRange($cellBlock); $ranges = self::splitRange($cellBlock);
foreach($ranges as $range) { foreach($ranges as $range) {
// Single cell? // Single cell?
if (!isset($range[1])) { if (!isset($range[1])) {
@ -813,7 +836,7 @@ class PHPExcel_Cell
return -1; return -1;
} elseif ($a->_row > $b->_row) { } elseif ($a->_row > $b->_row) {
return 1; return 1;
} elseif (PHPExcel_Cell::columnIndexFromString($a->_column) < PHPExcel_Cell::columnIndexFromString($b->_column)) { } elseif (self::columnIndexFromString($a->_column) < self::columnIndexFromString($b->_column)) {
return -1; return -1;
} else { } else {
return 1; return 1;
@ -839,7 +862,7 @@ class PHPExcel_Cell
* @param PHPExcel_Cell_IValueBinder $binder * @param PHPExcel_Cell_IValueBinder $binder
* @throws Exception * @throws Exception
*/ */
public static function setValueBinder(PHPExcel_Cell_IValueBinder $binder = null) { public static function setValueBinder(PHPExcel_Cell_IValueBinder $binder = NULL) {
if ($binder === NULL) { if ($binder === NULL) {
throw new Exception("A PHPExcel_Cell_IValueBinder is required for PHPExcel to function correctly."); throw new Exception("A PHPExcel_Cell_IValueBinder is required for PHPExcel to function correctly.");
} }

View File

@ -0,0 +1,52 @@
<?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2012 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/**
* PHPExcel_Exception
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Exception extends Exception {
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context) {
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
}

View File

@ -0,0 +1,259 @@
<?php
require_once 'testDataFileIterator.php';
class CellTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
/**
* @dataProvider providerColumnString
*/
public function testColumnIndexFromString()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','columnIndexFromString'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerColumnString()
{
return new testDataFileIterator('rawTestData/ColumnString.data');
}
public function testColumnIndexFromStringTooLong()
{
$cellAddress = 'ABCD';
try {
$result = call_user_func(array('PHPExcel_Cell','columnIndexFromString'),$cellAddress);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Column string index can not be longer than 3 characters');
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testColumnIndexFromStringTooShort()
{
$cellAddress = '';
try {
$result = call_user_func(array('PHPExcel_Cell','columnIndexFromString'),$cellAddress);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Column string index can not be empty');
return;
}
$this->fail('An expected exception has not been raised.');
}
/**
* @dataProvider providerColumnIndex
*/
public function testStringFromColumnIndex()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','stringFromColumnIndex'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerColumnIndex()
{
return new testDataFileIterator('rawTestData/ColumnIndex.data');
}
/**
* @dataProvider providerCoordinates
*/
public function testCoordinateFromString()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','coordinateFromString'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerCoordinates()
{
return new testDataFileIterator('rawTestData/CellCoordinates.data');
}
public function testCoordinateFromStringWithRangeAddress()
{
$cellAddress = 'A1:AI2012';
try {
$result = call_user_func(array('PHPExcel_Cell','coordinateFromString'),$cellAddress);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testCoordinateFromStringWithEmptyAddress()
{
$cellAddress = '';
try {
$result = call_user_func(array('PHPExcel_Cell','coordinateFromString'),$cellAddress);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Cell coordinate can not be zero-length string');
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testCoordinateFromStringWithInvalidAddress()
{
$cellAddress = 'AI';
try {
$result = call_user_func(array('PHPExcel_Cell','coordinateFromString'),$cellAddress);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Invalid cell coordinate '.$cellAddress);
return;
}
$this->fail('An expected exception has not been raised.');
}
/**
* @dataProvider providerAbsoluteCoordinates
*/
public function testAbsoluteCoordinateFromString()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','absoluteCoordinate'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerAbsoluteCoordinates()
{
return new testDataFileIterator('rawTestData/CellAbsoluteCoordinate.data');
}
public function testAbsoluteCoordinateFromStringWithRangeAddress()
{
$cellAddress = 'A1:AI2012';
try {
$result = call_user_func(array('PHPExcel_Cell','absoluteCoordinate'),$cellAddress);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
return;
}
$this->fail('An expected exception has not been raised.');
}
/**
* @dataProvider providerAbsoluteReferences
*/
public function testAbsoluteReferenceFromString()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','absoluteReference'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerAbsoluteReferences()
{
return new testDataFileIterator('rawTestData/CellAbsoluteReference.data');
}
public function testAbsoluteReferenceFromStringWithRangeAddress()
{
$cellAddress = 'A1:AI2012';
try {
$result = call_user_func(array('PHPExcel_Cell','absoluteReference'),$cellAddress);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
return;
}
$this->fail('An expected exception has not been raised.');
}
/**
* @dataProvider providerSplitRange
*/
public function testSplitRange()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','splitRange'),$args);
foreach($result as $key => $split) {
$this->assertEquals($expectedResult[$key], $split);
}
}
public function providerSplitRange()
{
return new testDataFileIterator('rawTestData/CellSplitRange.data');
}
/**
* @dataProvider providerBuildRange
*/
public function testBuildRange()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','buildRange'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerBuildRange()
{
return new testDataFileIterator('rawTestData/CellBuildRange.data');
}
public function testBuildRangeInvalid()
{
$cellRange = '';
try {
$result = call_user_func(array('PHPExcel_Cell','buildRange'),$cellRange);
} catch (PHPExcel_Exception $e) {
$this->assertEquals($e->getMessage(), 'Range does not contain any information');
return;
}
$this->fail('An expected exception has not been raised.');
}
/**
* @dataProvider providerRangeBoundaries
*/
public function testRangeBoundaries()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','rangeBoundaries'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerRangeBoundaries()
{
return new testDataFileIterator('rawTestData/CellRangeBoundaries.data');
}
/**
* @dataProvider providerRangeDimension
*/
public function testRangeDimension()
{
$args = func_get_args();
$expectedResult = array_pop($args);
$result = call_user_func_array(array('PHPExcel_Cell','rangeDimension'),$args);
$this->assertEquals($expectedResult, $result);
}
public function providerRangeDimension()
{
return new testDataFileIterator('rawTestData/CellRangeDimension.data');
}
}

View File

@ -0,0 +1,12 @@
"A1", "$A$1"
"A12", "$A$12"
"J1", "$J$1"
"J20", "$J$20"
"AI1", "$AI$1"
"AI2012", "$AI$2012"
"'Worksheet1'!AI256", "'Worksheet1'!$AI$256"
"Worksheet1!AI256", "Worksheet1!$AI$256"
"'Data Worksheet'!AI256", "'Data Worksheet'!$AI$256"
"'Worksheet1'!$AI256", "'Worksheet1'!$AI$256"
"'Worksheet1'!AI$256", "'Worksheet1'!$AI$256"
"'Worksheet1'!$AI$256", "'Worksheet1'!$AI$256"

View File

@ -0,0 +1,16 @@
"A1", "$A$1"
"A12", "$A$12"
"J1", "$J$1"
"J20", "$J$20"
"AI1", "$AI$1"
"AI2012", "$AI$2012"
"'Worksheet1'!AI256", "'Worksheet1'!$AI$256"
"Worksheet1!AI256", "Worksheet1!$AI$256"
"'Data Worksheet'!AI256", "'Data Worksheet'!$AI$256"
"AI", "$AI"
2012, "$2012"
"Worksheet1!AI", "Worksheet1!$AI"
"Worksheet1!256", "Worksheet1!$256"
"'Worksheet1'!$AI256", "'Worksheet1'!$AI$256"
"'Worksheet1'!AI$256", "'Worksheet1'!$AI$256"
"'Worksheet1'!$AI$256", "'Worksheet1'!$AI$256"

View File

@ -0,0 +1,2 @@
{"B4"|"E9"}, "B4:E9"
{"B4"|"E9";"H2"|"O11"}, "B4:E9,H2:O11"

View File

@ -0,0 +1,6 @@
"A1", {"A";1}
"A12", {"A";12}
"J1", {"J";1}
"J20", {"J";20}
"AI1", {"AI";1}
"AI2012", {"AI";2012}

View File

@ -0,0 +1,2 @@
"B4:E9", {2|4;5|9}
"B4", {2|4;2|4}

View File

@ -0,0 +1,2 @@
"B4:E9", {4;6}
"B4", {1;1}

View File

@ -0,0 +1,3 @@
"B4:E9", {"B4"|"E9"}
"B4", {"B4"}
"B4:E9,H2:O11", {"B4"|"E9";"H2"|"O11"}

View File

@ -0,0 +1,9 @@
0, "A"
25, "Z"
26, "AA"
27, "AB"
51, "AZ"
52, "BA"
701, "ZZ"
702, "AAA"
1378, "BAA"

View File

@ -0,0 +1,9 @@
"A", 1
"Z", 26
"AA", 27
"AB", 28
"AZ", 52
"BA", 53
"ZZ", 702
"AAA", 703
"BAA", 1379