Introduce PHP-CS-Fixer for stricter code style rules

PHP-CS-Fixer allow to check different things than phpcs and it allows
code to be more consistent. Configuration can be changed in `.php_cs`
This commit is contained in:
Adrien Crivelli 2016-08-17 00:33:57 +09:00
parent 685e29d8ff
commit 09d456e477
No known key found for this signature in database
GPG Key ID: B182FD79DC6DE92E
256 changed files with 11454 additions and 11579 deletions

108
.php_cs Normal file
View File

@ -0,0 +1,108 @@
<?php
$finder = Symfony\CS\Finder\DefaultFinder::create()
->exclude('vendor')
->in('src')
->in('tests');
return Symfony\CS\Config\Config::create()
->level(Symfony\CS\FixerInterface::NONE_LEVEL)
->fixers([
// 'align_double_arrow', // Waste of time
// 'align_equals', // Waste of time
'array_element_no_space_before_comma',
'array_element_white_space_after_comma',
'blankline_after_open_tag',
'braces',
// 'concat_without_spaces', // This make it less readable
'concat_with_spaces',
'double_arrow_multiline_whitespaces',
'duplicate_semicolon',
// 'echo_to_print', // We prefer echo
'elseif',
// 'empty_return', // even if technically useless, we prefer to be explicit with our intent to return null
'encoding',
'eof_ending',
'ereg_to_preg',
'extra_empty_lines',
'function_call_space',
'function_declaration',
'function_typehint_space',
// 'header_comment', // We don't use common header in all our files
'include',
'indentation',
'join_function',
'line_after_namespace',
'linefeed',
'list_commas',
// 'logical_not_operators_with_spaces', // No we prefer to keep "!" without spaces
// 'logical_not_operators_with_successor_space', // idem
// 'long_array_syntax', // We opted in for the short syntax
'lowercase_constants',
'lowercase_keywords',
'method_argument_space',
'multiline_array_trailing_comma',
'multiline_spaces_before_semicolon',
'multiple_use',
'namespace_no_leading_whitespace',
'newline_after_open_tag',
'new_with_braces',
'no_blank_lines_after_class_opening',
// 'no_blank_lines_before_namespace', // we want 1 blank line before namespace
'no_empty_lines_after_phpdocs',
'object_operator',
'operators_spaces',
'ordered_use',
'parenthesis',
'php4_constructor',
'php_closing_tag',
'phpdoc_indent',
'phpdoc_inline_tag',
'phpdoc_no_access',
'phpdoc_no_empty_return',
'phpdoc_no_package',
'phpdoc_order',
// 'phpdoc_params', // Waste of time
'phpdoc_scalar',
// 'phpdoc_separation', // Nope, annotations are easy to read enough, no need to split them with blank lines
// 'phpdoc_short_description', // We usually don't generate documentation so punctuation is not important
'phpdoc_to_comment',
'phpdoc_trim',
'phpdoc_types',
'phpdoc_type_to_var',
// 'phpdoc_var_to_type', // This is not supported by phpDoc2 anymore
'phpdoc_var_without_name',
'php_unit_construct',
// 'php_unit_strict', // We sometime actually need assertEquals
'pre_increment',
'print_to_echo',
'psr0',
'remove_leading_slash_use',
'remove_lines_between_uses',
'return',
'self_accessor',
'short_array_syntax',
'short_bool_cast',
'short_echo_tag',
'short_tag',
'single_array_no_trailing_comma',
'single_blank_line_before_namespace',
'single_line_after_imports',
'single_quote',
'spaces_before_semicolon',
'spaces_cast',
'standardize_not_equal',
// 'strict', // No, too dangerous to change that
// 'strict_param', // No, too dangerous to change that
// 'ternary_spaces', // That would be nice, but NetBeans does not cooperate :-(
'trailing_spaces',
'trim_array_spaces',
'unalign_double_arrow',
'unalign_equals',
'unary_operators_spaces',
'unneeded_control_parentheses',
'unused_use',
'visibility',
'whitespacy_lines',
])
->finder($finder);

View File

@ -27,6 +27,8 @@ before_script:
script: script:
## PHP_CodeSniffer ## PHP_CodeSniffer
- ./vendor/bin/phpcs --report-width=200 --report-summary --report-full src/ tests/ --standard=PSR2 -n - ./vendor/bin/phpcs --report-width=200 --report-summary --report-full src/ tests/ --standard=PSR2 -n
## PHP-CS-Fixer
- ./vendor/bin/php-cs-fixer fix . --diff
## PHPUnit ## PHPUnit
- ./vendor/bin/phpunit --coverage-clover coverage-clover.xml - ./vendor/bin/phpunit --coverage-clover coverage-clover.xml

View File

@ -31,7 +31,8 @@
"require-dev": { "require-dev": {
"squizlabs/php_codesniffer": "2.*", "squizlabs/php_codesniffer": "2.*",
"phpunit/phpunit": "4.6.*", "phpunit/phpunit": "4.6.*",
"mikey179/vfsStream": "1.5.*" "mikey179/vfsStream": "1.5.*",
"friendsofphp/php-cs-fixer": "^1.11"
}, },
"suggest": { "suggest": {
"ext-zip": "*", "ext-zip": "*",

View File

@ -3,7 +3,6 @@
namespace PhpSpreadsheet; namespace PhpSpreadsheet;
/** /**
*
* Autoloader for PhpSpreadsheet classes * Autoloader for PhpSpreadsheet classes
* *
* Copyright (c) 2006 - 2016 PhpSpreadsheet * Copyright (c) 2006 - 2016 PhpSpreadsheet
@ -31,7 +30,6 @@ class Autoloader
{ {
/** /**
* Register the Autoloader with SPL * Register the Autoloader with SPL
*
*/ */
public static function register() public static function register()
{ {
@ -40,10 +38,9 @@ class Autoloader
spl_autoload_register('__autoload'); spl_autoload_register('__autoload');
} }
// Register ourselves with SPL // Register ourselves with SPL
return spl_autoload_register(array(\PhpSpreadsheet\Autoloader::class, 'load')); return spl_autoload_register([\PhpSpreadsheet\Autoloader::class, 'load']);
} }
/** /**
* Autoload a class identified by name * Autoload a class identified by name
* *
@ -65,6 +62,6 @@ class Autoloader
// Can't load // Can't load
return false; return false;
} }
require($classFilePath); require $classFilePath;
} }
} }

View File

@ -1,7 +1,6 @@
<?php <?php
/** /**
*
* Bootstrap for PhpSpreadsheet classes * Bootstrap for PhpSpreadsheet classes
* *
* Copyright (c) 2006 - 2016 PhpSpreadsheet * Copyright (c) 2006 - 2016 PhpSpreadsheet
@ -25,7 +24,6 @@
* @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##
*/ */
include_once __DIR__ . '/Autoloader.php'; include_once __DIR__ . '/Autoloader.php';
\PhpSpreadsheet\Autoloader::register(); \PhpSpreadsheet\Autoloader::register();

View File

@ -29,7 +29,6 @@ class APC extends CacheBase implements ICache
/** /**
* Prefix used to uniquely identify cache data for this worksheet * Prefix used to uniquely identify cache data for this worksheet
* *
* @access private
* @var string * @var string
*/ */
private $cachePrefix = null; private $cachePrefix = null;
@ -37,8 +36,7 @@ class APC extends CacheBase implements ICache
/** /**
* Cache timeout * Cache timeout
* *
* @access private * @var int
* @var integer
*/ */
private $cacheTime = 600; private $cacheTime = 600;
@ -46,7 +44,6 @@ class APC extends CacheBase implements ICache
* Store cell data in cache for the current cell object if it's "dirty", * Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object * and the 'nullify' the current cell object
* *
* @access private
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
protected function storeData() protected function storeData()
@ -70,11 +67,10 @@ class APC extends CacheBase implements ICache
/** /**
* Add or Update a cell in cache identified by coordinate address * Add or Update a cell in cache identified by coordinate address
* *
* @access public
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -93,10 +89,9 @@ class APC extends CacheBase implements ICache
/** /**
* Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell? * Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell?
* *
* @access public
* @param string $pCoord Coordinate address of the cell to check * @param string $pCoord Coordinate address of the cell to check
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return boolean * @return bool
*/ */
public function isDataSet($pCoord) public function isDataSet($pCoord)
{ {
@ -106,21 +101,22 @@ class APC extends CacheBase implements ICache
return true; return true;
} }
// Check if the requested entry still exists in apc // Check if the requested entry still exists in apc
$success = apc_fetch($this->cachePrefix.$pCoord.'.cache'); $success = apc_fetch($this->cachePrefix . $pCoord . '.cache');
if ($success === false) { if ($success === false) {
// Entry no longer exists in APC, so clear it from the cache array // Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($pCoord); parent::deleteCacheData($pCoord);
throw new \PhpSpreadsheet\Exception('Cell entry '.$pCoord.' no longer exists in APC cache'); throw new \PhpSpreadsheet\Exception('Cell entry ' . $pCoord . ' no longer exists in APC cache');
} }
return true; return true;
} }
return false; return false;
} }
/** /**
* Get cell at a specific coordinate * Get cell at a specific coordinate
* *
* @access public
* @param string $pCoord Coordinate of the cell * @param string $pCoord Coordinate of the cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell Cell that was found, or null if not found * @return \PhpSpreadsheet\Cell Cell that was found, or null if not found
@ -138,7 +134,7 @@ class APC extends CacheBase implements ICache
if ($obj === false) { if ($obj === false) {
// Entry no longer exists in APC, so clear it from the cache array // Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($pCoord); parent::deleteCacheData($pCoord);
throw new \PhpSpreadsheet\Exception('Cell entry '.$pCoord.' no longer exists in APC cache'); throw new \PhpSpreadsheet\Exception('Cell entry ' . $pCoord . ' no longer exists in APC cache');
} }
} else { } else {
// Return null if requested entry doesn't exist in cache // Return null if requested entry doesn't exist in cache
@ -172,14 +168,13 @@ class APC extends CacheBase implements ICache
/** /**
* Delete a cell in cache identified by coordinate address * Delete a cell in cache identified by coordinate address
* *
* @access public
* @param string $pCoord Coordinate address of the cell to delete * @param string $pCoord Coordinate address of the cell to delete
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
public function deleteCacheData($pCoord) public function deleteCacheData($pCoord)
{ {
// Delete the entry from APC // Delete the entry from APC
apc_delete($this->cachePrefix.$pCoord.'.cache'); apc_delete($this->cachePrefix . $pCoord . '.cache');
// Delete the entry from our cell address array // Delete the entry from our cell address array
parent::deleteCacheData($pCoord); parent::deleteCacheData($pCoord);
@ -188,7 +183,6 @@ class APC extends CacheBase implements ICache
/** /**
* Clone the cell collection * Clone the cell collection
* *
* @access public
* @param \PhpSpreadsheet\Worksheet $parent The new worksheet that we're copying to * @param \PhpSpreadsheet\Worksheet $parent The new worksheet that we're copying to
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
@ -218,8 +212,6 @@ class APC extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -231,7 +223,7 @@ class APC extends CacheBase implements ICache
// Flush the APC cache // Flush the APC cache
$this->__destruct(); $this->__destruct();
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;
@ -271,7 +263,7 @@ class APC extends CacheBase implements ICache
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable() public static function cacheMethodIsAvailable()
{ {

View File

@ -50,7 +50,7 @@ abstract class CacheBase
/** /**
* Flag indicating whether the currently active Cell requires saving * Flag indicating whether the currently active Cell requires saving
* *
* @var boolean * @var bool
*/ */
protected $currentCellIsDirty = true; protected $currentCellIsDirty = true;
@ -60,7 +60,7 @@ abstract class CacheBase
* *
* @var array of mixed * @var array of mixed
*/ */
protected $cellCache = array(); protected $cellCache = [];
/** /**
* Initialise this new cell collection * Initialise this new cell collection
@ -89,7 +89,7 @@ abstract class CacheBase
* Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell? * Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell?
* *
* @param string $pCoord Coordinate address of the cell to check * @param string $pCoord Coordinate address of the cell to check
* @return boolean * @return bool
*/ */
public function isDataSet($pCoord) public function isDataSet($pCoord)
{ {
@ -105,7 +105,7 @@ abstract class CacheBase
* *
* @param string $fromAddress Current address of the cell to move * @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move * @param string $toAddress Destination address of the cell to move
* @return boolean * @return bool
*/ */
public function moveCell($fromAddress, $toAddress) public function moveCell($fromAddress, $toAddress)
{ {
@ -125,8 +125,8 @@ abstract class CacheBase
* Add or Update a cell in cache * Add or Update a cell in cache
* *
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function updateCacheData(\PhpSpreadsheet\Cell $cell) public function updateCacheData(\PhpSpreadsheet\Cell $cell)
{ {
@ -170,7 +170,7 @@ abstract class CacheBase
*/ */
public function getSortedCellList() public function getSortedCellList()
{ {
$sortKeys = array(); $sortKeys = [];
foreach ($this->getCellList() as $coord) { foreach ($this->getCellList() as $coord) {
sscanf($coord, '%[A-Z]%d', $column, $row); sscanf($coord, '%[A-Z]%d', $column, $row);
$sortKeys[sprintf('%09d%3s', $row, $column)] = $coord; $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord;
@ -188,12 +188,12 @@ abstract class CacheBase
public function getHighestRowAndColumn() public function getHighestRowAndColumn()
{ {
// Lookup highest column and highest row // Lookup highest column and highest row
$col = array('A' => '1A'); $col = ['A' => '1A'];
$row = array(1); $row = [1];
foreach ($this->getCellList() as $coord) { foreach ($this->getCellList() as $coord) {
sscanf($coord, '%[A-Z]%d', $c, $r); sscanf($coord, '%[A-Z]%d', $c, $r);
$row[$r] = $r; $row[$r] = $r;
$col[$c] = strlen($c).$c; $col[$c] = strlen($c) . $c;
} }
if (!empty($row)) { if (!empty($row)) {
// Determine highest column and row // Determine highest column and row
@ -201,10 +201,10 @@ abstract class CacheBase
$highestColumn = substr(max($col), 1); $highestColumn = substr(max($col), 1);
} }
return array( return [
'row' => $highestRow, 'row' => $highestRow,
'column' => $highestColumn 'column' => $highestColumn,
); ];
} }
/** /**
@ -225,17 +225,19 @@ abstract class CacheBase
public function getCurrentColumn() public function getCurrentColumn()
{ {
sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row); sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row);
return $column; return $column;
} }
/** /**
* Return the row address of the currently active cell object * Return the row address of the currently active cell object
* *
* @return integer * @return int
*/ */
public function getCurrentRow() public function getCurrentRow()
{ {
sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row); sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row);
return (integer) $row; return (integer) $row;
} }
@ -250,10 +252,11 @@ abstract class CacheBase
{ {
if ($row == null) { if ($row == null) {
$colRow = $this->getHighestRowAndColumn(); $colRow = $this->getHighestRowAndColumn();
return $colRow['column']; return $colRow['column'];
} }
$columnList = array(1); $columnList = [1];
foreach ($this->getCellList() as $coord) { foreach ($this->getCellList() as $coord) {
sscanf($coord, '%[A-Z]%d', $c, $r); sscanf($coord, '%[A-Z]%d', $c, $r);
if ($r != $row) { if ($r != $row) {
@ -261,6 +264,7 @@ abstract class CacheBase
} }
$columnList[] = \PhpSpreadsheet\Cell::columnIndexFromString($c); $columnList[] = \PhpSpreadsheet\Cell::columnIndexFromString($c);
} }
return \PhpSpreadsheet\Cell::stringFromColumnIndex(max($columnList) - 1); return \PhpSpreadsheet\Cell::stringFromColumnIndex(max($columnList) - 1);
} }
@ -275,10 +279,11 @@ abstract class CacheBase
{ {
if ($column == null) { if ($column == null) {
$colRow = $this->getHighestRowAndColumn(); $colRow = $this->getHighestRowAndColumn();
return $colRow['row']; return $colRow['row'];
} }
$rowList = array(0); $rowList = [0];
foreach ($this->getCellList() as $coord) { foreach ($this->getCellList() as $coord) {
sscanf($coord, '%[A-Z]%d', $c, $r); sscanf($coord, '%[A-Z]%d', $c, $r);
if ($c != $column) { if ($c != $column) {
@ -302,6 +307,7 @@ abstract class CacheBase
} else { } else {
$baseUnique = mt_rand(); $baseUnique = mt_rand();
} }
return uniqid($baseUnique, true); return uniqid($baseUnique, true);
} }
@ -325,7 +331,6 @@ abstract class CacheBase
* Remove a row, deleting all cells in that row * Remove a row, deleting all cells in that row
* *
* @param string $row Row number to remove * @param string $row Row number to remove
* @return void
*/ */
public function removeRow($row) public function removeRow($row)
{ {
@ -341,7 +346,6 @@ abstract class CacheBase
* Remove a column, deleting all cells in that column * Remove a column, deleting all cells in that column
* *
* @param string $column Column ID to remove * @param string $column Column ID to remove
* @return void
*/ */
public function removeColumn($column) public function removeColumn($column)
{ {
@ -357,7 +361,7 @@ abstract class CacheBase
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable() public static function cacheMethodIsAvailable()
{ {

View File

@ -51,7 +51,6 @@ class DiscISAM extends CacheBase implements ICache
* Store cell data in cache for the current cell object if it's "dirty", * Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object * and the 'nullify' the current cell object
* *
* @return void
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
protected function storeData() protected function storeData()
@ -61,10 +60,10 @@ class DiscISAM extends CacheBase implements ICache
fseek($this->fileHandle, 0, SEEK_END); fseek($this->fileHandle, 0, SEEK_END);
$this->cellCache[$this->currentObjectID] = array( $this->cellCache[$this->currentObjectID] = [
'ptr' => ftell($this->fileHandle), 'ptr' => ftell($this->fileHandle),
'sz' => fwrite($this->fileHandle, serialize($this->currentObject)) 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)),
); ];
$this->currentCellIsDirty = false; $this->currentCellIsDirty = false;
} }
$this->currentObjectID = $this->currentObject = null; $this->currentObjectID = $this->currentObject = null;
@ -75,8 +74,8 @@ class DiscISAM extends CacheBase implements ICache
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -146,7 +145,7 @@ class DiscISAM extends CacheBase implements ICache
parent::copyCellCollection($parent); parent::copyCellCollection($parent);
// Get a new id for the new file name // Get a new id for the new file name
$baseUnique = $this->getUniqueID(); $baseUnique = $this->getUniqueID();
$newFileName = $this->cacheDirectory.'/PhpSpreadsheet.'.$baseUnique.'.cache'; $newFileName = $this->cacheDirectory . '/PhpSpreadsheet.' . $baseUnique . '.cache';
// Copy the existing cell cache file // Copy the existing cell cache file
copy($this->fileName, $newFileName); copy($this->fileName, $newFileName);
$this->fileName = $newFileName; $this->fileName = $newFileName;
@ -156,7 +155,6 @@ class DiscISAM extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -164,7 +162,7 @@ class DiscISAM extends CacheBase implements ICache
$this->currentObject->detach(); $this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null; $this->currentObject = $this->currentObjectID = null;
} }
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;
@ -181,14 +179,14 @@ class DiscISAM extends CacheBase implements ICache
*/ */
public function __construct(\PhpSpreadsheet\Worksheet $parent, $arguments) public function __construct(\PhpSpreadsheet\Worksheet $parent, $arguments)
{ {
$this->cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== null)) $this->cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== null))
? $arguments['dir'] ? $arguments['dir']
: \PhpSpreadsheet\Shared\File::sysGetTempDir(); : \PhpSpreadsheet\Shared\File::sysGetTempDir();
parent::__construct($parent); parent::__construct($parent);
if (is_null($this->fileHandle)) { if (is_null($this->fileHandle)) {
$baseUnique = $this->getUniqueID(); $baseUnique = $this->getUniqueID();
$this->fileName = $this->cacheDirectory.'/PhpSpreadsheet.'.$baseUnique.'.cache'; $this->fileName = $this->cacheDirectory . '/PhpSpreadsheet.' . $baseUnique . '.cache';
$this->fileHandle = fopen($this->fileName, 'a+'); $this->fileHandle = fopen($this->fileName, 'a+');
} }
} }

View File

@ -31,8 +31,8 @@ interface ICache
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell); public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell);
@ -40,8 +40,8 @@ interface ICache
* Add or Update a cell in cache * Add or Update a cell in cache
* *
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function updateCacheData(\PhpSpreadsheet\Cell $cell); public function updateCacheData(\PhpSpreadsheet\Cell $cell);
@ -49,8 +49,8 @@ interface ICache
* Fetch a cell from cache identified by coordinate address * Fetch a cell from cache identified by coordinate address
* *
* @param string $pCoord Coordinate address of the cell to retrieve * @param string $pCoord Coordinate address of the cell to retrieve
* @return \PhpSpreadsheet\Cell Cell that was found, or null if not found
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell Cell that was found, or null if not found
*/ */
public function getCacheData($pCoord); public function getCacheData($pCoord);
@ -66,7 +66,7 @@ interface ICache
* Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell? * Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell?
* *
* @param string $pCoord Coordinate address of the cell to check * @param string $pCoord Coordinate address of the cell to check
* @return boolean * @return bool
*/ */
public function isDataSet($pCoord); public function isDataSet($pCoord);
@ -95,7 +95,7 @@ interface ICache
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable(); public static function cacheMethodIsAvailable();
} }

View File

@ -30,7 +30,6 @@ class Igbinary extends CacheBase implements ICache
* Store cell data in cache for the current cell object if it's "dirty", * Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object * and the 'nullify' the current cell object
* *
* @return void
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
protected function storeData() protected function storeData()
@ -44,14 +43,13 @@ class Igbinary extends CacheBase implements ICache
$this->currentObjectID = $this->currentObject = null; $this->currentObjectID = $this->currentObject = null;
} // function _storeData() } // function _storeData()
/** /**
* Add or Update a cell in cache identified by coordinate address * Add or Update a cell in cache identified by coordinate address
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -66,7 +64,6 @@ class Igbinary extends CacheBase implements ICache
return $cell; return $cell;
} }
/** /**
* Get cell at a specific coordinate * Get cell at a specific coordinate
* *
@ -97,7 +94,6 @@ class Igbinary extends CacheBase implements ICache
return $this->currentObject; return $this->currentObject;
} // function getCacheData() } // function getCacheData()
/** /**
* Get a list of all cell addresses currently held in cache * Get a list of all cell addresses currently held in cache
* *
@ -112,11 +108,8 @@ class Igbinary extends CacheBase implements ICache
return parent::getCellList(); return parent::getCellList();
} }
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -124,18 +117,17 @@ class Igbinary extends CacheBase implements ICache
$this->currentObject->detach(); $this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null; $this->currentObject = $this->currentObjectID = null;
} }
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;
} // function unsetWorksheetCells() } // function unsetWorksheetCells()
/** /**
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable() public static function cacheMethodIsAvailable()
{ {

View File

@ -36,7 +36,7 @@ class Memcache extends CacheBase implements ICache
/** /**
* Cache timeout * Cache timeout
* *
* @var integer * @var int
*/ */
private $cacheTime = 600; private $cacheTime = 600;
@ -47,7 +47,6 @@ class Memcache extends CacheBase implements ICache
*/ */
private $memcache = null; private $memcache = null;
/** /**
* Store cell data in cache for the current cell object if it's "dirty", * Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object * and the 'nullify' the current cell object
@ -71,14 +70,13 @@ class Memcache extends CacheBase implements ICache
$this->currentObjectID = $this->currentObject = null; $this->currentObjectID = $this->currentObject = null;
} }
/** /**
* Add or Update a cell in cache identified by coordinate address * Add or Update a cell in cache identified by coordinate address
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -94,13 +92,12 @@ class Memcache extends CacheBase implements ICache
return $cell; return $cell;
} }
/** /**
* Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell? * Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell?
* *
* @param string $pCoord Coordinate address of the cell to check * @param string $pCoord Coordinate address of the cell to check
* @return boolean
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return bool
*/ */
public function isDataSet($pCoord) public function isDataSet($pCoord)
{ {
@ -110,18 +107,19 @@ class Memcache extends CacheBase implements ICache
return true; return true;
} }
// Check if the requested entry still exists in Memcache // Check if the requested entry still exists in Memcache
$success = $this->memcache->get($this->cachePrefix.$pCoord.'.cache'); $success = $this->memcache->get($this->cachePrefix . $pCoord . '.cache');
if ($success === false) { if ($success === false) {
// Entry no longer exists in Memcache, so clear it from the cache array // Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($pCoord); parent::deleteCacheData($pCoord);
throw new \PhpSpreadsheet\Exception('Cell entry '.$pCoord.' no longer exists in MemCache'); throw new \PhpSpreadsheet\Exception('Cell entry ' . $pCoord . ' no longer exists in MemCache');
} }
return true; return true;
} }
return false; return false;
} }
/** /**
* Get cell at a specific coordinate * Get cell at a specific coordinate
* *
@ -203,7 +201,7 @@ class Memcache extends CacheBase implements ICache
$cacheList = $this->getCellList(); $cacheList = $this->getCellList();
foreach ($cacheList as $cellID) { foreach ($cacheList as $cellID) {
if ($cellID != $this->currentObjectID) { if ($cellID != $this->currentObjectID) {
$obj = $this->memcache->get($this->cachePrefix.$cellID.'.cache'); $obj = $this->memcache->get($this->cachePrefix . $cellID . '.cache');
if ($obj === false) { if ($obj === false) {
// Entry no longer exists in Memcache, so clear it from the cache array // Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($cellID); parent::deleteCacheData($cellID);
@ -220,8 +218,6 @@ class Memcache extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -233,7 +229,7 @@ class Memcache extends CacheBase implements ICache
// Flush the Memcache cache // Flush the Memcache cache
$this->__destruct(); $this->__destruct();
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;
@ -257,8 +253,8 @@ class Memcache extends CacheBase implements ICache
$this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.'; $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.';
// Set a new Memcache object and connect to the Memcache server // Set a new Memcache object and connect to the Memcache server
$this->memcache = new Memcache(); $this->memcache = new self();
if (!$this->memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) { if (!$this->memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, [$this, 'failureCallback'])) {
throw new \PhpSpreadsheet\Exception("Could not connect to MemCache server at {$memcacheServer}:{$memcachePort}"); throw new \PhpSpreadsheet\Exception("Could not connect to MemCache server at {$memcacheServer}:{$memcachePort}");
} }
$this->cacheTime = $cacheTime; $this->cacheTime = $cacheTime;
@ -271,7 +267,7 @@ class Memcache extends CacheBase implements ICache
* Memcache error handler * Memcache error handler
* *
* @param string $host Memcache server * @param string $host Memcache server
* @param integer $port Memcache port * @param int $port Memcache port
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
public function failureCallback($host, $port) public function failureCallback($host, $port)
@ -286,7 +282,7 @@ class Memcache extends CacheBase implements ICache
{ {
$cacheList = $this->getCellList(); $cacheList = $this->getCellList();
foreach ($cacheList as $cellID) { foreach ($cacheList as $cellID) {
$this->memcache->delete($this->cachePrefix.$cellID . '.cache'); $this->memcache->delete($this->cachePrefix . $cellID . '.cache');
} }
} }
@ -294,7 +290,7 @@ class Memcache extends CacheBase implements ICache
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable() public static function cacheMethodIsAvailable()
{ {

View File

@ -28,8 +28,6 @@ class Memory extends CacheBase implements ICache
{ {
/** /**
* Dummy method callable from CacheBase, but unused by Memory cache * Dummy method callable from CacheBase, but unused by Memory cache
*
* @return void
*/ */
protected function storeData() protected function storeData()
{ {
@ -40,8 +38,8 @@ class Memory extends CacheBase implements ICache
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -53,7 +51,6 @@ class Memory extends CacheBase implements ICache
return $cell; return $cell;
} }
/** /**
* Get cell at a specific coordinate * Get cell at a specific coordinate
* *
@ -77,7 +74,6 @@ class Memory extends CacheBase implements ICache
return $this->cellCache[$pCoord]; return $this->cellCache[$pCoord];
} }
/** /**
* Clone the cell collection * Clone the cell collection
* *
@ -87,7 +83,7 @@ class Memory extends CacheBase implements ICache
{ {
parent::copyCellCollection($parent); parent::copyCellCollection($parent);
$newCollection = array(); $newCollection = [];
foreach ($this->cellCache as $k => &$cell) { foreach ($this->cellCache as $k => &$cell) {
$newCollection[$k] = clone $cell; $newCollection[$k] = clone $cell;
$newCollection[$k]->attach($this); $newCollection[$k]->attach($this);
@ -98,7 +94,6 @@ class Memory extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -109,7 +104,7 @@ class Memory extends CacheBase implements ICache
} }
unset($cell); unset($cell);
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;

View File

@ -30,7 +30,6 @@ class MemoryGZip extends CacheBase implements ICache
* Store cell data in cache for the current cell object if it's "dirty", * Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object * and the 'nullify' the current cell object
* *
* @return void
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
protected function storeData() protected function storeData()
@ -44,14 +43,13 @@ class MemoryGZip extends CacheBase implements ICache
$this->currentObjectID = $this->currentObject = null; $this->currentObjectID = $this->currentObject = null;
} }
/** /**
* Add or Update a cell in cache identified by coordinate address * Add or Update a cell in cache identified by coordinate address
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -66,7 +64,6 @@ class MemoryGZip extends CacheBase implements ICache
return $cell; return $cell;
} }
/** /**
* Get cell at a specific coordinate * Get cell at a specific coordinate
* *
@ -97,7 +94,6 @@ class MemoryGZip extends CacheBase implements ICache
return $this->currentObject; return $this->currentObject;
} }
/** /**
* Get a list of all cell addresses currently held in cache * Get a list of all cell addresses currently held in cache
* *
@ -112,11 +108,8 @@ class MemoryGZip extends CacheBase implements ICache
return parent::getCellList(); return parent::getCellList();
} }
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -124,7 +117,7 @@ class MemoryGZip extends CacheBase implements ICache
$this->currentObject->detach(); $this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null; $this->currentObject = $this->currentObjectID = null;
} }
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;

View File

@ -30,7 +30,6 @@ class MemorySerialized extends CacheBase implements ICache
* Store cell data in cache for the current cell object if it's "dirty", * Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object * and the 'nullify' the current cell object
* *
* @return void
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
protected function storeData() protected function storeData()
@ -49,8 +48,8 @@ class MemorySerialized extends CacheBase implements ICache
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -111,8 +110,6 @@ class MemorySerialized extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -120,7 +117,7 @@ class MemorySerialized extends CacheBase implements ICache
$this->currentObject->detach(); $this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null; $this->currentObject = $this->currentObjectID = null;
} }
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;

View File

@ -36,7 +36,7 @@ class PHPTemp extends CacheBase implements ICache
/** /**
* Memory limit to use before reverting to file cache * Memory limit to use before reverting to file cache
* *
* @var integer * @var int
*/ */
private $memoryCacheSize = null; private $memoryCacheSize = null;
@ -53,23 +53,22 @@ class PHPTemp extends CacheBase implements ICache
fseek($this->fileHandle, 0, SEEK_END); fseek($this->fileHandle, 0, SEEK_END);
$this->cellCache[$this->currentObjectID] = array( $this->cellCache[$this->currentObjectID] = [
'ptr' => ftell($this->fileHandle), 'ptr' => ftell($this->fileHandle),
'sz' => fwrite($this->fileHandle, serialize($this->currentObject)) 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)),
); ];
$this->currentCellIsDirty = false; $this->currentCellIsDirty = false;
} }
$this->currentObjectID = $this->currentObject = null; $this->currentObjectID = $this->currentObject = null;
} }
/** /**
* Add or Update a cell in cache identified by coordinate address * Add or Update a cell in cache identified by coordinate address
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -84,7 +83,6 @@ class PHPTemp extends CacheBase implements ICache
return $cell; return $cell;
} }
/** /**
* Get cell at a specific coordinate * Get cell at a specific coordinate
* *
@ -150,8 +148,6 @@ class PHPTemp extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -159,7 +155,7 @@ class PHPTemp extends CacheBase implements ICache
$this->currentObject->detach(); $this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null; $this->currentObject = $this->currentObjectID = null;
} }
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;

View File

@ -51,7 +51,7 @@ class SQLite extends CacheBase implements ICache
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach(); $this->currentObject->detach();
if (!$this->DBHandle->queryExec("INSERT OR REPLACE INTO kvp_".$this->TableName." VALUES('".$this->currentObjectID."','".sqlite_escape_string(serialize($this->currentObject))."')")) { if (!$this->DBHandle->queryExec('INSERT OR REPLACE INTO kvp_' . $this->TableName . " VALUES('" . $this->currentObjectID . "','" . sqlite_escape_string(serialize($this->currentObject)) . "')")) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
} }
$this->currentCellIsDirty = false; $this->currentCellIsDirty = false;
@ -64,8 +64,8 @@ class SQLite extends CacheBase implements ICache
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -94,7 +94,7 @@ class SQLite extends CacheBase implements ICache
} }
$this->storeData(); $this->storeData();
$query = "SELECT value FROM kvp_".$this->TableName." WHERE id='".$pCoord."'"; $query = 'SELECT value FROM kvp_' . $this->TableName . " WHERE id='" . $pCoord . "'";
$cellResultSet = $this->DBHandle->query($query, SQLITE_ASSOC); $cellResultSet = $this->DBHandle->query($query, SQLITE_ASSOC);
if ($cellResultSet === false) { if ($cellResultSet === false) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
@ -119,8 +119,8 @@ class SQLite extends CacheBase implements ICache
* Is a value set for an indexed cell? * Is a value set for an indexed cell?
* *
* @param string $pCoord Coordinate address of the cell to check * @param string $pCoord Coordinate address of the cell to check
* @return boolean
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return bool
*/ */
public function isDataSet($pCoord) public function isDataSet($pCoord)
{ {
@ -129,7 +129,7 @@ class SQLite extends CacheBase implements ICache
} }
// Check if the requested entry exists in the cache // Check if the requested entry exists in the cache
$query = "SELECT id FROM kvp_".$this->TableName." WHERE id='".$pCoord."'"; $query = 'SELECT id FROM kvp_' . $this->TableName . " WHERE id='" . $pCoord . "'";
$cellResultSet = $this->DBHandle->query($query, SQLITE_ASSOC); $cellResultSet = $this->DBHandle->query($query, SQLITE_ASSOC);
if ($cellResultSet === false) { if ($cellResultSet === false) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
@ -137,6 +137,7 @@ class SQLite extends CacheBase implements ICache
// Return null if requested entry doesn't exist in cache // Return null if requested entry doesn't exist in cache
return false; return false;
} }
return true; return true;
} }
@ -154,7 +155,7 @@ class SQLite extends CacheBase implements ICache
} }
// Check if the requested entry exists in the cache // Check if the requested entry exists in the cache
$query = "DELETE FROM kvp_".$this->TableName." WHERE id='".$pCoord."'"; $query = 'DELETE FROM kvp_' . $this->TableName . " WHERE id='" . $pCoord . "'";
if (!$this->DBHandle->queryExec($query)) { if (!$this->DBHandle->queryExec($query)) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
} }
@ -168,7 +169,7 @@ class SQLite extends CacheBase implements ICache
* @param string $fromAddress Current address of the cell to move * @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move * @param string $toAddress Destination address of the cell to move
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return boolean * @return bool
*/ */
public function moveCell($fromAddress, $toAddress) public function moveCell($fromAddress, $toAddress)
{ {
@ -176,13 +177,13 @@ class SQLite extends CacheBase implements ICache
$this->currentObjectID = $toAddress; $this->currentObjectID = $toAddress;
} }
$query = "DELETE FROM kvp_".$this->TableName." WHERE id='".$toAddress."'"; $query = 'DELETE FROM kvp_' . $this->TableName . " WHERE id='" . $toAddress . "'";
$result = $this->DBHandle->exec($query); $result = $this->DBHandle->exec($query);
if ($result === false) { if ($result === false) {
throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg()); throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg());
} }
$query = "UPDATE kvp_".$this->TableName." SET id='".$toAddress."' WHERE id='".$fromAddress."'"; $query = 'UPDATE kvp_' . $this->TableName . " SET id='" . $toAddress . "' WHERE id='" . $fromAddress . "'";
$result = $this->DBHandle->exec($query); $result = $this->DBHandle->exec($query);
if ($result === false) { if ($result === false) {
throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg()); throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg());
@ -194,8 +195,8 @@ class SQLite extends CacheBase implements ICache
/** /**
* Get a list of all cell addresses currently held in cache * Get a list of all cell addresses currently held in cache
* *
* @return string[]
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return string[]
*/ */
public function getCellList() public function getCellList()
{ {
@ -203,13 +204,13 @@ class SQLite extends CacheBase implements ICache
$this->storeData(); $this->storeData();
} }
$query = "SELECT id FROM kvp_".$this->TableName; $query = 'SELECT id FROM kvp_' . $this->TableName;
$cellIdsResult = $this->DBHandle->unbufferedQuery($query, SQLITE_ASSOC); $cellIdsResult = $this->DBHandle->unbufferedQuery($query, SQLITE_ASSOC);
if ($cellIdsResult === false) { if ($cellIdsResult === false) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
} }
$cellKeys = array(); $cellKeys = [];
foreach ($cellIdsResult as $row) { foreach ($cellIdsResult as $row) {
$cellKeys[] = $row['id']; $cellKeys[] = $row['id'];
} }
@ -230,8 +231,8 @@ class SQLite extends CacheBase implements ICache
// Get a new id for the new table name // Get a new id for the new table name
$tableName = str_replace('.', '_', $this->getUniqueID()); $tableName = str_replace('.', '_', $this->getUniqueID());
if (!$this->DBHandle->queryExec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) if (!$this->DBHandle->queryExec('CREATE TABLE kvp_' . $tableName . ' (id VARCHAR(12) PRIMARY KEY, value BLOB)
AS SELECT * FROM kvp_'.$this->TableName) AS SELECT * FROM kvp_' . $this->TableName)
) { ) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
} }
@ -242,8 +243,6 @@ class SQLite extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -275,7 +274,7 @@ class SQLite extends CacheBase implements ICache
if ($this->DBHandle === false) { if ($this->DBHandle === false) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
} }
if (!$this->DBHandle->queryExec('CREATE TABLE kvp_'.$this->TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) { if (!$this->DBHandle->queryExec('CREATE TABLE kvp_' . $this->TableName . ' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) {
throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError()));
} }
} }
@ -287,7 +286,7 @@ class SQLite extends CacheBase implements ICache
public function __destruct() public function __destruct()
{ {
if (!is_null($this->DBHandle)) { if (!is_null($this->DBHandle)) {
$this->DBHandle->queryExec('DROP TABLE kvp_'.$this->TableName); $this->DBHandle->queryExec('DROP TABLE kvp_' . $this->TableName);
} }
$this->DBHandle = null; $this->DBHandle = null;
} }
@ -296,7 +295,7 @@ class SQLite extends CacheBase implements ICache
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable() public static function cacheMethodIsAvailable()
{ {

View File

@ -95,8 +95,8 @@ class SQLite3 extends CacheBase implements ICache
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -116,8 +116,8 @@ class SQLite3 extends CacheBase implements ICache
* *
* @param string $pCoord Coordinate of the cell * @param string $pCoord Coordinate of the cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell Cell that was found, or null if not found
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell Cell that was found, or null if not found
*/ */
public function getCacheData($pCoord) public function getCacheData($pCoord)
{ {
@ -152,8 +152,8 @@ class SQLite3 extends CacheBase implements ICache
* Is a value set for an indexed cell? * Is a value set for an indexed cell?
* *
* @param string $pCoord Coordinate address of the cell to check * @param string $pCoord Coordinate address of the cell to check
* @return boolean
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return bool
*/ */
public function isDataSet($pCoord) public function isDataSet($pCoord)
{ {
@ -200,8 +200,8 @@ class SQLite3 extends CacheBase implements ICache
* *
* @param string $fromAddress Current address of the cell to move * @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move * @param string $toAddress Destination address of the cell to move
* @return boolean
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return bool
*/ */
public function moveCell($fromAddress, $toAddress) public function moveCell($fromAddress, $toAddress)
{ {
@ -228,8 +228,8 @@ class SQLite3 extends CacheBase implements ICache
/** /**
* Get a list of all cell addresses currently held in cache * Get a list of all cell addresses currently held in cache
* *
* @return string[]
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return string[]
*/ */
public function getCellList() public function getCellList()
{ {
@ -237,13 +237,13 @@ class SQLite3 extends CacheBase implements ICache
$this->storeData(); $this->storeData();
} }
$query = "SELECT id FROM kvp_".$this->TableName; $query = 'SELECT id FROM kvp_' . $this->TableName;
$cellIdsResult = $this->DBHandle->query($query); $cellIdsResult = $this->DBHandle->query($query);
if ($cellIdsResult === false) { if ($cellIdsResult === false) {
throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg()); throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg());
} }
$cellKeys = array(); $cellKeys = [];
while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) { while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) {
$cellKeys[] = $row['id']; $cellKeys[] = $row['id'];
} }
@ -264,8 +264,8 @@ class SQLite3 extends CacheBase implements ICache
// Get a new id for the new table name // Get a new id for the new table name
$tableName = str_replace('.', '_', $this->getUniqueID()); $tableName = str_replace('.', '_', $this->getUniqueID());
if (!$this->DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) if (!$this->DBHandle->exec('CREATE TABLE kvp_' . $tableName . ' (id VARCHAR(12) PRIMARY KEY, value BLOB)
AS SELECT * FROM kvp_'.$this->TableName) AS SELECT * FROM kvp_' . $this->TableName)
) { ) {
throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg()); throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg());
} }
@ -276,8 +276,6 @@ class SQLite3 extends CacheBase implements ICache
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -309,15 +307,15 @@ class SQLite3 extends CacheBase implements ICache
if ($this->DBHandle === false) { if ($this->DBHandle === false) {
throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg()); throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg());
} }
if (!$this->DBHandle->exec('CREATE TABLE kvp_'.$this->TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) { if (!$this->DBHandle->exec('CREATE TABLE kvp_' . $this->TableName . ' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) {
throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg()); throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg());
} }
} }
$this->selectQuery = $this->DBHandle->prepare("SELECT value FROM kvp_".$this->TableName." WHERE id = :id"); $this->selectQuery = $this->DBHandle->prepare('SELECT value FROM kvp_' . $this->TableName . ' WHERE id = :id');
$this->insertQuery = $this->DBHandle->prepare("INSERT OR REPLACE INTO kvp_".$this->TableName." VALUES(:id,:data)"); $this->insertQuery = $this->DBHandle->prepare('INSERT OR REPLACE INTO kvp_' . $this->TableName . ' VALUES(:id,:data)');
$this->updateQuery = $this->DBHandle->prepare("UPDATE kvp_".$this->TableName." SET id=:toId WHERE id=:fromId"); $this->updateQuery = $this->DBHandle->prepare('UPDATE kvp_' . $this->TableName . ' SET id=:toId WHERE id=:fromId');
$this->deleteQuery = $this->DBHandle->prepare("DELETE FROM kvp_".$this->TableName." WHERE id = :id"); $this->deleteQuery = $this->DBHandle->prepare('DELETE FROM kvp_' . $this->TableName . ' WHERE id = :id');
} }
/** /**
@ -326,7 +324,7 @@ class SQLite3 extends CacheBase implements ICache
public function __destruct() public function __destruct()
{ {
if (!is_null($this->DBHandle)) { if (!is_null($this->DBHandle)) {
$this->DBHandle->exec('DROP TABLE kvp_'.$this->TableName); $this->DBHandle->exec('DROP TABLE kvp_' . $this->TableName);
$this->DBHandle->close(); $this->DBHandle->close();
} }
$this->DBHandle = null; $this->DBHandle = null;
@ -336,7 +334,7 @@ class SQLite3 extends CacheBase implements ICache
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable() public static function cacheMethodIsAvailable()
{ {

View File

@ -36,16 +36,14 @@ class Wincache extends CacheBase implements ICache
/** /**
* Cache timeout * Cache timeout
* *
* @var integer * @var int
*/ */
private $cacheTime = 600; private $cacheTime = 600;
/** /**
* Store cell data in cache for the current cell object if it's "dirty", * Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object * and the 'nullify' the current cell object
* *
* @return void
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
*/ */
protected function storeData() protected function storeData()
@ -54,15 +52,15 @@ class Wincache extends CacheBase implements ICache
$this->currentObject->detach(); $this->currentObject->detach();
$obj = serialize($this->currentObject); $obj = serialize($this->currentObject);
if (wincache_ucache_exists($this->cachePrefix.$this->currentObjectID.'.cache')) { if (wincache_ucache_exists($this->cachePrefix . $this->currentObjectID . '.cache')) {
if (!wincache_ucache_set($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) { if (!wincache_ucache_set($this->cachePrefix . $this->currentObjectID . '.cache', $obj, $this->cacheTime)) {
$this->__destruct(); $this->__destruct();
throw new \PhpSpreadsheet\Exception('Failed to store cell '.$this->currentObjectID.' in WinCache'); throw new \PhpSpreadsheet\Exception('Failed to store cell ' . $this->currentObjectID . ' in WinCache');
} }
} else { } else {
if (!wincache_ucache_add($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) { if (!wincache_ucache_add($this->cachePrefix . $this->currentObjectID . '.cache', $obj, $this->cacheTime)) {
$this->__destruct(); $this->__destruct();
throw new \PhpSpreadsheet\Exception('Failed to store cell '.$this->currentObjectID.' in WinCache'); throw new \PhpSpreadsheet\Exception('Failed to store cell ' . $this->currentObjectID . ' in WinCache');
} }
} }
$this->currentCellIsDirty = false; $this->currentCellIsDirty = false;
@ -76,8 +74,8 @@ class Wincache extends CacheBase implements ICache
* *
* @param string $pCoord Coordinate address of the cell to update * @param string $pCoord Coordinate address of the cell to update
* @param \PhpSpreadsheet\Cell $cell Cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update
* @return \PhpSpreadsheet\Cell
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return \PhpSpreadsheet\Cell
*/ */
public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell)
{ {
@ -97,8 +95,8 @@ class Wincache extends CacheBase implements ICache
* Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell? * Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell?
* *
* @param string $pCoord Coordinate address of the cell to check * @param string $pCoord Coordinate address of the cell to check
* @return boolean
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return bool
*/ */
public function isDataSet($pCoord) public function isDataSet($pCoord)
{ {
@ -108,18 +106,19 @@ class Wincache extends CacheBase implements ICache
return true; return true;
} }
// Check if the requested entry still exists in cache // Check if the requested entry still exists in cache
$success = wincache_ucache_exists($this->cachePrefix.$pCoord.'.cache'); $success = wincache_ucache_exists($this->cachePrefix . $pCoord . '.cache');
if ($success === false) { if ($success === false) {
// Entry no longer exists in Wincache, so clear it from the cache array // Entry no longer exists in Wincache, so clear it from the cache array
parent::deleteCacheData($pCoord); parent::deleteCacheData($pCoord);
throw new \PhpSpreadsheet\Exception('Cell entry '.$pCoord.' no longer exists in WinCache'); throw new \PhpSpreadsheet\Exception('Cell entry ' . $pCoord . ' no longer exists in WinCache');
} }
return true; return true;
} }
return false; return false;
} }
/** /**
* Get cell at a specific coordinate * Get cell at a specific coordinate
* *
@ -138,11 +137,11 @@ class Wincache extends CacheBase implements ICache
$obj = null; $obj = null;
if (parent::isDataSet($pCoord)) { if (parent::isDataSet($pCoord)) {
$success = false; $success = false;
$obj = wincache_ucache_get($this->cachePrefix.$pCoord.'.cache', $success); $obj = wincache_ucache_get($this->cachePrefix . $pCoord . '.cache', $success);
if ($success === false) { if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array // Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($pCoord); parent::deleteCacheData($pCoord);
throw new \PhpSpreadsheet\Exception('Cell entry '.$pCoord.' no longer exists in WinCache'); throw new \PhpSpreadsheet\Exception('Cell entry ' . $pCoord . ' no longer exists in WinCache');
} }
} else { } else {
// Return null if requested entry doesn't exist in cache // Return null if requested entry doesn't exist in cache
@ -159,7 +158,6 @@ class Wincache extends CacheBase implements ICache
return $this->currentObject; return $this->currentObject;
} }
/** /**
* Get a list of all cell addresses currently held in cache * Get a list of all cell addresses currently held in cache
* *
@ -183,7 +181,7 @@ class Wincache extends CacheBase implements ICache
public function deleteCacheData($pCoord) public function deleteCacheData($pCoord)
{ {
// Delete the entry from Wincache // Delete the entry from Wincache
wincache_ucache_delete($this->cachePrefix.$pCoord.'.cache'); wincache_ucache_delete($this->cachePrefix . $pCoord . '.cache');
// Delete the entry from our cell address array // Delete the entry from our cell address array
parent::deleteCacheData($pCoord); parent::deleteCacheData($pCoord);
@ -205,26 +203,23 @@ class Wincache extends CacheBase implements ICache
foreach ($cacheList as $cellID) { foreach ($cacheList as $cellID) {
if ($cellID != $this->currentObjectID) { if ($cellID != $this->currentObjectID) {
$success = false; $success = false;
$obj = wincache_ucache_get($this->cachePrefix.$cellID.'.cache', $success); $obj = wincache_ucache_get($this->cachePrefix . $cellID . '.cache', $success);
if ($success === false) { if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array // Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($cellID); parent::deleteCacheData($cellID);
throw new \PhpSpreadsheet\Exception('Cell entry '.$cellID.' no longer exists in Wincache'); throw new \PhpSpreadsheet\Exception('Cell entry ' . $cellID . ' no longer exists in Wincache');
} }
if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->cacheTime)) { if (!wincache_ucache_add($newCachePrefix . $cellID . '.cache', $obj, $this->cacheTime)) {
$this->__destruct(); $this->__destruct();
throw new \PhpSpreadsheet\Exception('Failed to store cell '.$cellID.' in Wincache'); throw new \PhpSpreadsheet\Exception('Failed to store cell ' . $cellID . ' in Wincache');
} }
} }
} }
$this->cachePrefix = $newCachePrefix; $this->cachePrefix = $newCachePrefix;
} }
/** /**
* Clear the cell collection and disconnect from our parent * Clear the cell collection and disconnect from our parent
*
* @return void
*/ */
public function unsetWorksheetCells() public function unsetWorksheetCells()
{ {
@ -236,7 +231,7 @@ class Wincache extends CacheBase implements ICache
// Flush the WinCache cache // Flush the WinCache cache
$this->__destruct(); $this->__destruct();
$this->cellCache = array(); $this->cellCache = [];
// detach ourself from the worksheet, so that it can then delete this object successfully // detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null; $this->parent = null;
@ -250,11 +245,11 @@ class Wincache extends CacheBase implements ICache
*/ */
public function __construct(\PhpSpreadsheet\Worksheet $parent, $arguments) public function __construct(\PhpSpreadsheet\Worksheet $parent, $arguments)
{ {
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600; $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
if (is_null($this->cachePrefix)) { if (is_null($this->cachePrefix)) {
$baseUnique = $this->getUniqueID(); $baseUnique = $this->getUniqueID();
$this->cachePrefix = substr(md5($baseUnique), 0, 8).'.'; $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.';
$this->cacheTime = $cacheTime; $this->cacheTime = $cacheTime;
parent::__construct($parent); parent::__construct($parent);
@ -268,7 +263,7 @@ class Wincache extends CacheBase implements ICache
{ {
$cacheList = $this->getCellList(); $cacheList = $this->getCellList();
foreach ($cacheList as $cellID) { foreach ($cacheList as $cellID) {
wincache_ucache_delete($this->cachePrefix.$cellID.'.cache'); wincache_ucache_delete($this->cachePrefix . $cellID . '.cache');
} }
} }
@ -276,7 +271,7 @@ class Wincache extends CacheBase implements ICache
* Identify whether the caching method is currently available * Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
* *
* @return boolean * @return bool
*/ */
public static function cacheMethodIsAvailable() public static function cacheMethodIsAvailable()
{ {

View File

@ -26,17 +26,17 @@ namespace PhpSpreadsheet;
*/ */
class CachedObjectStorageFactory class CachedObjectStorageFactory
{ {
const CACHE_IN_MEMORY = 'Memory'; const CACHE_IN_MEMORY = 'Memory';
const CACHE_IN_MEMORY_GZIP = 'MemoryGZip'; const CACHE_IN_MEMORY_GZIP = 'MemoryGZip';
const CACHE_IN_MEMORY_SERIALIZED = 'MemorySerialized'; const CACHE_IN_MEMORY_SERIALIZED = 'MemorySerialized';
const CACHE_IGBINARY = 'Igbinary'; const CACHE_IGBINARY = 'Igbinary';
const CACHE_TO_DISCISAM = 'DiscISAM'; const CACHE_TO_DISCISAM = 'DiscISAM';
const CACHE_TO_APC = 'APC'; const CACHE_TO_APC = 'APC';
const CACHE_TO_MEMCACHE = 'Memcache'; const CACHE_TO_MEMCACHE = 'Memcache';
const CACHE_TO_PHPTEMP = 'PHPTemp'; const CACHE_TO_PHPTEMP = 'PHPTemp';
const CACHE_TO_WINCACHE = 'Wincache'; const CACHE_TO_WINCACHE = 'Wincache';
const CACHE_TO_SQLITE = 'SQLite'; const CACHE_TO_SQLITE = 'SQLite';
const CACHE_TO_SQLITE3 = 'SQLite3'; const CACHE_TO_SQLITE3 = 'SQLite3';
/** /**
* Name of the method used for cell cacheing * Name of the method used for cell cacheing
@ -109,7 +109,6 @@ class CachedObjectStorageFactory
*/ */
private static $storageMethodParameters = []; private static $storageMethodParameters = [];
/** /**
* Return the current cache storage method * Return the current cache storage method
* *
@ -147,13 +146,14 @@ class CachedObjectStorageFactory
**/ **/
public static function getCacheStorageMethods() public static function getCacheStorageMethods()
{ {
$activeMethods = array(); $activeMethods = [];
foreach (self::$storageMethods as $storageMethod) { foreach (self::$storageMethods as $storageMethod) {
$cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $storageMethod; $cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $storageMethod;
if (call_user_func(array($cacheStorageClass, 'cacheMethodIsAvailable'))) { if (call_user_func([$cacheStorageClass, 'cacheMethodIsAvailable'])) {
$activeMethods[] = $storageMethod; $activeMethods[] = $storageMethod;
} }
} }
return $activeMethods; return $activeMethods;
} }
@ -163,7 +163,7 @@ class CachedObjectStorageFactory
* @param string $method Name of the method to use for cell cacheing * @param string $method Name of the method to use for cell cacheing
* @param mixed[] $arguments Additional arguments to pass to the cell caching class * @param mixed[] $arguments Additional arguments to pass to the cell caching class
* when instantiating * when instantiating
* @return boolean * @return bool
**/ **/
public static function initialize($method = self::CACHE_IN_MEMORY, $arguments = []) public static function initialize($method = self::CACHE_IN_MEMORY, $arguments = [])
{ {
@ -171,7 +171,7 @@ class CachedObjectStorageFactory
return false; return false;
} }
$cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\'.$method; $cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $method;
if (!call_user_func([$cacheStorageClass, 'cacheMethodIsAvailable'])) { if (!call_user_func([$cacheStorageClass, 'cacheMethodIsAvailable'])) {
return false; return false;
} }
@ -187,6 +187,7 @@ class CachedObjectStorageFactory
self::$cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $method; self::$cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $method;
self::$cacheStorageMethod = $method; self::$cacheStorageMethod = $method;
} }
return true; return true;
} }
@ -218,12 +219,11 @@ class CachedObjectStorageFactory
/** /**
* Clear the cache storage * Clear the cache storage
*
**/ **/
public static function finalize() public static function finalize()
{ {
self::$cacheStorageMethod = null; self::$cacheStorageMethod = null;
self::$cacheStorageClass = null; self::$cacheStorageClass = null;
self::$storageMethodParameters = array(); self::$storageMethodParameters = [];
} }
} }

View File

@ -31,12 +31,12 @@ class CyclicReferenceStack
* *
* @var mixed[] * @var mixed[]
*/ */
private $stack = array(); private $stack = [];
/** /**
* Return the number of entries on the stack * Return the number of entries on the stack
* *
* @return integer * @return int
*/ */
public function count() public function count()
{ {
@ -78,7 +78,7 @@ class CyclicReferenceStack
*/ */
public function clear() public function clear()
{ {
$this->stack = array(); $this->stack = [];
} }
/** /**

View File

@ -31,7 +31,7 @@ class Logger
* If true, then a debug log will be generated * If true, then a debug log will be generated
* If false, then a debug log will not be generated * If false, then a debug log will not be generated
* *
* @var boolean * @var bool
*/ */
private $writeDebugLog = false; private $writeDebugLog = false;
@ -41,7 +41,7 @@ class Logger
* If false, then a debug log will not be echoed * If false, then a debug log will not be echoed
* A debug log can only be echoed if it is generated * A debug log can only be echoed if it is generated
* *
* @var boolean * @var bool
*/ */
private $echoDebugLog = false; private $echoDebugLog = false;
@ -50,7 +50,7 @@ class Logger
* *
* @var string[] * @var string[]
*/ */
private $debugLog = array(); private $debugLog = [];
/** /**
* The calculation engine cell reference stack * The calculation engine cell reference stack
@ -72,7 +72,7 @@ class Logger
/** /**
* Enable/Disable Calculation engine logging * Enable/Disable Calculation engine logging
* *
* @param boolean $pValue * @param bool $pValue
*/ */
public function setWriteDebugLog($pValue = false) public function setWriteDebugLog($pValue = false)
{ {
@ -82,7 +82,7 @@ class Logger
/** /**
* Return whether calculation engine logging is enabled or disabled * Return whether calculation engine logging is enabled or disabled
* *
* @return boolean * @return bool
*/ */
public function getWriteDebugLog() public function getWriteDebugLog()
{ {
@ -92,7 +92,7 @@ class Logger
/** /**
* Enable/Disable echoing of debug log information * Enable/Disable echoing of debug log information
* *
* @param boolean $pValue * @param bool $pValue
*/ */
public function setEchoDebugLog($pValue = false) public function setEchoDebugLog($pValue = false)
{ {
@ -102,7 +102,7 @@ class Logger
/** /**
* Return whether echoing of debug log information is enabled or disabled * Return whether echoing of debug log information is enabled or disabled
* *
* @return boolean * @return bool
*/ */
public function getEchoDebugLog() public function getEchoDebugLog()
{ {
@ -135,7 +135,7 @@ class Logger
*/ */
public function clearLog() public function clearLog()
{ {
$this->debugLog = array(); $this->debugLog = [];
} }
/** /**

File diff suppressed because it is too large Load Diff

View File

@ -27,17 +27,17 @@ namespace PhpSpreadsheet\Calculation;
class Categories class Categories
{ {
/* Function categories */ /* Function categories */
const CATEGORY_CUBE = 'Cube'; const CATEGORY_CUBE = 'Cube';
const CATEGORY_DATABASE = 'Database'; const CATEGORY_DATABASE = 'Database';
const CATEGORY_DATE_AND_TIME = 'Date and Time'; const CATEGORY_DATE_AND_TIME = 'Date and Time';
const CATEGORY_ENGINEERING = 'Engineering'; const CATEGORY_ENGINEERING = 'Engineering';
const CATEGORY_FINANCIAL = 'Financial'; const CATEGORY_FINANCIAL = 'Financial';
const CATEGORY_INFORMATION = 'Information'; const CATEGORY_INFORMATION = 'Information';
const CATEGORY_LOGICAL = 'Logical'; const CATEGORY_LOGICAL = 'Logical';
const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference'; const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference';
const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; const CATEGORY_MATH_AND_TRIG = 'Math and Trig';
const CATEGORY_STATISTICAL = 'Statistical'; const CATEGORY_STATISTICAL = 'Statistical';
const CATEGORY_TEXT_AND_DATA = 'Text and Data'; const CATEGORY_TEXT_AND_DATA = 'Text and Data';
/** /**
* Category (represented by CATEGORY_*) * Category (represented by CATEGORY_*)
@ -71,11 +71,11 @@ class Categories
{ {
if (($pCategory !== null) && ($pExcelName !== null) && ($spreadsheetName !== null)) { if (($pCategory !== null) && ($pExcelName !== null) && ($spreadsheetName !== null)) {
// Initialise values // Initialise values
$this->category = $pCategory; $this->category = $pCategory;
$this->excelName = $pExcelName; $this->excelName = $pExcelName;
$this->spreadsheetName = $spreadsheetName; $this->spreadsheetName = $spreadsheetName;
} else { } else {
throw new Exception("Invalid parameters passed."); throw new Exception('Invalid parameters passed.');
} }
} }
@ -100,7 +100,7 @@ class Categories
if (!is_null($value)) { if (!is_null($value)) {
$this->category = $value; $this->category = $value;
} else { } else {
throw new Exception("Invalid parameter passed."); throw new Exception('Invalid parameter passed.');
} }
} }

View File

@ -31,7 +31,6 @@ class Database
* *
* Extracts the column ID to use for the data field. * Extracts the column ID to use for the data field.
* *
* @access private
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
@ -41,8 +40,7 @@ class Database
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
* the first column, 2 for the second column, and so on. * the first column, 2 for the second column, and so on.
* @return string|NULL * @return string|null
*
*/ */
private static function fieldExtract($database, $field) private static function fieldExtract($database, $field)
{ {
@ -51,9 +49,11 @@ class Database
if (is_numeric($field)) { if (is_numeric($field)) {
$keys = array_keys($fieldNames); $keys = array_keys($fieldNames);
return $keys[$field-1];
return $keys[$field - 1];
} }
$key = array_search($field, $fieldNames); $key = array_search($field, $fieldNames);
return ($key) ? $key : null; return ($key) ? $key : null;
} }
@ -63,7 +63,6 @@ class Database
* Parses the selection criteria, extracts the database rows that match those criteria, and * Parses the selection criteria, extracts the database rows that match those criteria, and
* returns that subset of rows. * returns that subset of rows.
* *
* @access private
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
@ -74,7 +73,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return array of mixed * @return array of mixed
*
*/ */
private static function filter($database, $criteria) private static function filter($database, $criteria)
{ {
@ -82,23 +80,23 @@ class Database
$criteriaNames = array_shift($criteria); $criteriaNames = array_shift($criteria);
// Convert the criteria into a set of AND/OR conditions with [:placeholders] // Convert the criteria into a set of AND/OR conditions with [:placeholders]
$testConditions = $testValues = array(); $testConditions = $testValues = [];
$testConditionsCount = 0; $testConditionsCount = 0;
foreach ($criteriaNames as $key => $criteriaName) { foreach ($criteriaNames as $key => $criteriaName) {
$testCondition = array(); $testCondition = [];
$testConditionCount = 0; $testConditionCount = 0;
foreach ($criteria as $row => $criterion) { foreach ($criteria as $row => $criterion) {
if ($criterion[$key] > '') { if ($criterion[$key] > '') {
$testCondition[] = '[:'.$criteriaName.']'.Functions::ifCondition($criterion[$key]); $testCondition[] = '[:' . $criteriaName . ']' . Functions::ifCondition($criterion[$key]);
$testConditionCount++; ++$testConditionCount;
} }
} }
if ($testConditionCount > 1) { if ($testConditionCount > 1) {
$testConditions[] = 'OR(' . implode(',', $testCondition) . ')'; $testConditions[] = 'OR(' . implode(',', $testCondition) . ')';
$testConditionsCount++; ++$testConditionsCount;
} elseif ($testConditionCount == 1) { } elseif ($testConditionCount == 1) {
$testConditions[] = $testCondition[0]; $testConditions[] = $testCondition[0];
$testConditionsCount++; ++$testConditionsCount;
} }
} }
@ -121,7 +119,7 @@ class Database
} }
} }
// evaluate the criteria against the row data // evaluate the criteria against the row data
$result = \PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList); $result = \PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue('=' . $testConditionList);
// If the row failed to meet the criteria, remove it from the database // If the row failed to meet the criteria, remove it from the database
if (!$result) { if (!$result) {
unset($database[$dataRow]); unset($database[$dataRow]);
@ -131,13 +129,12 @@ class Database
return $database; return $database;
} }
private static function getFilteredColumn($database, $field, $criteria) private static function getFilteredColumn($database, $field, $criteria)
{ {
// reduce the database to a set of rows that match all the criteria // reduce the database to a set of rows that match all the criteria
$database = self::filter($database, $criteria); $database = self::filter($database, $criteria);
// extract an array of values for the requested column // extract an array of values for the requested column
$colData = array(); $colData = [];
foreach ($database as $row) { foreach ($database as $row) {
$colData[] = $row[$field]; $colData[] = $row[$field];
} }
@ -153,13 +150,12 @@ class Database
* Excel Function: * Excel Function:
* DAVERAGE(database,field,criteria) * DAVERAGE(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -170,7 +166,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DAVERAGE($database, $field, $criteria) public static function DAVERAGE($database, $field, $criteria)
{ {
@ -185,7 +180,6 @@ class Database
); );
} }
/** /**
* DCOUNT * DCOUNT
* *
@ -198,13 +192,12 @@ class Database
* Excel Function: * Excel Function:
* DAVERAGE(database,field,criteria) * DAVERAGE(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -214,11 +207,10 @@ class Database
* includes at least one column label and at least one cell below * includes at least one column label and at least one cell below
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return integer * @return int
* *
* @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the
* database that match the criteria. * database that match the criteria.
*
*/ */
public static function DCOUNT($database, $field, $criteria) public static function DCOUNT($database, $field, $criteria)
{ {
@ -233,7 +225,6 @@ class Database
); );
} }
/** /**
* DCOUNTA * DCOUNTA
* *
@ -242,13 +233,12 @@ class Database
* Excel Function: * Excel Function:
* DCOUNTA(database,[field],criteria) * DCOUNTA(database,[field],criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -258,11 +248,10 @@ class Database
* includes at least one column label and at least one cell below * includes at least one column label and at least one cell below
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return integer * @return int
* *
* @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
* database that match the criteria. * database that match the criteria.
*
*/ */
public static function DCOUNTA($database, $field, $criteria) public static function DCOUNTA($database, $field, $criteria)
{ {
@ -274,7 +263,7 @@ class Database
// reduce the database to a set of rows that match all the criteria // reduce the database to a set of rows that match all the criteria
$database = self::filter($database, $criteria); $database = self::filter($database, $criteria);
// extract an array of values for the requested column // extract an array of values for the requested column
$colData = array(); $colData = [];
foreach ($database as $row) { foreach ($database as $row) {
$colData[] = $row[$field]; $colData[] = $row[$field];
} }
@ -285,7 +274,6 @@ class Database
); );
} }
/** /**
* DGET * DGET
* *
@ -295,13 +283,12 @@ class Database
* Excel Function: * Excel Function:
* DGET(database,field,criteria) * DGET(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -312,7 +299,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return mixed * @return mixed
*
*/ */
public static function DGET($database, $field, $criteria) public static function DGET($database, $field, $criteria)
{ {
@ -330,7 +316,6 @@ class Database
return $colData[0]; return $colData[0];
} }
/** /**
* DMAX * DMAX
* *
@ -340,13 +325,12 @@ class Database
* Excel Function: * Excel Function:
* DMAX(database,field,criteria) * DMAX(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -357,7 +341,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DMAX($database, $field, $criteria) public static function DMAX($database, $field, $criteria)
{ {
@ -372,7 +355,6 @@ class Database
); );
} }
/** /**
* DMIN * DMIN
* *
@ -382,13 +364,12 @@ class Database
* Excel Function: * Excel Function:
* DMIN(database,field,criteria) * DMIN(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -399,7 +380,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DMIN($database, $field, $criteria) public static function DMIN($database, $field, $criteria)
{ {
@ -414,7 +394,6 @@ class Database
); );
} }
/** /**
* DPRODUCT * DPRODUCT
* *
@ -423,13 +402,12 @@ class Database
* Excel Function: * Excel Function:
* DPRODUCT(database,field,criteria) * DPRODUCT(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -440,7 +418,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DPRODUCT($database, $field, $criteria) public static function DPRODUCT($database, $field, $criteria)
{ {
@ -455,7 +432,6 @@ class Database
); );
} }
/** /**
* DSTDEV * DSTDEV
* *
@ -465,13 +441,12 @@ class Database
* Excel Function: * Excel Function:
* DSTDEV(database,field,criteria) * DSTDEV(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -482,7 +457,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DSTDEV($database, $field, $criteria) public static function DSTDEV($database, $field, $criteria)
{ {
@ -497,7 +471,6 @@ class Database
); );
} }
/** /**
* DSTDEVP * DSTDEVP
* *
@ -507,13 +480,12 @@ class Database
* Excel Function: * Excel Function:
* DSTDEVP(database,field,criteria) * DSTDEVP(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -524,7 +496,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DSTDEVP($database, $field, $criteria) public static function DSTDEVP($database, $field, $criteria)
{ {
@ -539,7 +510,6 @@ class Database
); );
} }
/** /**
* DSUM * DSUM
* *
@ -548,13 +518,12 @@ class Database
* Excel Function: * Excel Function:
* DSUM(database,field,criteria) * DSUM(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -565,7 +534,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DSUM($database, $field, $criteria) public static function DSUM($database, $field, $criteria)
{ {
@ -580,7 +548,6 @@ class Database
); );
} }
/** /**
* DVAR * DVAR
* *
@ -590,13 +557,12 @@ class Database
* Excel Function: * Excel Function:
* DVAR(database,field,criteria) * DVAR(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -607,7 +573,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DVAR($database, $field, $criteria) public static function DVAR($database, $field, $criteria)
{ {
@ -622,7 +587,6 @@ class Database
); );
} }
/** /**
* DVARP * DVARP
* *
@ -632,13 +596,12 @@ class Database
* Excel Function: * Excel Function:
* DVARP(database,field,criteria) * DVARP(database,field,criteria)
* *
* @access public
* @category Database Functions * @category Database Functions
* @param mixed[] $database The range of cells that makes up the list or database. * @param mixed[] $database The range of cells that makes up the list or database.
* A database is a list of related data in which rows of related * A database is a list of related data in which rows of related
* information are records, and columns of data are fields. The * information are records, and columns of data are fields. The
* first row of the list contains labels for each column. * first row of the list contains labels for each column.
* @param string|integer $field Indicates which column is used in the function. Enter the * @param string|int $field Indicates which column is used in the function. Enter the
* column label enclosed between double quotation marks, such as * column label enclosed between double quotation marks, such as
* "Age" or "Yield," or a number (without quotation marks) that * "Age" or "Yield," or a number (without quotation marks) that
* represents the position of the column within the list: 1 for * represents the position of the column within the list: 1 for
@ -649,7 +612,6 @@ class Database
* the column label in which you specify a condition for the * the column label in which you specify a condition for the
* column. * column.
* @return float * @return float
*
*/ */
public static function DVARP($database, $field, $criteria) public static function DVARP($database, $field, $criteria)
{ {

View File

@ -29,26 +29,25 @@ class DateTime
/** /**
* Identify if a year is a leap year or not * Identify if a year is a leap year or not
* *
* @param integer $year The year to test * @param int $year The year to test
* @return boolean TRUE if the year is a leap year, otherwise FALSE * @return bool TRUE if the year is a leap year, otherwise FALSE
*/ */
public static function isLeapYear($year) public static function isLeapYear($year)
{ {
return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0)); return (($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0);
} }
/** /**
* Return the number of days between two dates based on a 360 day calendar * Return the number of days between two dates based on a 360 day calendar
* *
* @param integer $startDay Day of month of the start date * @param int $startDay Day of month of the start date
* @param integer $startMonth Month of the start date * @param int $startMonth Month of the start date
* @param integer $startYear Year of the start date * @param int $startYear Year of the start date
* @param integer $endDay Day of month of the start date * @param int $endDay Day of month of the start date
* @param integer $endMonth Month of the start date * @param int $endMonth Month of the start date
* @param integer $endYear Year of the start date * @param int $endYear Year of the start date
* @param boolean $methodUS Whether to use the US method or the European method of calculation * @param bool $methodUS Whether to use the US method or the European method of calculation
* @return integer Number of days between the start date and the end date * @return int Number of days between the start date and the end date
*/ */
private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS)
{ {
@ -74,7 +73,6 @@ class DateTime
return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
} }
/** /**
* getDateValue * getDateValue
* *
@ -97,10 +95,10 @@ class DateTime
Functions::setReturnDateType($saveReturnDateType); Functions::setReturnDateType($saveReturnDateType);
} }
} }
return $dateValue; return $dateValue;
} }
/** /**
* getTimeValue * getTimeValue
* *
@ -113,10 +111,10 @@ class DateTime
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
$timeValue = self::TIMEVALUE($timeValue); $timeValue = self::TIMEVALUE($timeValue);
Functions::setReturnDateType($saveReturnDateType); Functions::setReturnDateType($saveReturnDateType);
return $timeValue; return $timeValue;
} }
private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0)
{ {
// Execute function // Execute function
@ -126,10 +124,10 @@ class DateTime
$adjustmentMonthsString = (string) $adjustmentMonths; $adjustmentMonthsString = (string) $adjustmentMonths;
if ($adjustmentMonths > 0) { if ($adjustmentMonths > 0) {
$adjustmentMonthsString = '+'.$adjustmentMonths; $adjustmentMonthsString = '+' . $adjustmentMonths;
} }
if ($adjustmentMonths != 0) { if ($adjustmentMonths != 0) {
$PHPDateObject->modify($adjustmentMonthsString.' months'); $PHPDateObject->modify($adjustmentMonthsString . ' months');
} }
$nMonth = (int) $PHPDateObject->format('m'); $nMonth = (int) $PHPDateObject->format('m');
$nYear = (int) $PHPDateObject->format('Y'); $nYear = (int) $PHPDateObject->format('Y');
@ -137,13 +135,13 @@ class DateTime
$monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
if ($monthDiff != $adjustmentMonths) { if ($monthDiff != $adjustmentMonths) {
$adjustDays = (int) $PHPDateObject->format('d'); $adjustDays = (int) $PHPDateObject->format('d');
$adjustDaysString = '-'.$adjustDays.' days'; $adjustDaysString = '-' . $adjustDays . ' days';
$PHPDateObject->modify($adjustDaysString); $PHPDateObject->modify($adjustDaysString);
} }
return $PHPDateObject; return $PHPDateObject;
} }
/** /**
* DATETIMENOW * DATETIMENOW
* *
@ -158,7 +156,6 @@ class DateTime
* Excel Function: * Excel Function:
* NOW() * NOW()
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
* depending on the value of the ReturnDateType flag * depending on the value of the ReturnDateType flag
@ -184,7 +181,6 @@ class DateTime
return $retValue; return $retValue;
} }
/** /**
* DATENOW * DATENOW
* *
@ -199,7 +195,6 @@ class DateTime
* Excel Function: * Excel Function:
* TODAY() * TODAY()
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
* depending on the value of the ReturnDateType flag * depending on the value of the ReturnDateType flag
@ -226,7 +221,6 @@ class DateTime
return $retValue; return $retValue;
} }
/** /**
* DATE * DATE
* *
@ -242,9 +236,8 @@ class DateTime
* A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
* as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param integer $year The value of the year argument can include one to four digits. * @param int $year The value of the year argument can include one to four digits.
* Excel interprets the year argument according to the configured * Excel interprets the year argument according to the configured
* date system: 1900 or 1904. * date system: 1900 or 1904.
* If year is between 0 (zero) and 1899 (inclusive), Excel adds that * If year is between 0 (zero) and 1899 (inclusive), Excel adds that
@ -255,7 +248,7 @@ class DateTime
* 2008. * 2008.
* If year is less than 0 or is 10000 or greater, Excel returns the * If year is less than 0 or is 10000 or greater, Excel returns the
* #NUM! error value. * #NUM! error value.
* @param integer $month A positive or negative integer representing the month of the year * @param int $month A positive or negative integer representing the month of the year
* from 1 to 12 (January to December). * from 1 to 12 (January to December).
* If month is greater than 12, month adds that number of months to * If month is greater than 12, month adds that number of months to
* the first month in the year specified. For example, DATE(2008,14,2) * the first month in the year specified. For example, DATE(2008,14,2)
@ -264,7 +257,7 @@ class DateTime
* number of months, plus 1, from the first month in the year * number of months, plus 1, from the first month in the year
* specified. For example, DATE(2008,-3,2) returns the serial number * specified. For example, DATE(2008,-3,2) returns the serial number
* representing September 2, 2007. * representing September 2, 2007.
* @param integer $day A positive or negative integer representing the day of the month * @param int $day A positive or negative integer representing the day of the month
* from 1 to 31. * from 1 to 31.
* If day is greater than the number of days in the month specified, * If day is greater than the number of days in the month specified,
* day adds that number of days to the first day in the month. For * day adds that number of days to the first day in the month. For
@ -279,9 +272,9 @@ class DateTime
*/ */
public static function DATE($year = 0, $month = 1, $day = 1) public static function DATE($year = 0, $month = 1, $day = 1)
{ {
$year = Functions::flattenSingleValue($year); $year = Functions::flattenSingleValue($year);
$month = Functions::flattenSingleValue($month); $month = Functions::flattenSingleValue($month);
$day = Functions::flattenSingleValue($day); $day = Functions::flattenSingleValue($day);
if (($month !== null) && (!is_numeric($month))) { if (($month !== null) && (!is_numeric($month))) {
$month = \PhpSpreadsheet\Shared\Date::monthStringToNumber($month); $month = \PhpSpreadsheet\Shared\Date::monthStringToNumber($month);
@ -299,20 +292,20 @@ class DateTime
(!is_numeric($day))) { (!is_numeric($day))) {
return Functions::VALUE(); return Functions::VALUE();
} }
$year = (integer) $year; $year = (integer) $year;
$month = (integer) $month; $month = (integer) $month;
$day = (integer) $day; $day = (integer) $day;
$baseYear = \PhpSpreadsheet\Shared\Date::getExcelCalendar(); $baseYear = \PhpSpreadsheet\Shared\Date::getExcelCalendar();
// Validate parameters // Validate parameters
if ($year < ($baseYear-1900)) { if ($year < ($baseYear - 1900)) {
return Functions::NAN(); return Functions::NAN();
} }
if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) { if ((($baseYear - 1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
return Functions::NAN(); return Functions::NAN();
} }
if (($year < $baseYear) && ($year >= ($baseYear-1900))) { if (($year < $baseYear) && ($year >= ($baseYear - 1900))) {
$year += 1900; $year += 1900;
} }
@ -344,7 +337,6 @@ class DateTime
} }
} }
/** /**
* TIME * TIME
* *
@ -356,16 +348,15 @@ class DateTime
* Excel Function: * Excel Function:
* TIME(hour,minute,second) * TIME(hour,minute,second)
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param integer $hour A number from 0 (zero) to 32767 representing the hour. * @param int $hour A number from 0 (zero) to 32767 representing the hour.
* Any value greater than 23 will be divided by 24 and the remainder * Any value greater than 23 will be divided by 24 and the remainder
* will be treated as the hour value. For example, TIME(27,0,0) = * will be treated as the hour value. For example, TIME(27,0,0) =
* TIME(3,0,0) = .125 or 3:00 AM. * TIME(3,0,0) = .125 or 3:00 AM.
* @param integer $minute A number from 0 to 32767 representing the minute. * @param int $minute A number from 0 to 32767 representing the minute.
* Any value greater than 59 will be converted to hours and minutes. * Any value greater than 59 will be converted to hours and minutes.
* For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM. * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
* @param integer $second A number from 0 to 32767 representing the second. * @param int $second A number from 0 to 32767 representing the second.
* Any value greater than 59 will be converted to hours, minutes, * Any value greater than 59 will be converted to hours, minutes,
* and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
* or 12:33:20 AM * or 12:33:20 AM
@ -430,6 +421,7 @@ class DateTime
if ($calendar != \PhpSpreadsheet\Shared\Date::CALENDAR_WINDOWS_1900) { if ($calendar != \PhpSpreadsheet\Shared\Date::CALENDAR_WINDOWS_1900) {
$date = 1; $date = 1;
} }
return (float) \PhpSpreadsheet\Shared\Date::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); return (float) \PhpSpreadsheet\Shared\Date::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
case Functions::RETURNDATE_PHP_NUMERIC: case Functions::RETURNDATE_PHP_NUMERIC:
return (integer) \PhpSpreadsheet\Shared\Date::excelToTimestamp(\PhpSpreadsheet\Shared\Date::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 return (integer) \PhpSpreadsheet\Shared\Date::excelToTimestamp(\PhpSpreadsheet\Shared\Date::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
@ -445,15 +437,15 @@ class DateTime
$dayAdjust = floor($hour / 24); $dayAdjust = floor($hour / 24);
$hour = $hour % 24; $hour = $hour % 24;
} }
$phpDateObject = new \DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second); $phpDateObject = new \DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second);
if ($dayAdjust != 0) { if ($dayAdjust != 0) {
$phpDateObject->modify($dayAdjust.' days'); $phpDateObject->modify($dayAdjust . ' days');
} }
return $phpDateObject; return $phpDateObject;
} }
} }
/** /**
* DATEVALUE * DATEVALUE
* *
@ -467,7 +459,6 @@ class DateTime
* Excel Function: * Excel Function:
* DATEVALUE(dateValue) * DATEVALUE(dateValue)
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param string $dateValue Text that represents a date in a Microsoft Excel date format. * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
* For example, "1/30/2008" or "30-Jan-2008" are text strings within * For example, "1/30/2008" or "30-Jan-2008" are text strings within
@ -482,12 +473,12 @@ class DateTime
*/ */
public static function DATEVALUE($dateValue = 1) public static function DATEVALUE($dateValue = 1)
{ {
$dateValueOrig= $dateValue; $dateValueOrig = $dateValue;
$dateValue = trim(Functions::flattenSingleValue($dateValue), '"'); $dateValue = trim(Functions::flattenSingleValue($dateValue), '"');
// Strip any ordinals because they're allowed in Excel (English only) // Strip any ordinals because they're allowed in Excel (English only)
$dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue); $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue);
// Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
$dateValue = str_replace(array('/', '.', '-', ' '), array(' ', ' ', ' ', ' '), $dateValue); $dateValue = str_replace(['/', '.', '-', ' '], [' ', ' ', ' ', ' '], $dateValue);
$yearFound = false; $yearFound = false;
$t1 = explode(' ', $dateValue); $t1 = explode(' ', $dateValue);
@ -541,9 +532,9 @@ class DateTime
if ($testVal1 < 31 && $testVal2 < 12 && $testVal3 < 12 && strlen($testVal3) == 2) { if ($testVal1 < 31 && $testVal2 < 12 && $testVal3 < 12 && strlen($testVal3) == 2) {
$testVal3 += 2000; $testVal3 += 2000;
} }
$PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3); $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3);
if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
$PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3); $PHPDateArray = date_parse($testVal2 . '-' . $testVal1 . '-' . $testVal3);
if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
return Functions::VALUE(); return Functions::VALUE();
} }
@ -583,13 +574,13 @@ class DateTime
case Functions::RETURNDATE_PHP_NUMERIC: case Functions::RETURNDATE_PHP_NUMERIC:
return (integer) \PhpSpreadsheet\Shared\Date::excelToTimestamp($excelDateValue); return (integer) \PhpSpreadsheet\Shared\Date::excelToTimestamp($excelDateValue);
case Functions::RETURNDATE_PHP_OBJECT: case Functions::RETURNDATE_PHP_OBJECT:
return new \DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00'); return new \DateTime($PHPDateArray['year'] . '-' . $PHPDateArray['month'] . '-' . $PHPDateArray['day'] . ' 00:00:00');
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* TIMEVALUE * TIMEVALUE
* *
@ -603,7 +594,6 @@ class DateTime
* Excel Function: * Excel Function:
* TIMEVALUE(timeValue) * TIMEVALUE(timeValue)
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param string $timeValue A text string that represents a time in any one of the Microsoft * @param string $timeValue A text string that represents a time in any one of the Microsoft
* Excel time formats; for example, "6:45 PM" and "18:45" text strings * Excel time formats; for example, "6:45 PM" and "18:45" text strings
@ -615,10 +605,10 @@ class DateTime
public static function TIMEVALUE($timeValue) public static function TIMEVALUE($timeValue)
{ {
$timeValue = trim(Functions::flattenSingleValue($timeValue), '"'); $timeValue = trim(Functions::flattenSingleValue($timeValue), '"');
$timeValue = str_replace(array('/', '.'), array('-', '-'), $timeValue); $timeValue = str_replace(['/', '.'], ['-', '-'], $timeValue);
$arraySplit = preg_split('/[\/:\-\s]/', $timeValue); $arraySplit = preg_split('/[\/:\-\s]/', $timeValue);
if ((count($arraySplit) == 2 ||count($arraySplit) == 3) && $arraySplit[0] > 24) { if ((count($arraySplit) == 2 || count($arraySplit) == 3) && $arraySplit[0] > 24) {
$arraySplit[0] = ($arraySplit[0] % 24); $arraySplit[0] = ($arraySplit[0] % 24);
$timeValue = implode(':', $arraySplit); $timeValue = implode(':', $arraySplit);
} }
@ -642,15 +632,15 @@ class DateTime
case Functions::RETURNDATE_EXCEL: case Functions::RETURNDATE_EXCEL:
return (float) $excelDateValue; return (float) $excelDateValue;
case Functions::RETURNDATE_PHP_NUMERIC: case Functions::RETURNDATE_PHP_NUMERIC:
return (integer) $phpDateValue = \PhpSpreadsheet\Shared\Date::excelToTimestamp($excelDateValue+25569) - 3600; return (integer) $phpDateValue = \PhpSpreadsheet\Shared\Date::excelToTimestamp($excelDateValue + 25569) - 3600;
case Functions::RETURNDATE_PHP_OBJECT: case Functions::RETURNDATE_PHP_OBJECT:
return new \DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']); return new \DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']);
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* DATEDIF * DATEDIF
* *
@ -659,13 +649,13 @@ class DateTime
* @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
* or a standard date string * or a standard date string
* @param string $unit * @param string $unit
* @return integer Interval between the dates * @return int Interval between the dates
*/ */
public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D')
{ {
$startDate = Functions::flattenSingleValue($startDate); $startDate = Functions::flattenSingleValue($startDate);
$endDate = Functions::flattenSingleValue($endDate); $endDate = Functions::flattenSingleValue($endDate);
$unit = strtoupper(Functions::flattenSingleValue($unit)); $unit = strtoupper(Functions::flattenSingleValue($unit));
if (is_string($startDate = self::getDateValue($startDate))) { if (is_string($startDate = self::getDateValue($startDate))) {
return Functions::VALUE(); return Functions::VALUE();
@ -719,7 +709,7 @@ class DateTime
case 'MD': case 'MD':
if ($endDays < $startDays) { if ($endDays < $startDays) {
$retVal = $endDays; $retVal = $endDays;
$PHPEndDateObject->modify('-'.$endDays.' days'); $PHPEndDateObject->modify('-' . $endDays . ' days');
$adjustDays = $PHPEndDateObject->format('j'); $adjustDays = $PHPEndDateObject->format('j');
$retVal += ($adjustDays - $startDays); $retVal += ($adjustDays - $startDays);
} else { } else {
@ -752,10 +742,10 @@ class DateTime
default: default:
$retVal = Functions::VALUE(); $retVal = Functions::VALUE();
} }
return $retVal; return $retVal;
} }
/** /**
* DAYS360 * DAYS360
* *
@ -766,13 +756,12 @@ class DateTime
* Excel Function: * Excel Function:
* DAYS360(startDate,endDate[,method]) * DAYS360(startDate,endDate[,method])
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string * PHP DateTime object, or a standard date string
* @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string * PHP DateTime object, or a standard date string
* @param boolean $method US or European Method * @param bool $method US or European Method
* FALSE or omitted: U.S. (NASD) method. If the starting date is * FALSE or omitted: U.S. (NASD) method. If the starting date is
* the last day of a month, it becomes equal to the 30th of the * the last day of a month, it becomes equal to the 30th of the
* same month. If the ending date is the last day of a month and * same month. If the ending date is the last day of a month and
@ -783,12 +772,12 @@ class DateTime
* TRUE: European method. Starting dates and ending dates that * TRUE: European method. Starting dates and ending dates that
* occur on the 31st of a month become equal to the 30th of the * occur on the 31st of a month become equal to the 30th of the
* same month. * same month.
* @return integer Number of days between start date and end date * @return int Number of days between start date and end date
*/ */
public static function DAYS360($startDate = 0, $endDate = 0, $method = false) public static function DAYS360($startDate = 0, $endDate = 0, $method = false)
{ {
$startDate = Functions::flattenSingleValue($startDate); $startDate = Functions::flattenSingleValue($startDate);
$endDate = Functions::flattenSingleValue($endDate); $endDate = Functions::flattenSingleValue($endDate);
if (is_string($startDate = self::getDateValue($startDate))) { if (is_string($startDate = self::getDateValue($startDate))) {
return Functions::VALUE(); return Functions::VALUE();
@ -815,7 +804,6 @@ class DateTime
return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method); return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
} }
/** /**
* YEARFRAC * YEARFRAC
* *
@ -827,13 +815,12 @@ class DateTime
* Excel Function: * Excel Function:
* YEARFRAC(startDate,endDate[,method]) * YEARFRAC(startDate,endDate[,method])
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string * PHP DateTime object, or a standard date string
* @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string * PHP DateTime object, or a standard date string
* @param integer $method Method used for the calculation * @param int $method Method used for the calculation
* 0 or omitted US (NASD) 30/360 * 0 or omitted US (NASD) 30/360
* 1 Actual/actual * 1 Actual/actual
* 2 Actual/360 * 2 Actual/360
@ -843,9 +830,9 @@ class DateTime
*/ */
public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0)
{ {
$startDate = Functions::flattenSingleValue($startDate); $startDate = Functions::flattenSingleValue($startDate);
$endDate = Functions::flattenSingleValue($endDate); $endDate = Functions::flattenSingleValue($endDate);
$method = Functions::flattenSingleValue($method); $method = Functions::flattenSingleValue($method);
if (is_string($startDate = self::getDateValue($startDate))) { if (is_string($startDate = self::getDateValue($startDate))) {
return Functions::VALUE(); return Functions::VALUE();
@ -871,7 +858,7 @@ class DateTime
$endDay = self::DAYOFMONTH($endDate); $endDay = self::DAYOFMONTH($endDate);
if (($startMonth < 3) || if (($startMonth < 3) ||
(($endMonth * 100 + $endDay) >= (2 * 100 + 29))) { (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
$leapDays += 1; $leapDays += 1;
} }
} }
} else { } else {
@ -901,6 +888,7 @@ class DateTime
} }
$leapDays /= $years; $leapDays /= $years;
} }
return $days / (365 + $leapDays); return $days / (365 + $leapDays);
case 2: case 2:
return self::DATEDIF($startDate, $endDate) / 360; return self::DATEDIF($startDate, $endDate) / 360;
@ -910,10 +898,10 @@ class DateTime
return self::DAYS360($startDate, $endDate, true) / 360; return self::DAYS360($startDate, $endDate, true) / 360;
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* NETWORKDAYS * NETWORKDAYS
* *
@ -925,7 +913,6 @@ class DateTime
* Excel Function: * Excel Function:
* NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string * PHP DateTime object, or a standard date string
@ -935,13 +922,13 @@ class DateTime
* timestamp (integer), PHP DateTime object, or a standard date * timestamp (integer), PHP DateTime object, or a standard date
* strings that will be excluded from the working calendar, such * strings that will be excluded from the working calendar, such
* as state and federal holidays and floating holidays. * as state and federal holidays and floating holidays.
* @return integer Interval between the dates * @return int Interval between the dates
*/ */
public static function NETWORKDAYS($startDate, $endDate) public static function NETWORKDAYS($startDate, $endDate)
{ {
// Retrieve the mandatory start and end date that are referenced in the function definition // Retrieve the mandatory start and end date that are referenced in the function definition
$startDate = Functions::flattenSingleValue($startDate); $startDate = Functions::flattenSingleValue($startDate);
$endDate = Functions::flattenSingleValue($endDate); $endDate = Functions::flattenSingleValue($endDate);
// Flush the mandatory start and end date that are referenced in the function definition, and get the optional days // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days
$dateArgs = Functions::flattenArray(func_get_args()); $dateArgs = Functions::flattenArray(func_get_args());
array_shift($dateArgs); array_shift($dateArgs);
@ -979,7 +966,7 @@ class DateTime
} }
// Test any extra holiday parameters // Test any extra holiday parameters
$holidayCountedArray = array(); $holidayCountedArray = [];
foreach ($dateArgs as $holidayDate) { foreach ($dateArgs as $holidayDate) {
if (is_string($holidayDate = self::getDateValue($holidayDate))) { if (is_string($holidayDate = self::getDateValue($holidayDate))) {
return Functions::VALUE(); return Functions::VALUE();
@ -995,10 +982,10 @@ class DateTime
if ($sDate > $eDate) { if ($sDate > $eDate) {
return 0 - ($wholeWeekDays + $partWeekDays); return 0 - ($wholeWeekDays + $partWeekDays);
} }
return $wholeWeekDays + $partWeekDays; return $wholeWeekDays + $partWeekDays;
} }
/** /**
* WORKDAY * WORKDAY
* *
@ -1010,11 +997,10 @@ class DateTime
* Excel Function: * Excel Function:
* WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
* *
* @access public
* @category Date/Time Functions * @category Date/Time Functions
* @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string * PHP DateTime object, or a standard date string
* @param integer $endDays The number of nonweekend and nonholiday days before or after * @param int $endDays The number of nonweekend and nonholiday days before or after
* startDate. A positive value for days yields a future date; a * startDate. A positive value for days yields a future date; a
* negative value yields a past date. * negative value yields a past date.
* @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
@ -1027,8 +1013,8 @@ class DateTime
public static function WORKDAY($startDate, $endDays) public static function WORKDAY($startDate, $endDays)
{ {
// Retrieve the mandatory start date and days that are referenced in the function definition // Retrieve the mandatory start date and days that are referenced in the function definition
$startDate = Functions::flattenSingleValue($startDate); $startDate = Functions::flattenSingleValue($startDate);
$endDays = Functions::flattenSingleValue($endDays); $endDays = Functions::flattenSingleValue($endDays);
// Flush the mandatory start date and days that are referenced in the function definition, and get the optional days // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days
$dateArgs = Functions::flattenArray(func_get_args()); $dateArgs = Functions::flattenArray(func_get_args());
array_shift($dateArgs); array_shift($dateArgs);
@ -1065,7 +1051,7 @@ class DateTime
// Test any extra holiday parameters // Test any extra holiday parameters
if (!empty($dateArgs)) { if (!empty($dateArgs)) {
$holidayCountedArray = $holidayDates = array(); $holidayCountedArray = $holidayDates = [];
foreach ($dateArgs as $holidayDate) { foreach ($dateArgs as $holidayDate) {
if (($holidayDate !== null) && (trim($holidayDate) > '')) { if (($holidayDate !== null) && (trim($holidayDate) > '')) {
if (is_string($holidayDate = self::getDateValue($holidayDate))) { if (is_string($holidayDate = self::getDateValue($holidayDate))) {
@ -1115,7 +1101,6 @@ class DateTime
} }
} }
/** /**
* DAYOFMONTH * DAYOFMONTH
* *
@ -1131,7 +1116,7 @@ class DateTime
*/ */
public static function DAYOFMONTH($dateValue = 1) public static function DAYOFMONTH($dateValue = 1)
{ {
$dateValue = Functions::flattenSingleValue($dateValue); $dateValue = Functions::flattenSingleValue($dateValue);
if ($dateValue === null) { if ($dateValue === null) {
$dateValue = 1; $dateValue = 1;
@ -1149,7 +1134,6 @@ class DateTime
return (int) $PHPDateObject->format('j'); return (int) $PHPDateObject->format('j');
} }
/** /**
* DAYOFWEEK * DAYOFWEEK
* *
@ -1169,8 +1153,8 @@ class DateTime
*/ */
public static function DAYOFWEEK($dateValue = 1, $style = 1) public static function DAYOFWEEK($dateValue = 1, $style = 1)
{ {
$dateValue = Functions::flattenSingleValue($dateValue); $dateValue = Functions::flattenSingleValue($dateValue);
$style = Functions::flattenSingleValue($style); $style = Functions::flattenSingleValue($style);
if (!is_numeric($style)) { if (!is_numeric($style)) {
return Functions::VALUE(); return Functions::VALUE();
@ -1222,7 +1206,6 @@ class DateTime
return (int) $DoW; return (int) $DoW;
} }
/** /**
* WEEKOFYEAR * WEEKOFYEAR
* *
@ -1238,15 +1221,15 @@ class DateTime
* *
* @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string * PHP DateTime object, or a standard date string
* @param boolean $method Week begins on Sunday or Monday * @param bool $method Week begins on Sunday or Monday
* 1 or omitted Week begins on Sunday. * 1 or omitted Week begins on Sunday.
* 2 Week begins on Monday. * 2 Week begins on Monday.
* @return int Week Number * @return int Week Number
*/ */
public static function WEEKOFYEAR($dateValue = 1, $method = 1) public static function WEEKOFYEAR($dateValue = 1, $method = 1)
{ {
$dateValue = Functions::flattenSingleValue($dateValue); $dateValue = Functions::flattenSingleValue($dateValue);
$method = Functions::flattenSingleValue($method); $method = Functions::flattenSingleValue($method);
if (!is_numeric($method)) { if (!is_numeric($method)) {
return Functions::VALUE(); return Functions::VALUE();
@ -1275,7 +1258,6 @@ class DateTime
return (int) $weekOfYear; return (int) $weekOfYear;
} }
/** /**
* MONTHOFYEAR * MONTHOFYEAR
* *
@ -1291,7 +1273,7 @@ class DateTime
*/ */
public static function MONTHOFYEAR($dateValue = 1) public static function MONTHOFYEAR($dateValue = 1)
{ {
$dateValue = Functions::flattenSingleValue($dateValue); $dateValue = Functions::flattenSingleValue($dateValue);
if (empty($dateValue)) { if (empty($dateValue)) {
$dateValue = 1; $dateValue = 1;
@ -1308,7 +1290,6 @@ class DateTime
return (int) $PHPDateObject->format('n'); return (int) $PHPDateObject->format('n');
} }
/** /**
* YEAR * YEAR
* *
@ -1324,7 +1305,7 @@ class DateTime
*/ */
public static function YEAR($dateValue = 1) public static function YEAR($dateValue = 1)
{ {
$dateValue = Functions::flattenSingleValue($dateValue); $dateValue = Functions::flattenSingleValue($dateValue);
if ($dateValue === null) { if ($dateValue === null) {
$dateValue = 1; $dateValue = 1;
@ -1340,7 +1321,6 @@ class DateTime
return (int) $PHPDateObject->format('Y'); return (int) $PHPDateObject->format('Y');
} }
/** /**
* HOUROFDAY * HOUROFDAY
* *
@ -1356,7 +1336,7 @@ class DateTime
*/ */
public static function HOUROFDAY($timeValue = 0) public static function HOUROFDAY($timeValue = 0)
{ {
$timeValue = Functions::flattenSingleValue($timeValue); $timeValue = Functions::flattenSingleValue($timeValue);
if (!is_numeric($timeValue)) { if (!is_numeric($timeValue)) {
if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
@ -1381,7 +1361,6 @@ class DateTime
return (int) gmdate('G', $timeValue); return (int) gmdate('G', $timeValue);
} }
/** /**
* MINUTEOFHOUR * MINUTEOFHOUR
* *
@ -1397,7 +1376,7 @@ class DateTime
*/ */
public static function MINUTEOFHOUR($timeValue = 0) public static function MINUTEOFHOUR($timeValue = 0)
{ {
$timeValue = $timeTester = Functions::flattenSingleValue($timeValue); $timeValue = $timeTester = Functions::flattenSingleValue($timeValue);
if (!is_numeric($timeValue)) { if (!is_numeric($timeValue)) {
if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
@ -1422,7 +1401,6 @@ class DateTime
return (int) gmdate('i', $timeValue); return (int) gmdate('i', $timeValue);
} }
/** /**
* SECONDOFMINUTE * SECONDOFMINUTE
* *
@ -1438,7 +1416,7 @@ class DateTime
*/ */
public static function SECONDOFMINUTE($timeValue = 0) public static function SECONDOFMINUTE($timeValue = 0)
{ {
$timeValue = Functions::flattenSingleValue($timeValue); $timeValue = Functions::flattenSingleValue($timeValue);
if (!is_numeric($timeValue)) { if (!is_numeric($timeValue)) {
if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
@ -1463,7 +1441,6 @@ class DateTime
return (int) gmdate('s', $timeValue); return (int) gmdate('s', $timeValue);
} }
/** /**
* EDATE * EDATE
* *
@ -1485,8 +1462,8 @@ class DateTime
*/ */
public static function EDATE($dateValue = 1, $adjustmentMonths = 0) public static function EDATE($dateValue = 1, $adjustmentMonths = 0)
{ {
$dateValue = Functions::flattenSingleValue($dateValue); $dateValue = Functions::flattenSingleValue($dateValue);
$adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths);
if (!is_numeric($adjustmentMonths)) { if (!is_numeric($adjustmentMonths)) {
return Functions::VALUE(); return Functions::VALUE();
@ -1510,7 +1487,6 @@ class DateTime
} }
} }
/** /**
* EOMONTH * EOMONTH
* *
@ -1531,8 +1507,8 @@ class DateTime
*/ */
public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0)
{ {
$dateValue = Functions::flattenSingleValue($dateValue); $dateValue = Functions::flattenSingleValue($dateValue);
$adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths);
if (!is_numeric($adjustmentMonths)) { if (!is_numeric($adjustmentMonths)) {
return Functions::VALUE(); return Functions::VALUE();
@ -1544,7 +1520,7 @@ class DateTime
} }
// Execute function // Execute function
$PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths+1); $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths + 1);
$adjustDays = (int) $PHPDateObject->format('d'); $adjustDays = (int) $PHPDateObject->format('d');
$adjustDaysString = '-' . $adjustDays . ' days'; $adjustDaysString = '-' . $adjustDays . ' days';
$PHPDateObject->modify($adjustDaysString); $PHPDateObject->modify($adjustDaysString);

File diff suppressed because it is too large Load Diff

View File

@ -31,7 +31,7 @@ class ExceptionHandler
*/ */
public function __construct() public function __construct()
{ {
set_error_handler(array('\\PhpSpreadsheet\\Calculation\\Exception', 'errorHandlerCallback'), E_ALL); set_error_handler(['\\PhpSpreadsheet\\Calculation\\Exception', 'errorHandlerCallback'], E_ALL);
} }
/** /**

File diff suppressed because it is too large Load Diff

View File

@ -49,22 +49,22 @@ PARTLY BASED ON:
class FormulaParser class FormulaParser
{ {
/* Character constants */ /* Character constants */
const QUOTE_DOUBLE = '"'; const QUOTE_DOUBLE = '"';
const QUOTE_SINGLE = '\''; const QUOTE_SINGLE = '\'';
const BRACKET_CLOSE = ']'; const BRACKET_CLOSE = ']';
const BRACKET_OPEN = '['; const BRACKET_OPEN = '[';
const BRACE_OPEN = '{'; const BRACE_OPEN = '{';
const BRACE_CLOSE = '}'; const BRACE_CLOSE = '}';
const PAREN_OPEN = '('; const PAREN_OPEN = '(';
const PAREN_CLOSE = ')'; const PAREN_CLOSE = ')';
const SEMICOLON = ';'; const SEMICOLON = ';';
const WHITESPACE = ' '; const WHITESPACE = ' ';
const COMMA = ','; const COMMA = ',';
const ERROR_START = '#'; const ERROR_START = '#';
const OPERATORS_SN = "+-"; const OPERATORS_SN = '+-';
const OPERATORS_INFIX = "+-*/^&=><"; const OPERATORS_INFIX = '+-*/^&=><';
const OPERATORS_POSTFIX = "%"; const OPERATORS_POSTFIX = '%';
/** /**
* Formula * Formula
@ -78,7 +78,7 @@ class FormulaParser
* *
* @var FormulaToken[] * @var FormulaToken[]
*/ */
private $tokens = array(); private $tokens = [];
/** /**
* Create a new FormulaParser * Create a new FormulaParser
@ -90,7 +90,7 @@ class FormulaParser
{ {
// Check parameters // Check parameters
if (is_null($pFormula)) { if (is_null($pFormula)) {
throw new Exception("Invalid parameter passed: formula"); throw new Exception('Invalid parameter passed: formula');
} }
// Initialise values // Initialise values
@ -113,8 +113,8 @@ class FormulaParser
* Get Token * Get Token
* *
* @param int $pId Token id * @param int $pId Token id
* @return string
* @throws Exception * @throws Exception
* @return string
*/ */
public function getToken($pId = 0) public function getToken($pId = 0)
{ {
@ -160,15 +160,15 @@ class FormulaParser
} }
// Helper variables // Helper variables
$tokens1 = $tokens2 = $stack = array(); $tokens1 = $tokens2 = $stack = [];
$inString = $inPath = $inRange = $inError = false; $inString = $inPath = $inRange = $inError = false;
$token = $previousToken = $nextToken = null; $token = $previousToken = $nextToken = null;
$index = 1; $index = 1;
$value = ''; $value = '';
$ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"); $ERRORS = ['#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A'];
$COMPARATORS_MULTI = array(">=", "<=", "<>"); $COMPARATORS_MULTI = ['>=', '<=', '<>'];
while ($index < $formulaLength) { while ($index < $formulaLength) {
// state-dependent character evaluation (order is important) // state-dependent character evaluation (order is important)
@ -184,7 +184,7 @@ class FormulaParser
} else { } else {
$inString = false; $inString = false;
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_TEXT); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_TEXT);
$value = ""; $value = '';
} }
} else { } else {
$value .= $this->formula{$index}; $value .= $this->formula{$index};
@ -231,7 +231,7 @@ class FormulaParser
if (in_array($value, $ERRORS)) { if (in_array($value, $ERRORS)) {
$inError = false; $inError = false;
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_ERROR); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_ERROR);
$value = ""; $value = '';
} }
continue; continue;
} }
@ -254,7 +254,7 @@ class FormulaParser
if (strlen($value > 0)) { if (strlen($value > 0)) {
// unexpected // unexpected
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN);
$value = ""; $value = '';
} }
$inString = true; $inString = true;
++$index; ++$index;
@ -265,7 +265,7 @@ class FormulaParser
if (strlen($value) > 0) { if (strlen($value) > 0) {
// unexpected // unexpected
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN);
$value = ""; $value = '';
} }
$inPath = true; $inPath = true;
++$index; ++$index;
@ -283,7 +283,7 @@ class FormulaParser
if (strlen($value) > 0) { if (strlen($value) > 0) {
// unexpected // unexpected
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN);
$value = ""; $value = '';
} }
$inError = true; $inError = true;
$value .= self::ERROR_START; $value .= self::ERROR_START;
@ -296,14 +296,14 @@ class FormulaParser
if (strlen($value) > 0) { if (strlen($value) > 0) {
// unexpected // unexpected
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN);
$value = ""; $value = '';
} }
$tmp = new FormulaToken("ARRAY", FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tmp = new FormulaToken('ARRAY', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$stack[] = clone $tmp; $stack[] = clone $tmp;
$tmp = new FormulaToken("ARRAYROW", FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$stack[] = clone $tmp; $stack[] = clone $tmp;
@ -314,18 +314,18 @@ class FormulaParser
if ($this->formula{$index} == self::SEMICOLON) { if ($this->formula{$index} == self::SEMICOLON) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tmp = array_pop($stack); $tmp = array_pop($stack);
$tmp->setValue(""); $tmp->setValue('');
$tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$tmp = new FormulaToken(",", FormulaToken::TOKEN_TYPE_ARGUMENT); $tmp = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$tmp = new FormulaToken("ARRAYROW", FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$stack[] = clone $tmp; $stack[] = clone $tmp;
@ -336,16 +336,16 @@ class FormulaParser
if ($this->formula{$index} == self::BRACE_CLOSE) { if ($this->formula{$index} == self::BRACE_CLOSE) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tmp = array_pop($stack); $tmp = array_pop($stack);
$tmp->setValue(""); $tmp->setValue('');
$tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$tmp = array_pop($stack); $tmp = array_pop($stack);
$tmp->setValue(""); $tmp->setValue('');
$tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP);
$tokens1[] = $tmp; $tokens1[] = $tmp;
@ -357,9 +357,9 @@ class FormulaParser
if ($this->formula{$index} == self::WHITESPACE) { if ($this->formula{$index} == self::WHITESPACE) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tokens1[] = new FormulaToken("", FormulaToken::TOKEN_TYPE_WHITESPACE); $tokens1[] = new FormulaToken('', FormulaToken::TOKEN_TYPE_WHITESPACE);
++$index; ++$index;
while (($this->formula{$index} == self::WHITESPACE) && ($index < $formulaLength)) { while (($this->formula{$index} == self::WHITESPACE) && ($index < $formulaLength)) {
++$index; ++$index;
@ -372,7 +372,7 @@ class FormulaParser
if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) { if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tokens1[] = new FormulaToken(substr($this->formula, $index, 2), FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_LOGICAL); $tokens1[] = new FormulaToken(substr($this->formula, $index, 2), FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_LOGICAL);
$index += 2; $index += 2;
@ -383,8 +383,8 @@ class FormulaParser
// standard infix operators // standard infix operators
if (strpos(self::OPERATORS_INFIX, $this->formula{$index}) !== false) { if (strpos(self::OPERATORS_INFIX, $this->formula{$index}) !== false) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] =new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tokens1[] = new FormulaToken($this->formula{$index}, FormulaToken::TOKEN_TYPE_OPERATORINFIX); $tokens1[] = new FormulaToken($this->formula{$index}, FormulaToken::TOKEN_TYPE_OPERATORINFIX);
++$index; ++$index;
@ -395,7 +395,7 @@ class FormulaParser
if (strpos(self::OPERATORS_POSTFIX, $this->formula{$index}) !== false) { if (strpos(self::OPERATORS_POSTFIX, $this->formula{$index}) !== false) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tokens1[] = new FormulaToken($this->formula{$index}, FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); $tokens1[] = new FormulaToken($this->formula{$index}, FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX);
++$index; ++$index;
@ -408,9 +408,9 @@ class FormulaParser
$tmp = new FormulaToken($value, FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tmp = new FormulaToken($value, FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$stack[] = clone $tmp; $stack[] = clone $tmp;
$value = ""; $value = '';
} else { } else {
$tmp = new FormulaToken("", FormulaToken::TOKEN_TYPE_SUBEXPRESSION, FormulaToken::TOKEN_SUBTYPE_START); $tmp = new FormulaToken('', FormulaToken::TOKEN_TYPE_SUBEXPRESSION, FormulaToken::TOKEN_SUBTYPE_START);
$tokens1[] = $tmp; $tokens1[] = $tmp;
$stack[] = clone $tmp; $stack[] = clone $tmp;
} }
@ -422,18 +422,18 @@ class FormulaParser
if ($this->formula{$index} == self::COMMA) { if ($this->formula{$index} == self::COMMA) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tmp = array_pop($stack); $tmp = array_pop($stack);
$tmp->setValue(""); $tmp->setValue('');
$tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP);
$stack[] = $tmp; $stack[] = $tmp;
if ($tmp->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { if ($tmp->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) {
$tokens1[] = new FormulaToken(",", FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_UNION); $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_UNION);
} else { } else {
$tokens1[] = new FormulaToken(",", FormulaToken::TOKEN_TYPE_ARGUMENT); $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT);
} }
++$index; ++$index;
continue; continue;
@ -443,11 +443,11 @@ class FormulaParser
if ($this->formula{$index} == self::PAREN_CLOSE) { if ($this->formula{$index} == self::PAREN_CLOSE) {
if (strlen($value) > 0) { if (strlen($value) > 0) {
$tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND);
$value = ""; $value = '';
} }
$tmp = array_pop($stack); $tmp = array_pop($stack);
$tmp->setValue(""); $tmp->setValue('');
$tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP);
$tokens1[] = $tmp; $tokens1[] = $tmp;
@ -493,11 +493,11 @@ class FormulaParser
continue; continue;
} }
if (! ( if (!(
(($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) ||
(($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) ||
($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND)
) ) { )) {
continue; continue;
} }
@ -505,11 +505,11 @@ class FormulaParser
continue; continue;
} }
if (! ( if (!(
(($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) ||
(($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) ||
($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND)
) ) { )) {
continue; continue;
} }
@ -518,7 +518,7 @@ class FormulaParser
// move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators
// to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names
$this->tokens = array(); $this->tokens = [];
$tokenCount = count($tokens2); $tokenCount = count($tokens2);
for ($i = 0; $i < $tokenCount; ++$i) { for ($i = 0; $i < $tokenCount; ++$i) {
@ -538,7 +538,7 @@ class FormulaParser
continue; continue;
} }
if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") { if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '-') {
if ($i == 0) { if ($i == 0) {
$token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
} elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && } elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) &&
@ -556,7 +556,7 @@ class FormulaParser
continue; continue;
} }
if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") { if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '+') {
if ($i == 0) { if ($i == 0) {
continue; continue;
} elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && } elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) &&
@ -576,9 +576,9 @@ class FormulaParser
if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX &&
$token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING) { $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING) {
if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) { if (strpos('<>=', substr($token->getValue(), 0, 1)) !== false) {
$token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL);
} elseif ($token->getValue() == "&") { } elseif ($token->getValue() == '&') {
$token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_CONCATENATION); $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_CONCATENATION);
} else { } else {
$token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH);
@ -591,7 +591,7 @@ class FormulaParser
if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND &&
$token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING) { $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING) {
if (!is_numeric($token->getValue())) { if (!is_numeric($token->getValue())) {
if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) { if (strtoupper($token->getValue()) == 'TRUE' || strtoupper($token->getValue() == 'FALSE')) {
$token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL);
} else { } else {
$token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_RANGE); $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_RANGE);
@ -606,7 +606,7 @@ class FormulaParser
if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) {
if (strlen($token->getValue() > 0)) { if (strlen($token->getValue() > 0)) {
if (substr($token->getValue(), 0, 1) == "@") { if (substr($token->getValue(), 0, 1) == '@') {
$token->setValue(substr($token->getValue(), 1)); $token->setValue(substr($token->getValue(), 1));
} }
} }

View File

@ -50,30 +50,30 @@ PARTLY BASED ON:
class FormulaToken class FormulaToken
{ {
/* Token types */ /* Token types */
const TOKEN_TYPE_NOOP = 'Noop'; const TOKEN_TYPE_NOOP = 'Noop';
const TOKEN_TYPE_OPERAND = 'Operand'; const TOKEN_TYPE_OPERAND = 'Operand';
const TOKEN_TYPE_FUNCTION = 'Function'; const TOKEN_TYPE_FUNCTION = 'Function';
const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression'; const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression';
const TOKEN_TYPE_ARGUMENT = 'Argument'; const TOKEN_TYPE_ARGUMENT = 'Argument';
const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix'; const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix';
const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix'; const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix';
const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix'; const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix';
const TOKEN_TYPE_WHITESPACE = 'Whitespace'; const TOKEN_TYPE_WHITESPACE = 'Whitespace';
const TOKEN_TYPE_UNKNOWN = 'Unknown'; const TOKEN_TYPE_UNKNOWN = 'Unknown';
/* Token subtypes */ /* Token subtypes */
const TOKEN_SUBTYPE_NOTHING = 'Nothing'; const TOKEN_SUBTYPE_NOTHING = 'Nothing';
const TOKEN_SUBTYPE_START = 'Start'; const TOKEN_SUBTYPE_START = 'Start';
const TOKEN_SUBTYPE_STOP = 'Stop'; const TOKEN_SUBTYPE_STOP = 'Stop';
const TOKEN_SUBTYPE_TEXT = 'Text'; const TOKEN_SUBTYPE_TEXT = 'Text';
const TOKEN_SUBTYPE_NUMBER = 'Number'; const TOKEN_SUBTYPE_NUMBER = 'Number';
const TOKEN_SUBTYPE_LOGICAL = 'Logical'; const TOKEN_SUBTYPE_LOGICAL = 'Logical';
const TOKEN_SUBTYPE_ERROR = 'Error'; const TOKEN_SUBTYPE_ERROR = 'Error';
const TOKEN_SUBTYPE_RANGE = 'Range'; const TOKEN_SUBTYPE_RANGE = 'Range';
const TOKEN_SUBTYPE_MATH = 'Math'; const TOKEN_SUBTYPE_MATH = 'Math';
const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation'; const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation';
const TOKEN_SUBTYPE_INTERSECTION = 'Intersection'; const TOKEN_SUBTYPE_INTERSECTION = 'Intersection';
const TOKEN_SUBTYPE_UNION = 'Union'; const TOKEN_SUBTYPE_UNION = 'Union';
/** /**
* Value * Value
@ -106,8 +106,8 @@ class FormulaToken
public function __construct($pValue, $pTokenType = self::TOKEN_TYPE_UNKNOWN, $pTokenSubType = self::TOKEN_SUBTYPE_NOTHING) public function __construct($pValue, $pTokenType = self::TOKEN_TYPE_UNKNOWN, $pTokenSubType = self::TOKEN_SUBTYPE_NOTHING)
{ {
// Initialise values // Initialise values
$this->value = $pValue; $this->value = $pValue;
$this->tokenType = $pTokenType; $this->tokenType = $pTokenType;
$this->tokenSubType = $pTokenSubType; $this->tokenSubType = $pTokenSubType;
} }

View File

@ -2,19 +2,18 @@
namespace PhpSpreadsheet\Calculation; namespace PhpSpreadsheet\Calculation;
/** MAX_VALUE */ /* MAX_VALUE */
define('MAX_VALUE', 1.2e308); define('MAX_VALUE', 1.2e308);
/** 2 / PI */ /* 2 / PI */
define('M_2DIVPI', 0.63661977236758134307553505349006); define('M_2DIVPI', 0.63661977236758134307553505349006);
/** MAX_ITERATIONS */ /* MAX_ITERATIONS */
define('MAX_ITERATIONS', 256); define('MAX_ITERATIONS', 256);
/** PRECISION */ /* PRECISION */
define('PRECISION', 8.88E-016); define('PRECISION', 8.88E-016);
/** /**
* Copyright (c) 2006 - 2016 PhpSpreadsheet * Copyright (c) 2006 - 2016 PhpSpreadsheet
* *
@ -48,11 +47,9 @@ class Functions
const RETURNDATE_PHP_OBJECT = 'O'; const RETURNDATE_PHP_OBJECT = 'O';
const RETURNDATE_EXCEL = 'E'; const RETURNDATE_EXCEL = 'E';
/** /**
* Compatibility mode to use for error checking and responses * Compatibility mode to use for error checking and responses
* *
* @access private
* @var string * @var string
*/ */
protected static $compatibilityMode = self::COMPATIBILITY_EXCEL; protected static $compatibilityMode = self::COMPATIBILITY_EXCEL;
@ -60,7 +57,6 @@ class Functions
/** /**
* Data Type to use when returning date values * Data Type to use when returning date values
* *
* @access private
* @var string * @var string
*/ */
protected static $returnDateType = self::RETURNDATE_EXCEL; protected static $returnDateType = self::RETURNDATE_EXCEL;
@ -68,10 +64,9 @@ class Functions
/** /**
* List of error codes * List of error codes
* *
* @access private
* @var array * @var array
*/ */
protected static $errorCodes = array( protected static $errorCodes = [
'null' => '#NULL!', 'null' => '#NULL!',
'divisionbyzero' => '#DIV/0!', 'divisionbyzero' => '#DIV/0!',
'value' => '#VALUE!', 'value' => '#VALUE!',
@ -79,21 +74,19 @@ class Functions
'name' => '#NAME?', 'name' => '#NAME?',
'num' => '#NUM!', 'num' => '#NUM!',
'na' => '#N/A', 'na' => '#N/A',
'gettingdata' => '#GETTING_DATA' 'gettingdata' => '#GETTING_DATA',
); ];
/** /**
* Set the Compatibility Mode * Set the Compatibility Mode
* *
* @access public
* @category Function Configuration * @category Function Configuration
* @param string $compatibilityMode Compatibility Mode * @param string $compatibilityMode Compatibility Mode
* Permitted values are: * Permitted values are:
* Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_EXCEL 'Excel'
* Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
* Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
* @return boolean (Success or Failure) * @return bool (Success or Failure)
*/ */
public static function setCompatibilityMode($compatibilityMode) public static function setCompatibilityMode($compatibilityMode)
{ {
@ -102,16 +95,16 @@ class Functions
($compatibilityMode == self::COMPATIBILITY_OPENOFFICE) ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)
) { ) {
self::$compatibilityMode = $compatibilityMode; self::$compatibilityMode = $compatibilityMode;
return true; return true;
} }
return false; return false;
} }
/** /**
* Return the current Compatibility Mode * Return the current Compatibility Mode
* *
* @access public
* @category Function Configuration * @category Function Configuration
* @return string Compatibility Mode * @return string Compatibility Mode
* Possible Return values are: * Possible Return values are:
@ -124,18 +117,16 @@ class Functions
return self::$compatibilityMode; return self::$compatibilityMode;
} }
/** /**
* Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object) * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
* *
* @access public
* @category Function Configuration * @category Function Configuration
* @param string $returnDateType Return Date Format * @param string $returnDateType Return Date Format
* Permitted values are: * Permitted values are:
* Functions::RETURNDATE_PHP_NUMERIC 'P' * Functions::RETURNDATE_PHP_NUMERIC 'P'
* Functions::RETURNDATE_PHP_OBJECT 'O' * Functions::RETURNDATE_PHP_OBJECT 'O'
* Functions::RETURNDATE_EXCEL 'E' * Functions::RETURNDATE_EXCEL 'E'
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setReturnDateType($returnDateType) public static function setReturnDateType($returnDateType)
{ {
@ -144,16 +135,16 @@ class Functions
($returnDateType == self::RETURNDATE_EXCEL) ($returnDateType == self::RETURNDATE_EXCEL)
) { ) {
self::$returnDateType = $returnDateType; self::$returnDateType = $returnDateType;
return true; return true;
} }
return false; return false;
} }
/** /**
* Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object) * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
* *
* @access public
* @category Function Configuration * @category Function Configuration
* @return string Return Date Format * @return string Return Date Format
* Possible Return values are: * Possible Return values are:
@ -166,11 +157,9 @@ class Functions
return self::$returnDateType; return self::$returnDateType;
} }
/** /**
* DUMMY * DUMMY
* *
* @access public
* @category Error Returns * @category Error Returns
* @return string #Not Yet Implemented * @return string #Not Yet Implemented
*/ */
@ -179,11 +168,9 @@ class Functions
return '#Not Yet Implemented'; return '#Not Yet Implemented';
} }
/** /**
* DIV0 * DIV0
* *
* @access public
* @category Error Returns * @category Error Returns
* @return string #Not Yet Implemented * @return string #Not Yet Implemented
*/ */
@ -192,7 +179,6 @@ class Functions
return self::$errorCodes['divisionbyzero']; return self::$errorCodes['divisionbyzero'];
} }
/** /**
* NA * NA
* *
@ -202,7 +188,6 @@ class Functions
* Returns the error value #N/A * Returns the error value #N/A
* #N/A is the error value that means "no value is available." * #N/A is the error value that means "no value is available."
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @return string #N/A! * @return string #N/A!
*/ */
@ -211,13 +196,11 @@ class Functions
return self::$errorCodes['na']; return self::$errorCodes['na'];
} }
/** /**
* NaN * NaN
* *
* Returns the error value #NUM! * Returns the error value #NUM!
* *
* @access public
* @category Error Returns * @category Error Returns
* @return string #NUM! * @return string #NUM!
*/ */
@ -226,13 +209,11 @@ class Functions
return self::$errorCodes['num']; return self::$errorCodes['num'];
} }
/** /**
* NAME * NAME
* *
* Returns the error value #NAME? * Returns the error value #NAME?
* *
* @access public
* @category Error Returns * @category Error Returns
* @return string #NAME? * @return string #NAME?
*/ */
@ -241,13 +222,11 @@ class Functions
return self::$errorCodes['name']; return self::$errorCodes['name'];
} }
/** /**
* REF * REF
* *
* Returns the error value #REF! * Returns the error value #REF!
* *
* @access public
* @category Error Returns * @category Error Returns
* @return string #REF! * @return string #REF!
*/ */
@ -256,28 +235,24 @@ class Functions
return self::$errorCodes['reference']; return self::$errorCodes['reference'];
} }
/** /**
* NULL * NULL
* *
* Returns the error value #NULL! * Returns the error value #NULL!
* *
* @access public
* @category Error Returns * @category Error Returns
* @return string #NULL! * @return string #NULL!
*/ */
public static function NULL() public static function null()
{ {
return self::$errorCodes['null']; return self::$errorCodes['null'];
} }
/** /**
* VALUE * VALUE
* *
* Returns the error value #VALUE! * Returns the error value #VALUE!
* *
* @access public
* @category Error Returns * @category Error Returns
* @return string #VALUE! * @return string #VALUE!
*/ */
@ -286,35 +261,32 @@ class Functions
return self::$errorCodes['value']; return self::$errorCodes['value'];
} }
public static function isMatrixValue($idx) public static function isMatrixValue($idx)
{ {
return ((substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0)); return (substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0);
} }
public static function isValue($idx) public static function isValue($idx)
{ {
return (substr_count($idx, '.') == 0); return substr_count($idx, '.') == 0;
} }
public static function isCellValue($idx) public static function isCellValue($idx)
{ {
return (substr_count($idx, '.') > 1); return substr_count($idx, '.') > 1;
} }
public static function ifCondition($condition) public static function ifCondition($condition)
{ {
$condition = Functions::flattenSingleValue($condition); $condition = self::flattenSingleValue($condition);
if (!isset($condition{0})) { if (!isset($condition{0})) {
$condition = '=""'; $condition = '=""';
} }
if (!in_array($condition{0}, array('>', '<', '='))) { if (!in_array($condition{0}, ['>', '<', '='])) {
if (!is_numeric($condition)) { if (!is_numeric($condition)) {
$condition = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($condition)); $condition = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($condition));
} }
return '=' . $condition; return '=' . $condition;
} else { } else {
preg_match('/([<>=]+)(.*)/', $condition, $matches); preg_match('/([<>=]+)(.*)/', $condition, $matches);
@ -333,7 +305,7 @@ class Functions
* ERROR_TYPE * ERROR_TYPE
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function errorType($value = '') public static function errorType($value = '')
{ {
@ -346,15 +318,15 @@ class Functions
} }
++$i; ++$i;
} }
return self::NA(); return self::NA();
} }
/** /**
* IS_BLANK * IS_BLANK
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isBlank($value = null) public static function isBlank($value = null)
{ {
@ -365,12 +337,11 @@ class Functions
return is_null($value); return is_null($value);
} }
/** /**
* IS_ERR * IS_ERR
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isErr($value = '') public static function isErr($value = '')
{ {
@ -379,12 +350,11 @@ class Functions
return self::isError($value) && (!self::isNa(($value))); return self::isError($value) && (!self::isNa(($value)));
} }
/** /**
* IS_ERROR * IS_ERROR
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isError($value = '') public static function isError($value = '')
{ {
@ -393,29 +363,28 @@ class Functions
if (!is_string($value)) { if (!is_string($value)) {
return false; return false;
} }
return in_array($value, array_values(self::$errorCodes)); return in_array($value, array_values(self::$errorCodes));
} }
/** /**
* IS_NA * IS_NA
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isNa($value = '') public static function isNa($value = '')
{ {
$value = self::flattenSingleValue($value); $value = self::flattenSingleValue($value);
return ($value === self::NA()); return $value === self::NA();
} }
/** /**
* IS_EVEN * IS_EVEN
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isEven($value = null) public static function isEven($value = null)
{ {
@ -427,15 +396,14 @@ class Functions
return self::VALUE(); return self::VALUE();
} }
return ($value % 2 == 0); return $value % 2 == 0;
} }
/** /**
* IS_ODD * IS_ODD
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isOdd($value = null) public static function isOdd($value = null)
{ {
@ -447,15 +415,14 @@ class Functions
return self::VALUE(); return self::VALUE();
} }
return (abs($value) % 2 == 1); return abs($value) % 2 == 1;
} }
/** /**
* IS_NUMBER * IS_NUMBER
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isNumber($value = null) public static function isNumber($value = null)
{ {
@ -464,15 +431,15 @@ class Functions
if (is_string($value)) { if (is_string($value)) {
return false; return false;
} }
return is_numeric($value); return is_numeric($value);
} }
/** /**
* IS_LOGICAL * IS_LOGICAL
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isLogical($value = null) public static function isLogical($value = null)
{ {
@ -481,33 +448,30 @@ class Functions
return is_bool($value); return is_bool($value);
} }
/** /**
* IS_TEXT * IS_TEXT
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isText($value = null) public static function isText($value = null)
{ {
$value = self::flattenSingleValue($value); $value = self::flattenSingleValue($value);
return (is_string($value) && !self::isError($value)); return is_string($value) && !self::isError($value);
} }
/** /**
* IS_NONTEXT * IS_NONTEXT
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function isNonText($value = null) public static function isNonText($value = null)
{ {
return !self::isText($value); return !self::isText($value);
} }
/** /**
* VERSION * VERSION
* *
@ -518,7 +482,6 @@ class Functions
return 'PhpSpreadsheet ##VERSION##, ##DATE##'; return 'PhpSpreadsheet ##VERSION##, ##DATE##';
} }
/** /**
* N * N
* *
@ -546,7 +509,7 @@ class Functions
case 'integer': case 'integer':
return $value; return $value;
case 'boolean': case 'boolean':
return (integer)$value; return (integer) $value;
case 'string': case 'string':
// Errors // Errors
if ((strlen($value) > 0) && ($value{0} == '#')) { if ((strlen($value) > 0) && ($value{0} == '#')) {
@ -554,10 +517,10 @@ class Functions
} }
break; break;
} }
return 0; return 0;
} }
/** /**
* TYPE * TYPE
* *
@ -602,12 +565,13 @@ class Functions
if ((strlen($value) > 0) && ($value{0} == '#')) { if ((strlen($value) > 0) && ($value{0} == '#')) {
return 16; return 16;
} }
return 2; return 2;
} }
return 0; return 0;
} }
/** /**
* Convert a multi-dimensional array to a simple 1-dimensional array * Convert a multi-dimensional array to a simple 1-dimensional array
* *
@ -617,10 +581,10 @@ class Functions
public static function flattenArray($array) public static function flattenArray($array)
{ {
if (!is_array($array)) { if (!is_array($array)) {
return (array)$array; return (array) $array;
} }
$arrayValues = array(); $arrayValues = [];
foreach ($array as $value) { foreach ($array as $value) {
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $val) { foreach ($value as $val) {
@ -640,7 +604,6 @@ class Functions
return $arrayValues; return $arrayValues;
} }
/** /**
* Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
* *
@ -650,10 +613,10 @@ class Functions
public static function flattenArrayIndexed($array) public static function flattenArrayIndexed($array)
{ {
if (!is_array($array)) { if (!is_array($array)) {
return (array)$array; return (array) $array;
} }
$arrayValues = array(); $arrayValues = [];
foreach ($array as $k1 => $value) { foreach ($array as $k1 => $value) {
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $k2 => $val) { foreach ($value as $k2 => $val) {
@ -673,7 +636,6 @@ class Functions
return $arrayValues; return $arrayValues;
} }
/** /**
* Convert an array to a single scalar value by extracting the first element * Convert an array to a single scalar value by extracting the first element
* *
@ -690,7 +652,6 @@ class Functions
} }
} }
// //
// There are a few mathematical functions that aren't available on all versions of PHP for all platforms // There are a few mathematical functions that aren't available on all versions of PHP for all platforms
// These functions aren't available in Windows implementations of PHP prior to version 5.3.0 // These functions aren't available in Windows implementations of PHP prior to version 5.3.0
@ -717,7 +678,6 @@ if (!function_exists('atanh')) {
} // function atanh() } // function atanh()
} }
// //
// Strangely, PHP doesn't have a mb_str_replace multibyte function // Strangely, PHP doesn't have a mb_str_replace multibyte function
// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set // As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
@ -728,14 +688,15 @@ if ((!function_exists('mb_str_replace')) &&
function mb_str_replace($search, $replace, $subject) function mb_str_replace($search, $replace, $subject)
{ {
if (is_array($subject)) { if (is_array($subject)) {
$ret = array(); $ret = [];
foreach ($subject as $key => $val) { foreach ($subject as $key => $val) {
$ret[$key] = mb_str_replace($search, $replace, $val); $ret[$key] = mb_str_replace($search, $replace, $val);
} }
return $ret; return $ret;
} }
foreach ((array)$search as $key => $s) { foreach ((array) $search as $key => $s) {
if ($s == '' && $s !== 0) { if ($s == '' && $s !== 0) {
continue; continue;
} }
@ -746,6 +707,7 @@ if ((!function_exists('mb_str_replace')) &&
$pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8'); $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
} }
} }
return $subject; return $subject;
} }
} }

View File

@ -34,16 +34,14 @@ class Logical
* Excel Function: * Excel Function:
* =TRUE() * =TRUE()
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @return boolean True * @return bool True
*/ */
public static function TRUE() public static function true()
{ {
return true; return true;
} }
/** /**
* FALSE * FALSE
* *
@ -52,16 +50,14 @@ class Logical
* Excel Function: * Excel Function:
* =FALSE() * =FALSE()
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @return boolean False * @return bool False
*/ */
public static function FALSE() public static function false()
{ {
return false; return false;
} }
/** /**
* LOGICAL_AND * LOGICAL_AND
* *
@ -78,10 +74,9 @@ class Logical
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return boolean The logical AND of the arguments. * @return bool The logical AND of the arguments.
*/ */
public static function logicalAnd() public static function logicalAnd()
{ {
@ -114,10 +109,10 @@ class Logical
if ($argCount < 0) { if ($argCount < 0) {
return Functions::VALUE(); return Functions::VALUE();
} }
return $returnValue; return $returnValue;
} }
/** /**
* LOGICAL_OR * LOGICAL_OR
* *
@ -134,10 +129,9 @@ class Logical
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return boolean The logical OR of the arguments. * @return bool The logical OR of the arguments.
*/ */
public static function logicalOr() public static function logicalOr()
{ {
@ -170,10 +164,10 @@ class Logical
if ($argCount < 0) { if ($argCount < 0) {
return Functions::VALUE(); return Functions::VALUE();
} }
return $returnValue; return $returnValue;
} }
/** /**
* NOT * NOT
* *
@ -189,10 +183,9 @@ class Logical
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE
* @return boolean The boolean inverse of the argument. * @return bool The boolean inverse of the argument.
*/ */
public static function NOT($logical = false) public static function NOT($logical = false)
{ {
@ -236,7 +229,6 @@ class Logical
* If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
* ReturnIfFalse can be another formula. * ReturnIfFalse can be another formula.
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @param mixed $condition Condition to evaluate * @param mixed $condition Condition to evaluate
* @param mixed $returnIfTrue Value to return when condition is true * @param mixed $returnIfTrue Value to return when condition is true
@ -245,21 +237,19 @@ class Logical
*/ */
public static function statementIf($condition = true, $returnIfTrue = 0, $returnIfFalse = false) public static function statementIf($condition = true, $returnIfTrue = 0, $returnIfFalse = false)
{ {
$condition = (is_null($condition)) ? true : (boolean) Functions::flattenSingleValue($condition); $condition = (is_null($condition)) ? true : (boolean) Functions::flattenSingleValue($condition);
$returnIfTrue = (is_null($returnIfTrue)) ? 0 : Functions::flattenSingleValue($returnIfTrue); $returnIfTrue = (is_null($returnIfTrue)) ? 0 : Functions::flattenSingleValue($returnIfTrue);
$returnIfFalse = (is_null($returnIfFalse)) ? false : Functions::flattenSingleValue($returnIfFalse); $returnIfFalse = (is_null($returnIfFalse)) ? false : Functions::flattenSingleValue($returnIfFalse);
return ($condition) ? $returnIfTrue : $returnIfFalse; return ($condition) ? $returnIfTrue : $returnIfFalse;
} }
/** /**
* IFERROR * IFERROR
* *
* Excel Function: * Excel Function:
* =IFERROR(testValue,errorpart) * =IFERROR(testValue,errorpart)
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @param mixed $testValue Value to check, is also the value returned when no error * @param mixed $testValue Value to check, is also the value returned when no error
* @param mixed $errorpart Value to return when testValue is an error condition * @param mixed $errorpart Value to return when testValue is an error condition

View File

@ -49,10 +49,10 @@ class LookupRef
*/ */
public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '') public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '')
{ {
$row = Functions::flattenSingleValue($row); $row = Functions::flattenSingleValue($row);
$column = Functions::flattenSingleValue($column); $column = Functions::flattenSingleValue($column);
$relativity = Functions::flattenSingleValue($relativity); $relativity = Functions::flattenSingleValue($relativity);
$sheetText = Functions::flattenSingleValue($sheetText); $sheetText = Functions::flattenSingleValue($sheetText);
if (($row < 1) || ($column < 1)) { if (($row < 1) || ($column < 1)) {
return Functions::VALUE(); return Functions::VALUE();
@ -60,32 +60,33 @@ class LookupRef
if ($sheetText > '') { if ($sheetText > '') {
if (strpos($sheetText, ' ') !== false) { if (strpos($sheetText, ' ') !== false) {
$sheetText = "'".$sheetText."'"; $sheetText = "'" . $sheetText . "'";
} }
$sheetText .='!'; $sheetText .= '!';
} }
if ((!is_bool($referenceStyle)) || $referenceStyle) { if ((!is_bool($referenceStyle)) || $referenceStyle) {
$rowRelative = $columnRelative = '$'; $rowRelative = $columnRelative = '$';
$column = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); $column = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1);
if (($relativity == 2) || ($relativity == 4)) { if (($relativity == 2) || ($relativity == 4)) {
$columnRelative = ''; $columnRelative = '';
} }
if (($relativity == 3) || ($relativity == 4)) { if (($relativity == 3) || ($relativity == 4)) {
$rowRelative = ''; $rowRelative = '';
} }
return $sheetText.$columnRelative.$column.$rowRelative.$row;
return $sheetText . $columnRelative . $column . $rowRelative . $row;
} else { } else {
if (($relativity == 2) || ($relativity == 4)) { if (($relativity == 2) || ($relativity == 4)) {
$column = '['.$column.']'; $column = '[' . $column . ']';
} }
if (($relativity == 3) || ($relativity == 4)) { if (($relativity == 3) || ($relativity == 4)) {
$row = '['.$row.']'; $row = '[' . $row . ']';
} }
return $sheetText.'R'.$row.'C'.$column;
return $sheetText . 'R' . $row . 'C' . $column;
} }
} }
/** /**
* COLUMN * COLUMN
* *
@ -98,7 +99,7 @@ class LookupRef
* =COLUMN([cellAddress]) * =COLUMN([cellAddress])
* *
* @param cellAddress A reference to a range of cells for which you want the column numbers * @param cellAddress A reference to a range of cells for which you want the column numbers
* @return integer or array of integer * @return int or array of integer
*/ */
public static function COLUMN($cellAddress = null) public static function COLUMN($cellAddress = null)
{ {
@ -109,6 +110,7 @@ class LookupRef
if (is_array($cellAddress)) { if (is_array($cellAddress)) {
foreach ($cellAddress as $columnKey => $value) { foreach ($cellAddress as $columnKey => $value) {
$columnKey = preg_replace('/[^a-z]/i', '', $columnKey); $columnKey = preg_replace('/[^a-z]/i', '', $columnKey);
return (integer) \PhpSpreadsheet\Cell::columnIndexFromString($columnKey); return (integer) \PhpSpreadsheet\Cell::columnIndexFromString($columnKey);
} }
} else { } else {
@ -119,19 +121,20 @@ class LookupRef
list($startAddress, $endAddress) = explode(':', $cellAddress); list($startAddress, $endAddress) = explode(':', $cellAddress);
$startAddress = preg_replace('/[^a-z]/i', '', $startAddress); $startAddress = preg_replace('/[^a-z]/i', '', $startAddress);
$endAddress = preg_replace('/[^a-z]/i', '', $endAddress); $endAddress = preg_replace('/[^a-z]/i', '', $endAddress);
$returnValue = array(); $returnValue = [];
do { do {
$returnValue[] = (integer) \PhpSpreadsheet\Cell::columnIndexFromString($startAddress); $returnValue[] = (integer) \PhpSpreadsheet\Cell::columnIndexFromString($startAddress);
} while ($startAddress++ != $endAddress); } while ($startAddress++ != $endAddress);
return $returnValue; return $returnValue;
} else { } else {
$cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress); $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress);
return (integer) \PhpSpreadsheet\Cell::columnIndexFromString($cellAddress); return (integer) \PhpSpreadsheet\Cell::columnIndexFromString($cellAddress);
} }
} }
} }
/** /**
* COLUMNS * COLUMNS
* *
@ -141,7 +144,7 @@ class LookupRef
* =COLUMNS(cellAddress) * =COLUMNS(cellAddress)
* *
* @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
* @return integer The number of columns in cellAddress * @return int The number of columns in cellAddress
*/ */
public static function COLUMNS($cellAddress = null) public static function COLUMNS($cellAddress = null)
{ {
@ -162,7 +165,6 @@ class LookupRef
} }
} }
/** /**
* ROW * ROW
* *
@ -175,7 +177,7 @@ class LookupRef
* =ROW([cellAddress]) * =ROW([cellAddress])
* *
* @param cellAddress A reference to a range of cells for which you want the row numbers * @param cellAddress A reference to a range of cells for which you want the row numbers
* @return integer or array of integer * @return int or array of integer
*/ */
public static function ROW($cellAddress = null) public static function ROW($cellAddress = null)
{ {
@ -197,19 +199,20 @@ class LookupRef
list($startAddress, $endAddress) = explode(':', $cellAddress); list($startAddress, $endAddress) = explode(':', $cellAddress);
$startAddress = preg_replace('/[^0-9]/', '', $startAddress); $startAddress = preg_replace('/[^0-9]/', '', $startAddress);
$endAddress = preg_replace('/[^0-9]/', '', $endAddress); $endAddress = preg_replace('/[^0-9]/', '', $endAddress);
$returnValue = array(); $returnValue = [];
do { do {
$returnValue[][] = (integer) $startAddress; $returnValue[][] = (integer) $startAddress;
} while ($startAddress++ != $endAddress); } while ($startAddress++ != $endAddress);
return $returnValue; return $returnValue;
} else { } else {
list($cellAddress) = explode(':', $cellAddress); list($cellAddress) = explode(':', $cellAddress);
return (integer) preg_replace('/[^0-9]/', '', $cellAddress); return (integer) preg_replace('/[^0-9]/', '', $cellAddress);
} }
} }
} }
/** /**
* ROWS * ROWS
* *
@ -219,7 +222,7 @@ class LookupRef
* =ROWS(cellAddress) * =ROWS(cellAddress)
* *
* @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
* @return integer The number of rows in cellAddress * @return int The number of rows in cellAddress
*/ */
public static function ROWS($cellAddress = null) public static function ROWS($cellAddress = null)
{ {
@ -240,14 +243,12 @@ class LookupRef
} }
} }
/** /**
* HYPERLINK * HYPERLINK
* *
* Excel Function: * Excel Function:
* =HYPERLINK(linkURL,displayName) * =HYPERLINK(linkURL,displayName)
* *
* @access public
* @category Logical Functions * @category Logical Functions
* @param string $linkURL Value to check, is also the value returned when no error * @param string $linkURL Value to check, is also the value returned when no error
* @param string $displayName Value to return when testValue is an error condition * @param string $displayName Value to return when testValue is an error condition
@ -259,7 +260,7 @@ class LookupRef
$args = func_get_args(); $args = func_get_args();
$pCell = array_pop($args); $pCell = array_pop($args);
$linkURL = (is_null($linkURL)) ? '' : Functions::flattenSingleValue($linkURL); $linkURL = (is_null($linkURL)) ? '' : Functions::flattenSingleValue($linkURL);
$displayName = (is_null($displayName)) ? '' : Functions::flattenSingleValue($displayName); $displayName = (is_null($displayName)) ? '' : Functions::flattenSingleValue($displayName);
if ((!is_object($pCell)) || (trim($linkURL) == '')) { if ((!is_object($pCell)) || (trim($linkURL) == '')) {
@ -276,7 +277,6 @@ class LookupRef
return $displayName; return $displayName;
} }
/** /**
* INDIRECT * INDIRECT
* *
@ -293,11 +293,10 @@ class LookupRef
* @return mixed The cells referenced by cellAddress * @return mixed The cells referenced by cellAddress
* *
* @todo Support for the optional a1 parameter introduced in Excel 2010 * @todo Support for the optional a1 parameter introduced in Excel 2010
*
*/ */
public static function INDIRECT($cellAddress = null, \PhpSpreadsheet\Cell $pCell = null) public static function INDIRECT($cellAddress = null, \PhpSpreadsheet\Cell $pCell = null)
{ {
$cellAddress = Functions::flattenSingleValue($cellAddress); $cellAddress = Functions::flattenSingleValue($cellAddress);
if (is_null($cellAddress) || $cellAddress === '') { if (is_null($cellAddress) || $cellAddress === '') {
return Functions::REF(); return Functions::REF();
} }
@ -308,9 +307,9 @@ class LookupRef
list($cellAddress1, $cellAddress2) = explode(':', $cellAddress); list($cellAddress1, $cellAddress2) = explode(':', $cellAddress);
} }
if ((!preg_match('/^'.\PhpSpreadsheet\Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) || if ((!preg_match('/^' . \PhpSpreadsheet\Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress1, $matches)) ||
((!is_null($cellAddress2)) && (!preg_match('/^'.\PhpSpreadsheet\Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) { ((!is_null($cellAddress2)) && (!preg_match('/^' . \PhpSpreadsheet\Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress2, $matches)))) {
if (!preg_match('/^'.\PhpSpreadsheet\Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) { if (!preg_match('/^' . \PhpSpreadsheet\Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $cellAddress1, $matches)) {
return Functions::REF(); return Functions::REF();
} }
@ -336,7 +335,6 @@ class LookupRef
return \PhpSpreadsheet\Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); return \PhpSpreadsheet\Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
} }
/** /**
* OFFSET * OFFSET
* *
@ -364,10 +362,10 @@ class LookupRef
*/ */
public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null) public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null)
{ {
$rows = Functions::flattenSingleValue($rows); $rows = Functions::flattenSingleValue($rows);
$columns = Functions::flattenSingleValue($columns); $columns = Functions::flattenSingleValue($columns);
$height = Functions::flattenSingleValue($height); $height = Functions::flattenSingleValue($height);
$width = Functions::flattenSingleValue($width); $width = Functions::flattenSingleValue($width);
if ($cellAddress == null) { if ($cellAddress == null) {
return 0; return 0;
} }
@ -379,12 +377,12 @@ class LookupRef
} }
$sheetName = null; $sheetName = null;
if (strpos($cellAddress, "!")) { if (strpos($cellAddress, '!')) {
list($sheetName, $cellAddress) = explode("!", $cellAddress); list($sheetName, $cellAddress) = explode('!', $cellAddress);
$sheetName = trim($sheetName, "'"); $sheetName = trim($sheetName, "'");
} }
if (strpos($cellAddress, ":")) { if (strpos($cellAddress, ':')) {
list($startCell, $endCell) = explode(":", $cellAddress); list($startCell, $endCell) = explode(':', $cellAddress);
} else { } else {
$startCell = $endCell = $cellAddress; $startCell = $endCell = $cellAddress;
} }
@ -417,9 +415,9 @@ class LookupRef
} }
$endCellColumn = \PhpSpreadsheet\Cell::stringFromColumnIndex($endCellColumn); $endCellColumn = \PhpSpreadsheet\Cell::stringFromColumnIndex($endCellColumn);
$cellAddress = $startCellColumn.$startCellRow; $cellAddress = $startCellColumn . $startCellRow;
if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
$cellAddress .= ':'.$endCellColumn.$endCellRow; $cellAddress .= ':' . $endCellColumn . $endCellRow;
} }
if ($sheetName !== null) { if ($sheetName !== null) {
@ -431,7 +429,6 @@ class LookupRef
return \PhpSpreadsheet\Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); return \PhpSpreadsheet\Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
} }
/** /**
* CHOOSE * CHOOSE
* *
@ -476,7 +473,6 @@ class LookupRef
} }
} }
/** /**
* MATCH * MATCH
* *
@ -488,13 +484,13 @@ class LookupRef
* @param lookup_value The value that you want to match in lookup_array * @param lookup_value The value that you want to match in lookup_array
* @param lookup_array The range of cells being searched * @param lookup_array The range of cells being searched
* @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered. * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
* @return integer The relative position of the found item * @return int The relative position of the found item
*/ */
public static function MATCH($lookup_value, $lookup_array, $match_type = 1) public static function MATCH($lookup_value, $lookup_array, $match_type = 1)
{ {
$lookup_array = Functions::flattenArray($lookup_array); $lookup_array = Functions::flattenArray($lookup_array);
$lookup_value = Functions::flattenSingleValue($lookup_value); $lookup_value = Functions::flattenSingleValue($lookup_value);
$match_type = (is_null($match_type)) ? 1 : (int) Functions::flattenSingleValue($match_type); $match_type = (is_null($match_type)) ? 1 : (int) Functions::flattenSingleValue($match_type);
// MATCH is not case sensitive // MATCH is not case sensitive
$lookup_value = strtolower($lookup_value); $lookup_value = strtolower($lookup_value);
@ -526,7 +522,7 @@ class LookupRef
$lookup_array[$i] = strtolower($lookupArrayValue); $lookup_array[$i] = strtolower($lookupArrayValue);
} }
if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) { if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
$lookup_array = array_slice($lookup_array, 0, $i-1); $lookup_array = array_slice($lookup_array, 0, $i - 1);
} }
} }
@ -554,7 +550,7 @@ class LookupRef
break; break;
} else { } else {
// the previous cell was the match // the previous cell was the match
return $keySet[$i-1]+1; return $keySet[$i - 1] + 1;
} }
} elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) { } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
$i = array_search($i, $keySet); $i = array_search($i, $keySet);
@ -564,7 +560,7 @@ class LookupRef
break; break;
} else { } else {
// the previous cell was the match // the previous cell was the match
return $keySet[$i-1]+1; return $keySet[$i - 1] + 1;
} }
} }
} }
@ -573,7 +569,6 @@ class LookupRef
return Functions::NA(); return Functions::NA();
} }
/** /**
* INDEX * INDEX
* *
@ -607,7 +602,7 @@ class LookupRef
return $arrayValues; return $arrayValues;
} }
$rowNum = $rowKeys[--$rowNum]; $rowNum = $rowKeys[--$rowNum];
$returnArray = array(); $returnArray = [];
foreach ($arrayValues as $arrayColumn) { foreach ($arrayValues as $arrayColumn) {
if (is_array($arrayColumn)) { if (is_array($arrayColumn)) {
if (isset($arrayColumn[$rowNum])) { if (isset($arrayColumn[$rowNum])) {
@ -619,6 +614,7 @@ class LookupRef
return $arrayValues[$rowNum]; return $arrayValues[$rowNum];
} }
} }
return $returnArray; return $returnArray;
} }
$columnNum = $columnKeys[--$columnNum]; $columnNum = $columnKeys[--$columnNum];
@ -632,7 +628,6 @@ class LookupRef
return $arrayValues[$rowNum][$columnNum]; return $arrayValues[$rowNum][$columnNum];
} }
/** /**
* TRANSPOSE * TRANSPOSE
* *
@ -643,9 +638,9 @@ class LookupRef
*/ */
public static function TRANSPOSE($matrixData) public static function TRANSPOSE($matrixData)
{ {
$returnMatrix = array(); $returnMatrix = [];
if (!is_array($matrixData)) { if (!is_array($matrixData)) {
$matrixData = array(array($matrixData)); $matrixData = [[$matrixData]];
} }
$column = 0; $column = 0;
@ -657,10 +652,10 @@ class LookupRef
} }
++$column; ++$column;
} }
return $returnMatrix; return $returnMatrix;
} }
private static function vlookupSort($a, $b) private static function vlookupSort($a, $b)
{ {
reset($a); reset($a);
@ -668,10 +663,10 @@ class LookupRef
if (($aLower = strtolower($a[$firstColumn])) == ($bLower = strtolower($b[$firstColumn]))) { if (($aLower = strtolower($a[$firstColumn])) == ($bLower = strtolower($b[$firstColumn]))) {
return 0; return 0;
} }
return ($aLower < $bLower) ? -1 : 1; return ($aLower < $bLower) ? -1 : 1;
} }
/** /**
* VLOOKUP * VLOOKUP
* The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number. * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
@ -683,8 +678,8 @@ class LookupRef
*/ */
public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
{ {
$lookup_value = Functions::flattenSingleValue($lookup_value); $lookup_value = Functions::flattenSingleValue($lookup_value);
$index_number = Functions::flattenSingleValue($index_number); $index_number = Functions::flattenSingleValue($index_number);
$not_exact_match = Functions::flattenSingleValue($not_exact_match); $not_exact_match = Functions::flattenSingleValue($not_exact_match);
// index_number must be greater than or equal to 1 // index_number must be greater than or equal to 1
@ -708,7 +703,7 @@ class LookupRef
} }
if (!$not_exact_match) { if (!$not_exact_match) {
uasort($lookup_array, array('self', 'vlookupSort')); uasort($lookup_array, ['self', 'vlookupSort']);
} }
$rowNumber = $rowValue = false; $rowNumber = $rowValue = false;
@ -738,7 +733,6 @@ class LookupRef
return Functions::NA(); return Functions::NA();
} }
/** /**
* HLOOKUP * HLOOKUP
* The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number. * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number.
@ -750,9 +744,9 @@ class LookupRef
*/ */
public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
{ {
$lookup_value = Functions::flattenSingleValue($lookup_value); $lookup_value = Functions::flattenSingleValue($lookup_value);
$index_number = Functions::flattenSingleValue($index_number); $index_number = Functions::flattenSingleValue($index_number);
$not_exact_match = Functions::flattenSingleValue($not_exact_match); $not_exact_match = Functions::flattenSingleValue($not_exact_match);
// index_number must be greater than or equal to 1 // index_number must be greater than or equal to 1
if ($index_number < 1) { if ($index_number < 1) {
@ -769,7 +763,7 @@ class LookupRef
return Functions::REF(); return Functions::REF();
} else { } else {
$columnKeys = array_keys($lookup_array[$firstRow]); $columnKeys = array_keys($lookup_array[$firstRow]);
$firstkey = $f[0] - 1; $firstkey = $f[0] - 1;
$returnColumn = $firstkey + $index_number; $returnColumn = $firstkey + $index_number;
$firstColumn = array_shift($f); $firstColumn = array_shift($f);
} }
@ -801,7 +795,6 @@ class LookupRef
return Functions::NA(); return Functions::NA();
} }
/** /**
* LOOKUP * LOOKUP
* The LOOKUP function searches for value either from a one-row or one-column range or from an array. * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
@ -851,7 +844,7 @@ class LookupRef
if (is_array($value)) { if (is_array($value)) {
$k = array_keys($value); $k = array_keys($value);
$key1 = $key2 = array_shift($k); $key1 = $key2 = array_shift($k);
$key2++; ++$key2;
$dataValue1 = $value[$key1]; $dataValue1 = $value[$key1];
} else { } else {
$key1 = 0; $key1 = 0;
@ -862,7 +855,7 @@ class LookupRef
if (is_array($dataValue2)) { if (is_array($dataValue2)) {
$dataValue2 = array_shift($dataValue2); $dataValue2 = array_shift($dataValue2);
} }
$value = array($key1 => $dataValue1, $key2 => $dataValue2); $value = [$key1 => $dataValue1, $key2 => $dataValue2];
} }
unset($value); unset($value);
} }

View File

@ -33,7 +33,7 @@ class MathTrig
{ {
$startVal = floor(sqrt($value)); $startVal = floor(sqrt($value));
$factorArray = array(); $factorArray = [];
for ($i = $startVal; $i > 1; --$i) { for ($i = $startVal; $i > 1; --$i) {
if (($value % $i) == 0) { if (($value % $i) == 0) {
$factorArray = array_merge($factorArray, self::factors($value / $i)); $factorArray = array_merge($factorArray, self::factors($value / $i));
@ -45,19 +45,18 @@ class MathTrig
} }
if (!empty($factorArray)) { if (!empty($factorArray)) {
rsort($factorArray); rsort($factorArray);
return $factorArray; return $factorArray;
} else { } else {
return array((integer) $value); return [(integer) $value];
} }
} }
private static function romanCut($num, $n) private static function romanCut($num, $n)
{ {
return ($num - ($num % $n ) ) / $n; return ($num - ($num % $n)) / $n;
} }
/** /**
* ATAN2 * ATAN2
* *
@ -74,7 +73,6 @@ class MathTrig
* Excel Function: * Excel Function:
* ATAN2(xCoordinate,yCoordinate) * ATAN2(xCoordinate,yCoordinate)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $xCoordinate The x-coordinate of the point. * @param float $xCoordinate The x-coordinate of the point.
* @param float $yCoordinate The y-coordinate of the point. * @param float $yCoordinate The y-coordinate of the point.
@ -89,9 +87,9 @@ class MathTrig
$yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0; $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0;
if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) && if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) { ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) {
$xCoordinate = (float) $xCoordinate; $xCoordinate = (float) $xCoordinate;
$yCoordinate = (float) $yCoordinate; $yCoordinate = (float) $yCoordinate;
if (($xCoordinate == 0) && ($yCoordinate == 0)) { if (($xCoordinate == 0) && ($yCoordinate == 0)) {
return Functions::DIV0(); return Functions::DIV0();
@ -99,10 +97,10 @@ class MathTrig
return atan2($yCoordinate, $xCoordinate); return atan2($yCoordinate, $xCoordinate);
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* CEILING * CEILING
* *
@ -114,7 +112,6 @@ class MathTrig
* Excel Function: * Excel Function:
* CEILING(number[,significance]) * CEILING(number[,significance])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $number The number you want to round. * @param float $number The number you want to round.
* @param float $significance The multiple to which you want to round. * @param float $significance The multiple to which you want to round.
@ -122,7 +119,7 @@ class MathTrig
*/ */
public static function CEILING($number, $significance = null) public static function CEILING($number, $significance = null)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
$significance = Functions::flattenSingleValue($significance); $significance = Functions::flattenSingleValue($significance);
if ((is_null($significance)) && if ((is_null($significance)) &&
@ -131,7 +128,7 @@ class MathTrig
} }
if ((is_numeric($number)) && (is_numeric($significance))) { if ((is_numeric($number)) && (is_numeric($significance))) {
if (($number == 0.0 ) || ($significance == 0.0)) { if (($number == 0.0) || ($significance == 0.0)) {
return 0.0; return 0.0;
} elseif (self::SIGN($number) == self::SIGN($significance)) { } elseif (self::SIGN($number) == self::SIGN($significance)) {
return ceil($number / $significance) * $significance; return ceil($number / $significance) * $significance;
@ -139,10 +136,10 @@ class MathTrig
return Functions::NAN(); return Functions::NAN();
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* COMBIN * COMBIN
* *
@ -152,7 +149,6 @@ class MathTrig
* Excel Function: * Excel Function:
* COMBIN(numObjs,numInSet) * COMBIN(numObjs,numInSet)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param int $numObjs Number of different objects * @param int $numObjs Number of different objects
* @param int $numInSet Number of objects in each combination * @param int $numInSet Number of objects in each combination
@ -160,8 +156,8 @@ class MathTrig
*/ */
public static function COMBIN($numObjs, $numInSet) public static function COMBIN($numObjs, $numInSet)
{ {
$numObjs = Functions::flattenSingleValue($numObjs); $numObjs = Functions::flattenSingleValue($numObjs);
$numInSet = Functions::flattenSingleValue($numInSet); $numInSet = Functions::flattenSingleValue($numInSet);
if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
if ($numObjs < $numInSet) { if ($numObjs < $numInSet) {
@ -169,12 +165,13 @@ class MathTrig
} elseif ($numInSet < 0) { } elseif ($numInSet < 0) {
return Functions::NAN(); return Functions::NAN();
} }
return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet); return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* EVEN * EVEN
* *
@ -187,7 +184,6 @@ class MathTrig
* Excel Function: * Excel Function:
* EVEN(number) * EVEN(number)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $number Number to round * @param float $number Number to round
* @return int Rounded Number * @return int Rounded Number
@ -204,12 +200,13 @@ class MathTrig
if (is_numeric($number)) { if (is_numeric($number)) {
$significance = 2 * self::SIGN($number); $significance = 2 * self::SIGN($number);
return (int) self::CEILING($number, $significance); return (int) self::CEILING($number, $significance);
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* FACT * FACT
* *
@ -219,14 +216,13 @@ class MathTrig
* Excel Function: * Excel Function:
* FACT(factVal) * FACT(factVal)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $factVal Factorial Value * @param float $factVal Factorial Value
* @return int Factorial * @return int Factorial
*/ */
public static function FACT($factVal) public static function FACT($factVal)
{ {
$factVal = Functions::flattenSingleValue($factVal); $factVal = Functions::flattenSingleValue($factVal);
if (is_numeric($factVal)) { if (is_numeric($factVal)) {
if ($factVal < 0) { if ($factVal < 0) {
@ -243,12 +239,13 @@ class MathTrig
while ($factLoop > 1) { while ($factLoop > 1) {
$factorial *= $factLoop--; $factorial *= $factLoop--;
} }
return $factorial ;
return $factorial;
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* FACTDOUBLE * FACTDOUBLE
* *
@ -257,17 +254,16 @@ class MathTrig
* Excel Function: * Excel Function:
* FACTDOUBLE(factVal) * FACTDOUBLE(factVal)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $factVal Factorial Value * @param float $factVal Factorial Value
* @return int Double Factorial * @return int Double Factorial
*/ */
public static function FACTDOUBLE($factVal) public static function FACTDOUBLE($factVal)
{ {
$factLoop = Functions::flattenSingleValue($factVal); $factLoop = Functions::flattenSingleValue($factVal);
if (is_numeric($factLoop)) { if (is_numeric($factLoop)) {
$factLoop = floor($factLoop); $factLoop = floor($factLoop);
if ($factVal < 0) { if ($factVal < 0) {
return Functions::NAN(); return Functions::NAN();
} }
@ -276,12 +272,13 @@ class MathTrig
$factorial *= $factLoop--; $factorial *= $factLoop--;
--$factLoop; --$factLoop;
} }
return $factorial ;
return $factorial;
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* FLOOR * FLOOR
* *
@ -290,7 +287,6 @@ class MathTrig
* Excel Function: * Excel Function:
* FLOOR(number[,significance]) * FLOOR(number[,significance])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $number Number to round * @param float $number Number to round
* @param float $significance Significance * @param float $significance Significance
@ -298,12 +294,12 @@ class MathTrig
*/ */
public static function FLOOR($number, $significance = null) public static function FLOOR($number, $significance = null)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
$significance = Functions::flattenSingleValue($significance); $significance = Functions::flattenSingleValue($significance);
if ((is_null($significance)) && if ((is_null($significance)) &&
(Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)) { (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)) {
$significance = $number/abs($number); $significance = $number / abs($number);
} }
if ((is_numeric($number)) && (is_numeric($significance))) { if ((is_numeric($number)) && (is_numeric($significance))) {
@ -321,7 +317,6 @@ class MathTrig
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* GCD * GCD
* *
@ -332,15 +327,14 @@ class MathTrig
* Excel Function: * Excel Function:
* GCD(number1[,number2[, ...]]) * GCD(number1[,number2[, ...]])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return integer Greatest Common Divisor * @return int Greatest Common Divisor
*/ */
public static function GCD() public static function GCD()
{ {
$returnValue = 1; $returnValue = 1;
$allValuesFactors = array(); $allValuesFactors = [];
// Loop through arguments // Loop through arguments
foreach (Functions::flattenArray(func_get_args()) as $value) { foreach (Functions::flattenArray(func_get_args()) as $value) {
if (!is_numeric($value)) { if (!is_numeric($value)) {
@ -360,7 +354,7 @@ class MathTrig
} }
$mergedArray = $allValuesFactors[0]; $mergedArray = $allValuesFactors[0];
for ($i=1; $i < $allValuesCount; ++$i) { for ($i = 1; $i < $allValuesCount; ++$i) {
$mergedArray = array_intersect_key($mergedArray, $allValuesFactors[$i]); $mergedArray = array_intersect_key($mergedArray, $allValuesFactors[$i]);
} }
$mergedArrayValues = count($mergedArray); $mergedArrayValues = count($mergedArray);
@ -382,6 +376,7 @@ class MathTrig
foreach ($mergedArray as $key => $value) { foreach ($mergedArray as $key => $value) {
$returnValue *= pow($key, $value); $returnValue *= pow($key, $value);
} }
return $returnValue; return $returnValue;
} else { } else {
$keys = array_keys($mergedArray); $keys = array_keys($mergedArray);
@ -394,11 +389,11 @@ class MathTrig
} }
} }
} }
return pow($key, $value); return pow($key, $value);
} }
} }
/** /**
* INT * INT
* *
@ -407,14 +402,13 @@ class MathTrig
* Excel Function: * Excel Function:
* INT(number) * INT(number)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $number Number to cast to an integer * @param float $number Number to cast to an integer
* @return integer Integer value * @return int Integer value
*/ */
public static function INT($number) public static function INT($number)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
if (is_null($number)) { if (is_null($number)) {
return 0; return 0;
@ -424,10 +418,10 @@ class MathTrig
if (is_numeric($number)) { if (is_numeric($number)) {
return (int) floor($number); return (int) floor($number);
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* LCM * LCM
* *
@ -439,7 +433,6 @@ class MathTrig
* Excel Function: * Excel Function:
* LCM(number1[,number2[, ...]]) * LCM(number1[,number2[, ...]])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return int Lowest Common Multiplier * @return int Lowest Common Multiplier
@ -447,7 +440,7 @@ class MathTrig
public static function LCM() public static function LCM()
{ {
$returnValue = 1; $returnValue = 1;
$allPoweredFactors = array(); $allPoweredFactors = [];
// Loop through arguments // Loop through arguments
foreach (Functions::flattenArray(func_get_args()) as $value) { foreach (Functions::flattenArray(func_get_args()) as $value) {
if (!is_numeric($value)) { if (!is_numeric($value)) {
@ -460,7 +453,7 @@ class MathTrig
} }
$myFactors = self::factors(floor($value)); $myFactors = self::factors(floor($value));
$myCountedFactors = array_count_values($myFactors); $myCountedFactors = array_count_values($myFactors);
$myPoweredFactors = array(); $myPoweredFactors = [];
foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) {
$myPoweredFactors[$myCountedFactor] = pow($myCountedFactor, $myCountedPower); $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor, $myCountedPower);
} }
@ -477,10 +470,10 @@ class MathTrig
foreach ($allPoweredFactors as $allPoweredFactor) { foreach ($allPoweredFactors as $allPoweredFactor) {
$returnValue *= (integer) $allPoweredFactor; $returnValue *= (integer) $allPoweredFactor;
} }
return $returnValue; return $returnValue;
} }
/** /**
* LOG_BASE * LOG_BASE
* *
@ -489,7 +482,6 @@ class MathTrig
* Excel Function: * Excel Function:
* LOG(number[,base]) * LOG(number[,base])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param float $number The positive real number for which you want the logarithm * @param float $number The positive real number for which you want the logarithm
* @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10. * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
@ -497,8 +489,8 @@ class MathTrig
*/ */
public static function logBase($number = null, $base = 10) public static function logBase($number = null, $base = 10)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
$base = (is_null($base)) ? 10 : (float) Functions::flattenSingleValue($base); $base = (is_null($base)) ? 10 : (float) Functions::flattenSingleValue($base);
if ((!is_numeric($base)) || (!is_numeric($number))) { if ((!is_numeric($base)) || (!is_numeric($number))) {
return Functions::VALUE(); return Functions::VALUE();
@ -506,10 +498,10 @@ class MathTrig
if (($base <= 0) || ($number <= 0)) { if (($base <= 0) || ($number <= 0)) {
return Functions::NAN(); return Functions::NAN();
} }
return log($number, $base); return log($number, $base);
} }
/** /**
* MDETERM * MDETERM
* *
@ -518,22 +510,21 @@ class MathTrig
* Excel Function: * Excel Function:
* MDETERM(array) * MDETERM(array)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param array $matrixValues A matrix of values * @param array $matrixValues A matrix of values
* @return float * @return float
*/ */
public static function MDETERM($matrixValues) public static function MDETERM($matrixValues)
{ {
$matrixData = array(); $matrixData = [];
if (!is_array($matrixValues)) { if (!is_array($matrixValues)) {
$matrixValues = array(array($matrixValues)); $matrixValues = [[$matrixValues]];
} }
$row = $maxColumn = 0; $row = $maxColumn = 0;
foreach ($matrixValues as $matrixRow) { foreach ($matrixValues as $matrixRow) {
if (!is_array($matrixRow)) { if (!is_array($matrixRow)) {
$matrixRow = array($matrixRow); $matrixRow = [$matrixRow];
} }
$column = 0; $column = 0;
foreach ($matrixRow as $matrixCell) { foreach ($matrixRow as $matrixCell) {
@ -554,13 +545,13 @@ class MathTrig
try { try {
$matrix = new \PhpSpreadsheet\Shared\JAMA\Matrix($matrixData); $matrix = new \PhpSpreadsheet\Shared\JAMA\Matrix($matrixData);
return $matrix->det(); return $matrix->det();
} catch (\PhpSpreadsheet\Exception $ex) { } catch (\PhpSpreadsheet\Exception $ex) {
return Functions::VALUE(); return Functions::VALUE();
} }
} }
/** /**
* MINVERSE * MINVERSE
* *
@ -569,22 +560,21 @@ class MathTrig
* Excel Function: * Excel Function:
* MINVERSE(array) * MINVERSE(array)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param array $matrixValues A matrix of values * @param array $matrixValues A matrix of values
* @return array * @return array
*/ */
public static function MINVERSE($matrixValues) public static function MINVERSE($matrixValues)
{ {
$matrixData = array(); $matrixData = [];
if (!is_array($matrixValues)) { if (!is_array($matrixValues)) {
$matrixValues = array(array($matrixValues)); $matrixValues = [[$matrixValues]];
} }
$row = $maxColumn = 0; $row = $maxColumn = 0;
foreach ($matrixValues as $matrixRow) { foreach ($matrixValues as $matrixRow) {
if (!is_array($matrixRow)) { if (!is_array($matrixRow)) {
$matrixRow = array($matrixRow); $matrixRow = [$matrixRow];
} }
$column = 0; $column = 0;
foreach ($matrixRow as $matrixCell) { foreach ($matrixRow as $matrixCell) {
@ -607,13 +597,13 @@ class MathTrig
try { try {
$matrix = new \PhpSpreadsheet\Shared\JAMA\Matrix($matrixData); $matrix = new \PhpSpreadsheet\Shared\JAMA\Matrix($matrixData);
return $matrix->inverse()->getArray(); return $matrix->inverse()->getArray();
} catch (\PhpSpreadsheet\Exception $ex) { } catch (\PhpSpreadsheet\Exception $ex) {
return Functions::VALUE(); return Functions::VALUE();
} }
} }
/** /**
* MMULT * MMULT
* *
@ -623,19 +613,19 @@ class MathTrig
*/ */
public static function MMULT($matrixData1, $matrixData2) public static function MMULT($matrixData1, $matrixData2)
{ {
$matrixAData = $matrixBData = array(); $matrixAData = $matrixBData = [];
if (!is_array($matrixData1)) { if (!is_array($matrixData1)) {
$matrixData1 = array(array($matrixData1)); $matrixData1 = [[$matrixData1]];
} }
if (!is_array($matrixData2)) { if (!is_array($matrixData2)) {
$matrixData2 = array(array($matrixData2)); $matrixData2 = [[$matrixData2]];
} }
try { try {
$rowA = 0; $rowA = 0;
foreach ($matrixData1 as $matrixRow) { foreach ($matrixData1 as $matrixRow) {
if (!is_array($matrixRow)) { if (!is_array($matrixRow)) {
$matrixRow = array($matrixRow); $matrixRow = [$matrixRow];
} }
$columnA = 0; $columnA = 0;
foreach ($matrixRow as $matrixCell) { foreach ($matrixRow as $matrixCell) {
@ -651,7 +641,7 @@ class MathTrig
$rowB = 0; $rowB = 0;
foreach ($matrixData2 as $matrixRow) { foreach ($matrixData2 as $matrixRow) {
if (!is_array($matrixRow)) { if (!is_array($matrixRow)) {
$matrixRow = array($matrixRow); $matrixRow = [$matrixRow];
} }
$columnB = 0; $columnB = 0;
foreach ($matrixRow as $matrixCell) { foreach ($matrixRow as $matrixCell) {
@ -672,11 +662,11 @@ class MathTrig
return $matrixA->times($matrixB)->getArray(); return $matrixA->times($matrixB)->getArray();
} catch (\PhpSpreadsheet\Exception $ex) { } catch (\PhpSpreadsheet\Exception $ex) {
var_dump($ex->getMessage()); var_dump($ex->getMessage());
return Functions::VALUE(); return Functions::VALUE();
} }
} }
/** /**
* MOD * MOD
* *
@ -700,7 +690,6 @@ class MathTrig
return fmod($a, $b); return fmod($a, $b);
} }
/** /**
* MROUND * MROUND
* *
@ -712,7 +701,7 @@ class MathTrig
*/ */
public static function MROUND($number, $multiple) public static function MROUND($number, $multiple)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
$multiple = Functions::flattenSingleValue($multiple); $multiple = Functions::flattenSingleValue($multiple);
if ((is_numeric($number)) && (is_numeric($multiple))) { if ((is_numeric($number)) && (is_numeric($multiple))) {
@ -721,14 +710,16 @@ class MathTrig
} }
if ((self::SIGN($number)) == (self::SIGN($multiple))) { if ((self::SIGN($number)) == (self::SIGN($multiple))) {
$multiplier = 1 / $multiple; $multiplier = 1 / $multiple;
return round($number * $multiplier) / $multiplier; return round($number * $multiplier) / $multiplier;
} }
return Functions::NAN(); return Functions::NAN();
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* MULTINOMIAL * MULTINOMIAL
* *
@ -758,12 +749,13 @@ class MathTrig
// Return // Return
if ($summer > 0) { if ($summer > 0) {
$summer = self::FACT($summer); $summer = self::FACT($summer);
return $summer / $divisor; return $summer / $divisor;
} }
return 0; return 0;
} }
/** /**
* ODD * ODD
* *
@ -793,10 +785,10 @@ class MathTrig
return (int) $result; return (int) $result;
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* POWER * POWER
* *
@ -808,8 +800,8 @@ class MathTrig
*/ */
public static function POWER($x = 0, $y = 2) public static function POWER($x = 0, $y = 2)
{ {
$x = Functions::flattenSingleValue($x); $x = Functions::flattenSingleValue($x);
$y = Functions::flattenSingleValue($y); $y = Functions::flattenSingleValue($y);
// Validate parameters // Validate parameters
if ($x == 0.0 && $y == 0.0) { if ($x == 0.0 && $y == 0.0) {
@ -820,10 +812,10 @@ class MathTrig
// Return // Return
$result = pow($x, $y); $result = pow($x, $y);
return (!is_nan($result) && !is_infinite($result)) ? $result : Functions::NAN(); return (!is_nan($result) && !is_infinite($result)) ? $result : Functions::NAN();
} }
/** /**
* PRODUCT * PRODUCT
* *
@ -832,7 +824,6 @@ class MathTrig
* Excel Function: * Excel Function:
* PRODUCT(value1[,value2[, ...]]) * PRODUCT(value1[,value2[, ...]])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return float * @return float
@ -858,10 +849,10 @@ class MathTrig
if (is_null($returnValue)) { if (is_null($returnValue)) {
return 0; return 0;
} }
return $returnValue; return $returnValue;
} }
/** /**
* QUOTIENT * QUOTIENT
* *
@ -871,7 +862,6 @@ class MathTrig
* Excel Function: * Excel Function:
* QUOTIENT(value1[,value2[, ...]]) * QUOTIENT(value1[,value2[, ...]])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return float * @return float
@ -901,7 +891,6 @@ class MathTrig
return intval($returnValue); return intval($returnValue);
} }
/** /**
* RAND * RAND
* *
@ -921,11 +910,10 @@ class MathTrig
} }
} }
public static function ROMAN($aValue, $style = 0) public static function ROMAN($aValue, $style = 0)
{ {
$aValue = Functions::flattenSingleValue($aValue); $aValue = Functions::flattenSingleValue($aValue);
$style = (is_null($style)) ? 0 : (integer) Functions::flattenSingleValue($style); $style = (is_null($style)) ? 0 : (integer) Functions::flattenSingleValue($style);
if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) { if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
return Functions::VALUE(); return Functions::VALUE();
} }
@ -934,10 +922,10 @@ class MathTrig
return ''; return '';
} }
$mill = array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM'); $mill = ['', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM'];
$cent = array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'); $cent = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'];
$tens = array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'); $tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'];
$ones = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'); $ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
$roman = ''; $roman = '';
while ($aValue > 5999) { while ($aValue > 5999) {
@ -951,10 +939,9 @@ class MathTrig
$t = self::romanCut($aValue, 10); $t = self::romanCut($aValue, 10);
$aValue %= 10; $aValue %= 10;
return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue]; return $roman . $mill[$m] . $cent[$c] . $tens[$t] . $ones[$aValue];
} }
/** /**
* ROUNDUP * ROUNDUP
* *
@ -966,8 +953,8 @@ class MathTrig
*/ */
public static function ROUNDUP($number, $digits) public static function ROUNDUP($number, $digits)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
$digits = Functions::flattenSingleValue($digits); $digits = Functions::flattenSingleValue($digits);
if ((is_numeric($number)) && (is_numeric($digits))) { if ((is_numeric($number)) && (is_numeric($digits))) {
$significance = pow(10, (int) $digits); $significance = pow(10, (int) $digits);
@ -977,10 +964,10 @@ class MathTrig
return ceil($number * $significance) / $significance; return ceil($number * $significance) / $significance;
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* ROUNDDOWN * ROUNDDOWN
* *
@ -992,8 +979,8 @@ class MathTrig
*/ */
public static function ROUNDDOWN($number, $digits) public static function ROUNDDOWN($number, $digits)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
$digits = Functions::flattenSingleValue($digits); $digits = Functions::flattenSingleValue($digits);
if ((is_numeric($number)) && (is_numeric($digits))) { if ((is_numeric($number)) && (is_numeric($digits))) {
$significance = pow(10, (int) $digits); $significance = pow(10, (int) $digits);
@ -1003,10 +990,10 @@ class MathTrig
return floor($number * $significance) / $significance; return floor($number * $significance) / $significance;
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* SERIESSUM * SERIESSUM
* *
@ -1040,12 +1027,13 @@ class MathTrig
return Functions::VALUE(); return Functions::VALUE();
} }
} }
return $returnValue; return $returnValue;
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* SIGN * SIGN
* *
@ -1057,7 +1045,7 @@ class MathTrig
*/ */
public static function SIGN($number) public static function SIGN($number)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
if (is_bool($number)) { if (is_bool($number)) {
return (int) $number; return (int) $number;
@ -1066,12 +1054,13 @@ class MathTrig
if ($number == 0.0) { if ($number == 0.0) {
return 0; return 0;
} }
return $number / abs($number); return $number / abs($number);
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* SQRTPI * SQRTPI
* *
@ -1082,18 +1071,19 @@ class MathTrig
*/ */
public static function SQRTPI($number) public static function SQRTPI($number)
{ {
$number = Functions::flattenSingleValue($number); $number = Functions::flattenSingleValue($number);
if (is_numeric($number)) { if (is_numeric($number)) {
if ($number < 0) { if ($number < 0) {
return Functions::NAN(); return Functions::NAN();
} }
return sqrt($number * M_PI) ;
return sqrt($number * M_PI);
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* SUBTOTAL * SUBTOTAL
* *
@ -1137,10 +1127,10 @@ class MathTrig
return Statistical::VARP($aArgs); return Statistical::VARP($aArgs);
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* SUM * SUM
* *
@ -1149,7 +1139,6 @@ class MathTrig
* Excel Function: * Excel Function:
* SUM(value1[,value2[, ...]]) * SUM(value1[,value2[, ...]])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return float * @return float
@ -1169,7 +1158,6 @@ class MathTrig
return $returnValue; return $returnValue;
} }
/** /**
* SUMIF * SUMIF
* *
@ -1178,13 +1166,12 @@ class MathTrig
* Excel Function: * Excel Function:
* SUMIF(value1[,value2[, ...]],condition) * SUMIF(value1[,value2[, ...]],condition)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @param string $condition The criteria that defines which cells will be summed. * @param string $condition The criteria that defines which cells will be summed.
* @return float * @return float
*/ */
public static function SUMIF($aArgs, $condition, $sumArgs = array()) public static function SUMIF($aArgs, $condition, $sumArgs = [])
{ {
$returnValue = 0; $returnValue = 0;
@ -1201,7 +1188,7 @@ class MathTrig
$arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg));
} }
$testCondition = '='.$arg.$condition; $testCondition = '=' . $arg . $condition;
if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
// Is it a value within our criteria // Is it a value within our criteria
$returnValue += $sumArgs[$key]; $returnValue += $sumArgs[$key];
@ -1211,7 +1198,7 @@ class MathTrig
return $returnValue; return $returnValue;
} }
/** /**
* SUMIFS * SUMIFS
* *
* Counts the number of cells that contain numbers within the list of arguments * Counts the number of cells that contain numbers within the list of arguments
@ -1219,7 +1206,6 @@ class MathTrig
* Excel Function: * Excel Function:
* SUMIFS(value1[,value2[, ...]],condition) * SUMIFS(value1[,value2[, ...]],condition)
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @param string $condition The criteria that defines which cells will be summed. * @param string $condition The criteria that defines which cells will be summed.
@ -1248,7 +1234,7 @@ class MathTrig
if (!is_numeric($arg)) { if (!is_numeric($arg)) {
$arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg));
} }
$testCondition = '='.$arg.$condition; $testCondition = '=' . $arg . $condition;
if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
// Is it a value within our criteria // Is it a value within our criteria
$returnValue += $sumArgs[$key]; $returnValue += $sumArgs[$key];
@ -1266,7 +1252,6 @@ class MathTrig
* Excel Function: * Excel Function:
* SUMPRODUCT(value1[,value2[, ...]]) * SUMPRODUCT(value1[,value2[, ...]])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return float * @return float
@ -1278,7 +1263,7 @@ class MathTrig
$wrkArray = Functions::flattenArray(array_shift($arrayList)); $wrkArray = Functions::flattenArray(array_shift($arrayList));
$wrkCellCount = count($wrkArray); $wrkCellCount = count($wrkArray);
for ($i=0; $i< $wrkCellCount; ++$i) { for ($i = 0; $i < $wrkCellCount; ++$i) {
if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) {
$wrkArray[$i] = 0; $wrkArray[$i] = 0;
} }
@ -1302,7 +1287,6 @@ class MathTrig
return array_sum($wrkArray); return array_sum($wrkArray);
} }
/** /**
* SUMSQ * SUMSQ
* *
@ -1311,7 +1295,6 @@ class MathTrig
* Excel Function: * Excel Function:
* SUMSQ(value1[,value2[, ...]]) * SUMSQ(value1[,value2[, ...]])
* *
* @access public
* @category Mathematical and Trigonometric Functions * @category Mathematical and Trigonometric Functions
* @param mixed $arg,... Data values * @param mixed $arg,... Data values
* @return float * @return float
@ -1331,7 +1314,6 @@ class MathTrig
return $returnValue; return $returnValue;
} }
/** /**
* SUMX2MY2 * SUMX2MY2
* *
@ -1356,7 +1338,6 @@ class MathTrig
return $result; return $result;
} }
/** /**
* SUMX2PY2 * SUMX2PY2
* *
@ -1381,7 +1362,6 @@ class MathTrig
return $result; return $result;
} }
/** /**
* SUMXMY2 * SUMXMY2
* *
@ -1406,7 +1386,6 @@ class MathTrig
return $result; return $result;
} }
/** /**
* TRUNC * TRUNC
* *
@ -1418,8 +1397,8 @@ class MathTrig
*/ */
public static function TRUNC($value = 0, $digits = 0) public static function TRUNC($value = 0, $digits = 0)
{ {
$value = Functions::flattenSingleValue($value); $value = Functions::flattenSingleValue($value);
$digits = Functions::flattenSingleValue($digits); $digits = Functions::flattenSingleValue($digits);
// Validate parameters // Validate parameters
if ((!is_numeric($value)) || (!is_numeric($digits))) { if ((!is_numeric($value)) || (!is_numeric($digits))) {
@ -1430,7 +1409,7 @@ class MathTrig
// Truncate // Truncate
$adjust = pow(10, $digits); $adjust = pow(10, $digits);
if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust), '0') < $adjust/10)) { if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust), '0') < $adjust / 10)) {
return $value; return $value;
} }

File diff suppressed because it is too large Load Diff

View File

@ -30,22 +30,23 @@ class TextData
private static function unicodeToOrd($c) private static function unicodeToOrd($c)
{ {
if (ord($c{0}) >=0 && ord($c{0}) <= 127) { if (ord($c{0}) >= 0 && ord($c{0}) <= 127) {
return ord($c{0}); return ord($c{0});
} elseif (ord($c{0}) >= 192 && ord($c{0}) <= 223) { } elseif (ord($c{0}) >= 192 && ord($c{0}) <= 223) {
return (ord($c{0})-192)*64 + (ord($c{1})-128); return (ord($c{0}) - 192) * 64 + (ord($c{1}) - 128);
} elseif (ord($c{0}) >= 224 && ord($c{0}) <= 239) { } elseif (ord($c{0}) >= 224 && ord($c{0}) <= 239) {
return (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128); return (ord($c{0}) - 224) * 4096 + (ord($c{1}) - 128) * 64 + (ord($c{2}) - 128);
} elseif (ord($c{0}) >= 240 && ord($c{0}) <= 247) { } elseif (ord($c{0}) >= 240 && ord($c{0}) <= 247) {
return (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128); return (ord($c{0}) - 240) * 262144 + (ord($c{1}) - 128) * 4096 + (ord($c{2}) - 128) * 64 + (ord($c{3}) - 128);
} elseif (ord($c{0}) >= 248 && ord($c{0}) <= 251) { } elseif (ord($c{0}) >= 248 && ord($c{0}) <= 251) {
return (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128); return (ord($c{0}) - 248) * 16777216 + (ord($c{1}) - 128) * 262144 + (ord($c{2}) - 128) * 4096 + (ord($c{3}) - 128) * 64 + (ord($c{4}) - 128);
} elseif (ord($c{0}) >= 252 && ord($c{0}) <= 253) { } elseif (ord($c{0}) >= 252 && ord($c{0}) <= 253) {
return (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128); return (ord($c{0}) - 252) * 1073741824 + (ord($c{1}) - 128) * 16777216 + (ord($c{2}) - 128) * 262144 + (ord($c{3}) - 128) * 4096 + (ord($c{4}) - 128) * 64 + (ord($c{5}) - 128);
} elseif (ord($c{0}) >= 254 && ord($c{0}) <= 255) { } elseif (ord($c{0}) >= 254 && ord($c{0}) <= 255) {
// error // error
return Functions::VALUE(); return Functions::VALUE();
} }
return 0; return 0;
} }
@ -64,13 +65,12 @@ class TextData
} }
if (function_exists('mb_convert_encoding')) { if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding('&#'.intval($character).';', 'UTF-8', 'HTML-ENTITIES'); return mb_convert_encoding('&#' . intval($character) . ';', 'UTF-8', 'HTML-ENTITIES');
} else { } else {
return chr(intval($character)); return chr(intval($character));
} }
} }
/** /**
* TRIMNONPRINTABLE * TRIMNONPRINTABLE
* *
@ -79,7 +79,7 @@ class TextData
*/ */
public static function TRIMNONPRINTABLE($stringValue = '') public static function TRIMNONPRINTABLE($stringValue = '')
{ {
$stringValue = Functions::flattenSingleValue($stringValue); $stringValue = Functions::flattenSingleValue($stringValue);
if (is_bool($stringValue)) { if (is_bool($stringValue)) {
return ($stringValue) ? \PhpSpreadsheet\Calculation::getTRUE() : \PhpSpreadsheet\Calculation::getFALSE(); return ($stringValue) ? \PhpSpreadsheet\Calculation::getTRUE() : \PhpSpreadsheet\Calculation::getFALSE();
@ -92,10 +92,10 @@ class TextData
if (is_string($stringValue) || is_numeric($stringValue)) { if (is_string($stringValue) || is_numeric($stringValue)) {
return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F")); return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F"));
} }
return null; return null;
} }
/** /**
* TRIMSPACES * TRIMSPACES
* *
@ -112,10 +112,10 @@ class TextData
if (is_string($stringValue) || is_numeric($stringValue)) { if (is_string($stringValue) || is_numeric($stringValue)) {
return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' '); return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' ');
} }
return null; return null;
} }
/** /**
* ASCIICODE * ASCIICODE
* *
@ -127,7 +127,7 @@ class TextData
if (($characters === null) || ($characters === '')) { if (($characters === null) || ($characters === '')) {
return Functions::VALUE(); return Functions::VALUE();
} }
$characters = Functions::flattenSingleValue($characters); $characters = Functions::flattenSingleValue($characters);
if (is_bool($characters)) { if (is_bool($characters)) {
if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
$characters = (int) $characters; $characters = (int) $characters;
@ -141,16 +141,17 @@ class TextData
if (mb_strlen($characters, 'UTF-8') > 1) { if (mb_strlen($characters, 'UTF-8') > 1) {
$character = mb_substr($characters, 0, 1, 'UTF-8'); $character = mb_substr($characters, 0, 1, 'UTF-8');
} }
return self::unicodeToOrd($character); return self::unicodeToOrd($character);
} else { } else {
if (strlen($characters) > 0) { if (strlen($characters) > 0) {
$character = substr($characters, 0, 1); $character = substr($characters, 0, 1);
} }
return ord($character); return ord($character);
} }
} }
/** /**
* CONCATENATE * CONCATENATE
* *
@ -176,7 +177,6 @@ class TextData
return $returnValue; return $returnValue;
} }
/** /**
* DOLLAR * DOLLAR
* *
@ -191,8 +191,8 @@ class TextData
*/ */
public static function DOLLAR($value = 0, $decimals = 2) public static function DOLLAR($value = 0, $decimals = 2)
{ {
$value = Functions::flattenSingleValue($value); $value = Functions::flattenSingleValue($value);
$decimals = is_null($decimals) ? 0 : Functions::flattenSingleValue($decimals); $decimals = is_null($decimals) ? 0 : Functions::flattenSingleValue($decimals);
// Validate parameters // Validate parameters
if (!is_numeric($value) || !is_numeric($decimals)) { if (!is_numeric($value) || !is_numeric($decimals)) {
@ -206,7 +206,7 @@ class TextData
} else { } else {
$round = pow(10, abs($decimals)); $round = pow(10, abs($decimals));
if ($value < 0) { if ($value < 0) {
$round = 0-$round; $round = 0 - $round;
} }
$value = MathTrig::MROUND($value, $round); $value = MathTrig::MROUND($value, $round);
} }
@ -214,7 +214,6 @@ class TextData
return \PhpSpreadsheet\Style\NumberFormat::toFormattedString($value, $mask); return \PhpSpreadsheet\Style\NumberFormat::toFormattedString($value, $mask);
} }
/** /**
* SEARCHSENSITIVE * SEARCHSENSITIVE
* *
@ -225,9 +224,9 @@ class TextData
*/ */
public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1) public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1)
{ {
$needle = Functions::flattenSingleValue($needle); $needle = Functions::flattenSingleValue($needle);
$haystack = Functions::flattenSingleValue($haystack); $haystack = Functions::flattenSingleValue($haystack);
$offset = Functions::flattenSingleValue($offset); $offset = Functions::flattenSingleValue($offset);
if (!is_bool($needle)) { if (!is_bool($needle)) {
if (is_bool($haystack)) { if (is_bool($haystack)) {
@ -248,10 +247,10 @@ class TextData
} }
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* SEARCHINSENSITIVE * SEARCHINSENSITIVE
* *
@ -262,9 +261,9 @@ class TextData
*/ */
public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1) public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1)
{ {
$needle = Functions::flattenSingleValue($needle); $needle = Functions::flattenSingleValue($needle);
$haystack = Functions::flattenSingleValue($haystack); $haystack = Functions::flattenSingleValue($haystack);
$offset = Functions::flattenSingleValue($offset); $offset = Functions::flattenSingleValue($offset);
if (!is_bool($needle)) { if (!is_bool($needle)) {
if (is_bool($haystack)) { if (is_bool($haystack)) {
@ -285,22 +284,22 @@ class TextData
} }
} }
} }
return Functions::VALUE(); return Functions::VALUE();
} }
/** /**
* FIXEDFORMAT * FIXEDFORMAT
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @param integer $decimals * @param int $decimals
* @param boolean $no_commas * @param bool $no_commas
* @return boolean * @return bool
*/ */
public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false) public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false)
{ {
$value = Functions::flattenSingleValue($value); $value = Functions::flattenSingleValue($value);
$decimals = Functions::flattenSingleValue($decimals); $decimals = Functions::flattenSingleValue($decimals);
$no_commas = Functions::flattenSingleValue($no_commas); $no_commas = Functions::flattenSingleValue($no_commas);
// Validate parameters // Validate parameters
@ -320,7 +319,6 @@ class TextData
return (string) $valueResult; return (string) $valueResult;
} }
/** /**
* LEFT * LEFT
* *
@ -348,7 +346,6 @@ class TextData
} }
} }
/** /**
* MID * MID
* *
@ -381,7 +378,6 @@ class TextData
} }
} }
/** /**
* RIGHT * RIGHT
* *
@ -409,7 +405,6 @@ class TextData
} }
} }
/** /**
* STRINGLENGTH * STRINGLENGTH
* *
@ -431,7 +426,6 @@ class TextData
} }
} }
/** /**
* LOWERCASE * LOWERCASE
* *
@ -451,7 +445,6 @@ class TextData
return \PhpSpreadsheet\Shared\StringHelper::strToLower($mixedCaseString); return \PhpSpreadsheet\Shared\StringHelper::strToLower($mixedCaseString);
} }
/** /**
* UPPERCASE * UPPERCASE
* *
@ -471,7 +464,6 @@ class TextData
return \PhpSpreadsheet\Shared\StringHelper::strToUpper($mixedCaseString); return \PhpSpreadsheet\Shared\StringHelper::strToUpper($mixedCaseString);
} }
/** /**
* PROPERCASE * PROPERCASE
* *
@ -491,7 +483,6 @@ class TextData
return \PhpSpreadsheet\Shared\StringHelper::strToTitle($mixedCaseString); return \PhpSpreadsheet\Shared\StringHelper::strToTitle($mixedCaseString);
} }
/** /**
* REPLACE * REPLACE
* *
@ -504,31 +495,30 @@ class TextData
public static function REPLACE($oldText, $start, $chars, $newText) public static function REPLACE($oldText, $start, $chars, $newText)
{ {
$oldText = Functions::flattenSingleValue($oldText); $oldText = Functions::flattenSingleValue($oldText);
$start = Functions::flattenSingleValue($start); $start = Functions::flattenSingleValue($start);
$chars = Functions::flattenSingleValue($chars); $chars = Functions::flattenSingleValue($chars);
$newText = Functions::flattenSingleValue($newText); $newText = Functions::flattenSingleValue($newText);
$left = self::LEFT($oldText, $start-1); $left = self::LEFT($oldText, $start - 1);
$right = self::RIGHT($oldText, self::STRINGLENGTH($oldText)-($start+$chars)+1); $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText) - ($start + $chars) + 1);
return $left.$newText.$right; return $left . $newText . $right;
} }
/** /**
* SUBSTITUTE * SUBSTITUTE
* *
* @param string $text Value * @param string $text Value
* @param string $fromText From Value * @param string $fromText From Value
* @param string $toText To Value * @param string $toText To Value
* @param integer $instance Instance Number * @param int $instance Instance Number
* @return string * @return string
*/ */
public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0)
{ {
$text = Functions::flattenSingleValue($text); $text = Functions::flattenSingleValue($text);
$fromText = Functions::flattenSingleValue($fromText); $fromText = Functions::flattenSingleValue($fromText);
$toText = Functions::flattenSingleValue($toText); $toText = Functions::flattenSingleValue($toText);
$instance = floor(Functions::flattenSingleValue($instance)); $instance = floor(Functions::flattenSingleValue($instance));
if ($instance == 0) { if ($instance == 0) {
@ -541,9 +531,9 @@ class TextData
$pos = -1; $pos = -1;
while ($instance > 0) { while ($instance > 0) {
if (function_exists('mb_strpos')) { if (function_exists('mb_strpos')) {
$pos = mb_strpos($text, $fromText, $pos+1, 'UTF-8'); $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8');
} else { } else {
$pos = strpos($text, $fromText, $pos+1); $pos = strpos($text, $fromText, $pos + 1);
} }
if ($pos === false) { if ($pos === false) {
break; break;
@ -562,12 +552,11 @@ class TextData
return $text; return $text;
} }
/** /**
* RETURNSTRING * RETURNSTRING
* *
* @param mixed $testValue Value to check * @param mixed $testValue Value to check
* @return boolean * @return bool
*/ */
public static function RETURNSTRING($testValue = '') public static function RETURNSTRING($testValue = '')
{ {
@ -576,20 +565,20 @@ class TextData
if (is_string($testValue)) { if (is_string($testValue)) {
return $testValue; return $testValue;
} }
return null; return null;
} }
/** /**
* TEXTFORMAT * TEXTFORMAT
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @param string $format Format mask to use * @param string $format Format mask to use
* @return boolean * @return bool
*/ */
public static function TEXTFORMAT($value, $format) public static function TEXTFORMAT($value, $format)
{ {
$value = Functions::flattenSingleValue($value); $value = Functions::flattenSingleValue($value);
$format = Functions::flattenSingleValue($format); $format = Functions::flattenSingleValue($format);
if ((is_string($value)) && (!is_numeric($value)) && \PhpSpreadsheet\Shared\Date::isDateTimeFormatCode($format)) { if ((is_string($value)) && (!is_numeric($value)) && \PhpSpreadsheet\Shared\Date::isDateTimeFormatCode($format)) {
@ -603,7 +592,7 @@ class TextData
* VALUE * VALUE
* *
* @param mixed $value Value to check * @param mixed $value Value to check
* @return boolean * @return bool
*/ */
public static function VALUE($value = '') public static function VALUE($value = '')
{ {
@ -626,18 +615,21 @@ class TextData
$timeValue = DateTime::TIMEVALUE($value); $timeValue = DateTime::TIMEVALUE($value);
if ($timeValue !== Functions::VALUE()) { if ($timeValue !== Functions::VALUE()) {
Functions::setReturnDateType($dateSetting); Functions::setReturnDateType($dateSetting);
return $timeValue; return $timeValue;
} }
} }
$dateValue = DateTime::DATEVALUE($value); $dateValue = DateTime::DATEVALUE($value);
if ($dateValue !== Functions::VALUE()) { if ($dateValue !== Functions::VALUE()) {
Functions::setReturnDateType($dateSetting); Functions::setReturnDateType($dateSetting);
return $dateValue; return $dateValue;
} }
Functions::setReturnDateType($dateSetting); Functions::setReturnDateType($dateSetting);
return Functions::VALUE(); return Functions::VALUE();
} }
return (float) $value; return (float) $value;
} }
} }

View File

@ -31,19 +31,19 @@ class Stack
* *
* @var mixed[] * @var mixed[]
*/ */
private $stack = array(); private $stack = [];
/** /**
* Count of entries in the parser stack * Count of entries in the parser stack
* *
* @var integer * @var int
*/ */
private $count = 0; private $count = 0;
/** /**
* Return the number of entries on the stack * Return the number of entries on the stack
* *
* @return integer * @return int
*/ */
public function count() public function count()
{ {
@ -59,11 +59,11 @@ class Stack
*/ */
public function push($type, $value, $reference = null) public function push($type, $value, $reference = null)
{ {
$this->stack[$this->count++] = array( $this->stack[$this->count++] = [
'type' => $type, 'type' => $type,
'value' => $value, 'value' => $value,
'reference' => $reference 'reference' => $reference,
); ];
if ($type == 'Function') { if ($type == 'Function') {
$localeFunction = \PhpSpreadsheet\Calculation::localeFunc($value); $localeFunction = \PhpSpreadsheet\Calculation::localeFunc($value);
if ($localeFunction != $value) { if ($localeFunction != $value) {
@ -82,13 +82,14 @@ class Stack
if ($this->count > 0) { if ($this->count > 0) {
return $this->stack[--$this->count]; return $this->stack[--$this->count];
} }
return null; return null;
} }
/** /**
* Return an entry from the stack without removing it * Return an entry from the stack without removing it
* *
* @param integer $n number indicating how far back in the stack we want to look * @param int $n number indicating how far back in the stack we want to look
* @return mixed * @return mixed
*/ */
public function last($n = 1) public function last($n = 1)
@ -96,6 +97,7 @@ class Stack
if ($this->count - $n < 0) { if ($this->count - $n < 0) {
return null; return null;
} }
return $this->stack[$this->count - $n]; return $this->stack[$this->count - $n];
} }
@ -104,7 +106,7 @@ class Stack
*/ */
public function clear() public function clear()
{ {
$this->stack = array(); $this->stack = [];
$this->count = 0; $this->count = 0;
} }
} }

View File

@ -82,15 +82,11 @@ class Cell
/** /**
* 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
**/ **/
public function notifyCacheController() public function notifyCacheController()
{ {
@ -109,7 +105,6 @@ class Cell
$this->parent = $parent; $this->parent = $parent;
} }
/** /**
* Create a new Cell * Create a new Cell
* *
@ -133,7 +128,7 @@ class Cell
} }
$this->dataType = $pDataType; $this->dataType = $pDataType;
} elseif (!self::getValueBinder()->bindValue($this, $pValue)) { } elseif (!self::getValueBinder()->bindValue($this, $pValue)) {
throw new Exception("Value could not be bound to cell."); throw new Exception('Value could not be bound to cell.');
} }
} }
@ -197,14 +192,15 @@ class Cell
* 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 Cell
* @throws Exception * @throws Exception
* @return Cell
*/ */
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 Exception('Value could not be bound to cell.');
} }
return $this; return $this;
} }
@ -213,8 +209,8 @@ class Cell
* *
* @param mixed $pValue Value * @param mixed $pValue Value
* @param string $pDataType Explicit data type * @param string $pDataType Explicit data type
* @return Cell
* @throws Exception * @throws Exception
* @return Cell
*/ */
public function setValueExplicit($pValue = null, $pDataType = Cell\DataType::TYPE_STRING) public function setValueExplicit($pValue = null, $pDataType = Cell\DataType::TYPE_STRING)
{ {
@ -260,16 +256,16 @@ class Cell
* *
* @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
* *
* @param boolean $resetLog Whether the calculation engine logger should be reset or not * @param bool $resetLog Whether the calculation engine logger should be reset or not
* @return mixed
* @throws Exception * @throws Exception
* @return mixed
*/ */
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().PHP_EOL; //echo 'Cell '.$this->getCoordinate().' value is a '.$this->dataType.' with a value of '.$this->getValue().PHP_EOL;
if ($this->dataType == Cell\DataType::TYPE_FORMULA) { if ($this->dataType == Cell\DataType::TYPE_FORMULA) {
try { try {
//echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL; //echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL;
$result = Calculation::getInstance( $result = Calculation::getInstance(
$this->getWorksheet()->getParent() $this->getWorksheet()->getParent()
)->calculateCellValue($this, $resetLog); )->calculateCellValue($this, $resetLog);
@ -282,24 +278,24 @@ class Cell
} }
} catch (Exception $ex) { } catch (Exception $ex) {
if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
//echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; //echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
return $this->calculatedValue; // Fallback for calculations referencing external files. return $this->calculatedValue; // Fallback for calculations referencing external files.
} }
//echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL; //echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL;
$result = '#N/A'; $result = '#N/A';
throw new Calculation\Exception( throw new Calculation\Exception(
$this->getWorksheet()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage() $this->getWorksheet()->getTitle() . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage()
); );
} }
if ($result === '#Not Yet Implemented') { if ($result === '#Not Yet Implemented') {
//echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; //echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
return $this->calculatedValue; // Fallback if calculation engine does not support the formula. return $this->calculatedValue; // Fallback if calculation engine does not support the formula.
} }
//echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL; //echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL;
return $result; return $result;
} elseif ($this->value instanceof RichText) { } elseif ($this->value instanceof RichText) {
// echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->value.'<br />'; // echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->value.'<br />';
return $this->value->getPlainText(); return $this->value->getPlainText();
} }
// 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 />';
@ -365,7 +361,7 @@ class Cell
/** /**
* Identify if the cell contains a formula * Identify if the cell contains a formula
* *
* @return boolean * @return bool
*/ */
public function isFormula() public function isFormula()
{ {
@ -375,8 +371,8 @@ class Cell
/** /**
* Does this cell contain Data validation rules? * Does this cell contain Data validation rules?
* *
* @return boolean
* @throws Exception * @throws Exception
* @return bool
*/ */
public function hasDataValidation() public function hasDataValidation()
{ {
@ -390,8 +386,8 @@ class Cell
/** /**
* Get Data validation rules * Get Data validation rules
* *
* @return Cell\DataValidation
* @throws Exception * @throws Exception
* @return Cell\DataValidation
*/ */
public function getDataValidation() public function getDataValidation()
{ {
@ -406,8 +402,8 @@ class Cell
* Set Data validation rules * Set Data validation rules
* *
* @param Cell\DataValidation $pDataValidation * @param Cell\DataValidation $pDataValidation
* @return Cell
* @throws Exception * @throws Exception
* @return Cell
*/ */
public function setDataValidation(Cell\DataValidation $pDataValidation = null) public function setDataValidation(Cell\DataValidation $pDataValidation = null)
{ {
@ -423,8 +419,8 @@ class Cell
/** /**
* Does this cell contain a Hyperlink? * Does this cell contain a Hyperlink?
* *
* @return boolean
* @throws Exception * @throws Exception
* @return bool
*/ */
public function hasHyperlink() public function hasHyperlink()
{ {
@ -438,8 +434,8 @@ class Cell
/** /**
* Get Hyperlink * Get Hyperlink
* *
* @return Cell\Hyperlink
* @throws Exception * @throws Exception
* @return Cell\Hyperlink
*/ */
public function getHyperlink() public function getHyperlink()
{ {
@ -454,8 +450,8 @@ class Cell
* Set Hyperlink * Set Hyperlink
* *
* @param Cell\Hyperlink $pHyperlink * @param Cell\Hyperlink $pHyperlink
* @return Cell
* @throws Exception * @throws Exception
* @return Cell
*/ */
public function setHyperlink(Cell\Hyperlink $pHyperlink = null) public function setHyperlink(Cell\Hyperlink $pHyperlink = null)
{ {
@ -491,7 +487,7 @@ class Cell
/** /**
* Is this cell in a merge range * Is this cell in a merge range
* *
* @return boolean * @return bool
*/ */
public function isInMergeRange() public function isInMergeRange()
{ {
@ -501,17 +497,18 @@ class Cell
/** /**
* Is this cell the master (top left cell) in a merge range (that holds the actual data value) * Is this cell the master (top left cell) in a merge range (that holds the actual data value)
* *
* @return boolean * @return bool
*/ */
public function isMergeRangeValueCell() public function isMergeRangeValueCell()
{ {
if ($mergeRange = $this->getMergeRange()) { if ($mergeRange = $this->getMergeRange()) {
$mergeRange = Cell::splitRange($mergeRange); $mergeRange = self::splitRange($mergeRange);
list($startCell) = $mergeRange[0]; list($startCell) = $mergeRange[0];
if ($this->getCoordinate() === $startCell) { if ($this->getCoordinate() === $startCell) {
return true; return true;
} }
} }
return false; return false;
} }
@ -527,6 +524,7 @@ class Cell
return $mergeRange; return $mergeRange;
} }
} }
return false; return false;
} }
@ -557,7 +555,7 @@ class 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 bool
*/ */
public function isInRange($pRange = 'A1:A1') public function isInRange($pRange = 'A1:A1')
{ {
@ -565,32 +563,31 @@ class Cell
// Translate properties // Translate properties
$myColumn = self::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
return (($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) &&
($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow) ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow);
);
} }
/** /**
* Coordinate from string * Coordinate from string
* *
* @param string $pCoordinateString * @param string $pCoordinateString
* @return array Array containing column and row (indexes 0 and 1)
* @throws Exception * @throws Exception
* @return array Array containing column and row (indexes 0 and 1)
*/ */
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 [$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 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 Exception('Cell coordinate can not be zero-length string');
} }
throw new Exception('Invalid cell coordinate '.$pCoordinateString); throw new Exception('Invalid cell coordinate ' . $pCoordinateString);
} }
/** /**
@ -598,8 +595,8 @@ class Cell
* *
* @param string $pCoordinateString e.g. 'A' or '1' or 'A1' * @param string $pCoordinateString e.g. 'A' or '1' or 'A1'
* Note that this value can be a row or column reference as well as a cell reference * Note that this value can be a row or column reference as well as a cell reference
* @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
* @throws Exception * @throws Exception
* @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
*/ */
public static function absoluteReference($pCoordinateString = 'A1') public static function absoluteReference($pCoordinateString = 'A1')
{ {
@ -620,6 +617,7 @@ class Cell
} elseif (ctype_alpha($pCoordinateString)) { } elseif (ctype_alpha($pCoordinateString)) {
return $worksheet . '$' . strtoupper($pCoordinateString); return $worksheet . '$' . strtoupper($pCoordinateString);
} }
return $worksheet . self::absoluteCoordinate($pCoordinateString); return $worksheet . self::absoluteCoordinate($pCoordinateString);
} }
@ -630,8 +628,8 @@ class Cell
* 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'
* @throws Exception * @throws Exception
* @return string Absolute coordinate e.g. '$A$1'
*/ */
public static function absoluteCoordinate($pCoordinateString = 'A1') public static function absoluteCoordinate($pCoordinateString = 'A1')
{ {
@ -650,6 +648,7 @@ class Cell
list($column, $row) = self::coordinateFromString($pCoordinateString); list($column, $row) = self::coordinateFromString($pCoordinateString);
$column = ltrim($column, '$'); $column = ltrim($column, '$');
$row = ltrim($row, '$'); $row = ltrim($row, '$');
return $worksheet . '$' . $column . '$' . $row; return $worksheet . '$' . $column . '$' . $row;
} }
@ -676,6 +675,7 @@ class Cell
for ($i = 0; $i < $counter; ++$i) { for ($i = 0; $i < $counter; ++$i) {
$exploded[$i] = explode(':', $exploded[$i]); $exploded[$i] = explode(':', $exploded[$i]);
} }
return $exploded; return $exploded;
} }
@ -683,8 +683,8 @@ class 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
* @throws Exception * @throws Exception
* @return string String representation of $pRange
*/ */
public static function buildRange($pRange) public static function buildRange($pRange)
{ {
@ -694,7 +694,7 @@ class Cell
} }
// Build range // Build range
$imploded = array(); $imploded = [];
$counter = count($pRange); $counter = count($pRange);
for ($i = 0; $i < $counter; ++$i) { for ($i = 0; $i < $counter; ++$i) {
$pRange[$i] = implode(':', $pRange[$i]); $pRange[$i] = implode(':', $pRange[$i]);
@ -730,13 +730,13 @@ class Cell
// Calculate range outer borders // Calculate range outer borders
$rangeStart = self::coordinateFromString($rangeA); $rangeStart = self::coordinateFromString($rangeA);
$rangeEnd = self::coordinateFromString($rangeB); $rangeEnd = self::coordinateFromString($rangeB);
// Translate column into index // Translate column into index
$rangeStart[0] = self::columnIndexFromString($rangeStart[0]); $rangeStart[0] = self::columnIndexFromString($rangeStart[0]);
$rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]);
return array($rangeStart, $rangeEnd); return [$rangeStart, $rangeEnd];
} }
/** /**
@ -750,7 +750,7 @@ class Cell
// Calculate range outer borders // Calculate range outer borders
list($rangeStart, $rangeEnd) = self::rangeBoundaries($pRange); list($rangeStart, $rangeEnd) = self::rangeBoundaries($pRange);
return array( ($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1) ); return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)];
} }
/** /**
@ -777,7 +777,7 @@ class Cell
list($rangeA, $rangeB) = explode(':', $pRange); list($rangeA, $rangeB) = explode(':', $pRange);
} }
return array( self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)); return [self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)];
} }
/** /**
@ -791,7 +791,7 @@ class Cell
// Using a lookup cache adds a slight memory overhead, but boosts speed // Using a lookup cache adds a slight memory overhead, but boosts speed
// caching using a static within the method is faster than a class static, // caching using a static within the method is faster than a class static,
// though it's additional memory overhead // though it's additional memory overhead
static $_indexCache = array(); static $_indexCache = [];
if (isset($_indexCache[$pString])) { if (isset($_indexCache[$pString])) {
return $_indexCache[$pString]; return $_indexCache[$pString];
@ -799,28 +799,31 @@ class Cell
// It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord() // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord()
// and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant
// memory overhead either // memory overhead either
static $_columnLookup = array( static $_columnLookup = [
'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13,
'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26,
'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13,
'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26,
); ];
// We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString
// for improved performance // for improved performance
if (isset($pString{0})) { if (isset($pString{0})) {
if (!isset($pString{1})) { if (!isset($pString{1})) {
$_indexCache[$pString] = $_columnLookup[$pString]; $_indexCache[$pString] = $_columnLookup[$pString];
return $_indexCache[$pString]; return $_indexCache[$pString];
} elseif (!isset($pString{2})) { } elseif (!isset($pString{2})) {
$_indexCache[$pString] = $_columnLookup[$pString{0}] * 26 + $_columnLookup[$pString{1}]; $_indexCache[$pString] = $_columnLookup[$pString{0}] * 26 + $_columnLookup[$pString{1}];
return $_indexCache[$pString]; return $_indexCache[$pString];
} elseif (!isset($pString{3})) { } elseif (!isset($pString{3})) {
$_indexCache[$pString] = $_columnLookup[$pString{0}] * 676 + $_columnLookup[$pString{1}] * 26 + $_columnLookup[$pString{2}]; $_indexCache[$pString] = $_columnLookup[$pString{0}] * 676 + $_columnLookup[$pString{1}] * 26 + $_columnLookup[$pString{2}];
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 Exception('Column string index can not be ' . ((isset($pString{0})) ? 'longer than 3 characters' : 'empty'));
} }
/** /**
@ -834,7 +837,7 @@ class Cell
// Using a lookup cache adds a slight memory overhead, but boosts speed // Using a lookup cache adds a slight memory overhead, but boosts speed
// caching using a static within the method is faster than a class static, // caching using a static within the method is faster than a class static,
// though it's additional memory overhead // though it's additional memory overhead
static $_indexCache = array(); static $_indexCache = [];
if (!isset($_indexCache[$pColumnIndex])) { if (!isset($_indexCache[$pColumnIndex])) {
// Determine column string // Determine column string
@ -849,6 +852,7 @@ class Cell
chr(65 + $pColumnIndex % 26); chr(65 + $pColumnIndex % 26);
} }
} }
return $_indexCache[$pColumnIndex]; return $_indexCache[$pColumnIndex];
} }
@ -861,7 +865,7 @@ class Cell
public static function extractAllCellReferencesInRange($pRange = 'A1') public static function extractAllCellReferencesInRange($pRange = 'A1')
{ {
// Returnvalue // Returnvalue
$returnValue = array(); $returnValue = [];
// Explode spaces // Explode spaces
$cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange))); $cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange)));
@ -882,7 +886,7 @@ class Cell
} }
// Range... // Range...
list($rangeStart, $rangeEnd) = $range; list($rangeStart, $rangeEnd) = $range;
sscanf($rangeStart, '%[A-Z]%d', $startCol, $startRow); sscanf($rangeStart, '%[A-Z]%d', $startCol, $startRow);
sscanf($rangeEnd, '%[A-Z]%d', $endCol, $endRow); sscanf($rangeEnd, '%[A-Z]%d', $endCol, $endRow);
++$endCol; ++$endCol;
@ -894,7 +898,7 @@ class Cell
// Loop cells // Loop cells
while ($currentCol != $endCol) { while ($currentCol != $endCol) {
while ($currentRow <= $endRow) { while ($currentRow <= $endRow) {
$returnValue[] = $currentCol.$currentRow; $returnValue[] = $currentCol . $currentRow;
++$currentRow; ++$currentRow;
} }
++$currentCol; ++$currentCol;
@ -904,7 +908,7 @@ class Cell
} }
// Sort the result by column and row // Sort the result by column and row
$sortKeys = array(); $sortKeys = [];
foreach (array_unique($returnValue) as $coord) { foreach (array_unique($returnValue) as $coord) {
sscanf($coord, '%[A-Z]%d', $column, $row); sscanf($coord, '%[A-Z]%d', $column, $row);
$sortKeys[sprintf('%3s%09d', $column, $row)] = $coord; $sortKeys[sprintf('%3s%09d', $column, $row)] = $coord;
@ -958,7 +962,7 @@ class Cell
public static function setValueBinder(Cell\IValueBinder $binder = null) public static function setValueBinder(Cell\IValueBinder $binder = null)
{ {
if ($binder === null) { if ($binder === null) {
throw new Exception("A \\PhpSpreadsheet\\Cell\\IValueBinder is required for PhpSpreadsheet to function correctly."); throw new Exception('A \\PhpSpreadsheet\\Cell\\IValueBinder is required for PhpSpreadsheet to function correctly.');
} }
self::$valueBinder = $binder; self::$valueBinder = $binder;
@ -1008,6 +1012,7 @@ class Cell
public function setFormulaAttributes($pAttributes) public function setFormulaAttributes($pAttributes)
{ {
$this->formulaAttributes = $pAttributes; $this->formulaAttributes = $pAttributes;
return $this; return $this;
} }

View File

@ -31,7 +31,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
* *
* @param \PhpSpreadsheet\Cell $cell Cell to bind value to * @param \PhpSpreadsheet\Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell * @param mixed $value Value to bind in cell
* @return boolean * @return bool
*/ */
public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null) public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null)
{ {
@ -48,15 +48,18 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Test for booleans using locale-setting // Test for booleans using locale-setting
if ($value == \PhpSpreadsheet\Calculation::getTRUE()) { if ($value == \PhpSpreadsheet\Calculation::getTRUE()) {
$cell->setValueExplicit(true, DataType::TYPE_BOOL); $cell->setValueExplicit(true, DataType::TYPE_BOOL);
return true; return true;
} elseif ($value == \PhpSpreadsheet\Calculation::getFALSE()) { } elseif ($value == \PhpSpreadsheet\Calculation::getFALSE()) {
$cell->setValueExplicit(false, DataType::TYPE_BOOL); $cell->setValueExplicit(false, DataType::TYPE_BOOL);
return true; return true;
} }
// Check for number in scientific format // Check for number in scientific format
if (preg_match('/^'.\PhpSpreadsheet\Calculation::CALCULATION_REGEXP_NUMBER.'$/', $value)) { if (preg_match('/^' . \PhpSpreadsheet\Calculation::CALCULATION_REGEXP_NUMBER . '$/', $value)) {
$cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
return true; return true;
} }
@ -71,6 +74,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode('??/??'); ->getNumberFormat()->setFormatCode('??/??');
return true; return true;
} elseif (preg_match('/^([+-]?)([0-9]*) +([0-9]*)\s?\/\s*([0-9]*)$/', $value, $matches)) { } elseif (preg_match('/^([+-]?)([0-9]*) +([0-9]*)\s?\/\s*([0-9]*)$/', $value, $matches)) {
// Convert value to number // Convert value to number
@ -82,6 +86,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode('# ??/??'); ->getNumberFormat()->setFormatCode('# ??/??');
return true; return true;
} }
@ -93,6 +98,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00); ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
return true; return true;
} }
@ -100,23 +106,25 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
$currencyCode = \PhpSpreadsheet\Shared\StringHelper::getCurrencyCode(); $currencyCode = \PhpSpreadsheet\Shared\StringHelper::getCurrencyCode();
$decimalSeparator = \PhpSpreadsheet\Shared\StringHelper::getDecimalSeparator(); $decimalSeparator = \PhpSpreadsheet\Shared\StringHelper::getDecimalSeparator();
$thousandsSeparator = \PhpSpreadsheet\Shared\StringHelper::getThousandsSeparator(); $thousandsSeparator = \PhpSpreadsheet\Shared\StringHelper::getThousandsSeparator();
if (preg_match('/^'.preg_quote($currencyCode).' *(\d{1,3}('.preg_quote($thousandsSeparator).'\d{3})*|(\d+))('.preg_quote($decimalSeparator).'\d{2})?$/', $value)) { if (preg_match('/^' . preg_quote($currencyCode) . ' *(\d{1,3}(' . preg_quote($thousandsSeparator) . '\d{3})*|(\d+))(' . preg_quote($decimalSeparator) . '\d{2})?$/', $value)) {
// Convert value to number // Convert value to number
$value = (float) trim(str_replace(array($currencyCode, $thousandsSeparator, $decimalSeparator), array('', '', '.'), $value)); $value = (float) trim(str_replace([$currencyCode, $thousandsSeparator, $decimalSeparator], ['', '', '.'], $value));
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC); $cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode( ->getNumberFormat()->setFormatCode(
str_replace('$', $currencyCode, \PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE) str_replace('$', $currencyCode, \PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE)
); );
return true; return true;
} elseif (preg_match('/^\$ *(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/', $value)) { } elseif (preg_match('/^\$ *(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/', $value)) {
// Convert value to number // Convert value to number
$value = (float) trim(str_replace(array('$',','), '', $value)); $value = (float) trim(str_replace(['$', ','], '', $value));
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC); $cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE); ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
return true; return true;
} }
@ -129,6 +137,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME3); ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME3);
return true; return true;
} }
@ -142,6 +151,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4); ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4);
return true; return true;
} }
@ -157,6 +167,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
} }
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode($formatCode); ->getNumberFormat()->setFormatCode($formatCode);
return true; return true;
} }
@ -167,6 +178,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Set style // Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate()) $cell->getWorksheet()->getStyle($cell->getCoordinate())
->getAlignment()->setWrapText(true); ->getAlignment()->setWrapText(true);
return true; return true;
} }
} }

View File

@ -27,29 +27,29 @@ namespace PhpSpreadsheet\Cell;
class DataType class DataType
{ {
/* Data types */ /* Data types */
const TYPE_STRING2 = 'str'; const TYPE_STRING2 = 'str';
const TYPE_STRING = 's'; const TYPE_STRING = 's';
const TYPE_FORMULA = 'f'; const TYPE_FORMULA = 'f';
const TYPE_NUMERIC = 'n'; const TYPE_NUMERIC = 'n';
const TYPE_BOOL = 'b'; const TYPE_BOOL = 'b';
const TYPE_NULL = 'null'; const TYPE_NULL = 'null';
const TYPE_INLINE = 'inlineStr'; const TYPE_INLINE = 'inlineStr';
const TYPE_ERROR = 'e'; const TYPE_ERROR = 'e';
/** /**
* List of error codes * List of error codes
* *
* @var array * @var array
*/ */
private static $errorCodes = array( private static $errorCodes = [
'#NULL!' => 0, '#NULL!' => 0,
'#DIV/0!' => 1, '#DIV/0!' => 1,
'#VALUE!' => 2, '#VALUE!' => 2,
'#REF!' => 3, '#REF!' => 3,
'#NAME?' => 4, '#NAME?' => 4,
'#NUM!' => 5, '#NUM!' => 5,
'#N/A' => 6 '#N/A' => 6,
); ];
/** /**
* Get list of error codes * Get list of error codes
@ -90,7 +90,7 @@ class DataType
$pValue = \PhpSpreadsheet\Shared\StringHelper::substring($pValue, 0, 32767); $pValue = \PhpSpreadsheet\Shared\StringHelper::substring($pValue, 0, 32767);
// we require that newline is represented as "\n" in core, not as "\r\n" or "\r" // we require that newline is represented as "\n" in core, not as "\r\n" or "\r"
$pValue = str_replace(array("\r\n", "\r"), "\n", $pValue); $pValue = str_replace(["\r\n", "\r"], "\n", $pValue);
return $pValue; return $pValue;
} }

View File

@ -27,29 +27,29 @@ namespace PhpSpreadsheet\Cell;
class DataValidation class DataValidation
{ {
/* Data validation types */ /* Data validation types */
const TYPE_NONE = 'none'; const TYPE_NONE = 'none';
const TYPE_CUSTOM = 'custom'; const TYPE_CUSTOM = 'custom';
const TYPE_DATE = 'date'; const TYPE_DATE = 'date';
const TYPE_DECIMAL = 'decimal'; const TYPE_DECIMAL = 'decimal';
const TYPE_LIST = 'list'; const TYPE_LIST = 'list';
const TYPE_TEXTLENGTH = 'textLength'; const TYPE_TEXTLENGTH = 'textLength';
const TYPE_TIME = 'time'; const TYPE_TIME = 'time';
const TYPE_WHOLE = 'whole'; const TYPE_WHOLE = 'whole';
/* Data validation error styles */ /* Data validation error styles */
const STYLE_STOP = 'stop'; const STYLE_STOP = 'stop';
const STYLE_WARNING = 'warning'; const STYLE_WARNING = 'warning';
const STYLE_INFORMATION = 'information'; const STYLE_INFORMATION = 'information';
/* Data validation operators */ /* Data validation operators */
const OPERATOR_BETWEEN = 'between'; const OPERATOR_BETWEEN = 'between';
const OPERATOR_EQUAL = 'equal'; const OPERATOR_EQUAL = 'equal';
const OPERATOR_GREATERTHAN = 'greaterThan'; const OPERATOR_GREATERTHAN = 'greaterThan';
const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
const OPERATOR_LESSTHAN = 'lessThan'; const OPERATOR_LESSTHAN = 'lessThan';
const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
const OPERATOR_NOTBETWEEN = 'notBetween'; const OPERATOR_NOTBETWEEN = 'notBetween';
const OPERATOR_NOTEQUAL = 'notEqual'; const OPERATOR_NOTEQUAL = 'notEqual';
/** /**
* Formula 1 * Formula 1
@ -70,14 +70,14 @@ class DataValidation
* *
* @var string * @var string
*/ */
private $type = DataValidation::TYPE_NONE; private $type = self::TYPE_NONE;
/** /**
* Error style * Error style
* *
* @var string * @var string
*/ */
private $errorStyle = DataValidation::STYLE_STOP; private $errorStyle = self::STYLE_STOP;
/** /**
* Operator * Operator
@ -89,28 +89,28 @@ class DataValidation
/** /**
* Allow Blank * Allow Blank
* *
* @var boolean * @var bool
*/ */
private $allowBlank = false; private $allowBlank = false;
/** /**
* Show DropDown * Show DropDown
* *
* @var boolean * @var bool
*/ */
private $showDropDown = false; private $showDropDown = false;
/** /**
* Show InputMessage * Show InputMessage
* *
* @var boolean * @var bool
*/ */
private $showInputMessage = false; private $showInputMessage = false;
/** /**
* Show ErrorMessage * Show ErrorMessage
* *
* @var boolean * @var bool
*/ */
private $showErrorMessage = false; private $showErrorMessage = false;
@ -168,6 +168,7 @@ class DataValidation
public function setFormula1($value = '') public function setFormula1($value = '')
{ {
$this->formula1 = $value; $this->formula1 = $value;
return $this; return $this;
} }
@ -190,6 +191,7 @@ class DataValidation
public function setFormula2($value = '') public function setFormula2($value = '')
{ {
$this->formula2 = $value; $this->formula2 = $value;
return $this; return $this;
} }
@ -212,6 +214,7 @@ class DataValidation
public function setType($value = self::TYPE_NONE) public function setType($value = self::TYPE_NONE)
{ {
$this->type = $value; $this->type = $value;
return $this; return $this;
} }
@ -234,6 +237,7 @@ class DataValidation
public function setErrorStyle($value = self::STYLE_STOP) public function setErrorStyle($value = self::STYLE_STOP)
{ {
$this->errorStyle = $value; $this->errorStyle = $value;
return $this; return $this;
} }
@ -256,13 +260,14 @@ class DataValidation
public function setOperator($value = '') public function setOperator($value = '')
{ {
$this->operator = $value; $this->operator = $value;
return $this; return $this;
} }
/** /**
* Get Allow Blank * Get Allow Blank
* *
* @return boolean * @return bool
*/ */
public function getAllowBlank() public function getAllowBlank()
{ {
@ -272,19 +277,20 @@ class DataValidation
/** /**
* Set Allow Blank * Set Allow Blank
* *
* @param boolean $value * @param bool $value
* @return DataValidation * @return DataValidation
*/ */
public function setAllowBlank($value = false) public function setAllowBlank($value = false)
{ {
$this->allowBlank = $value; $this->allowBlank = $value;
return $this; return $this;
} }
/** /**
* Get Show DropDown * Get Show DropDown
* *
* @return boolean * @return bool
*/ */
public function getShowDropDown() public function getShowDropDown()
{ {
@ -294,19 +300,20 @@ class DataValidation
/** /**
* Set Show DropDown * Set Show DropDown
* *
* @param boolean $value * @param bool $value
* @return DataValidation * @return DataValidation
*/ */
public function setShowDropDown($value = false) public function setShowDropDown($value = false)
{ {
$this->showDropDown = $value; $this->showDropDown = $value;
return $this; return $this;
} }
/** /**
* Get Show InputMessage * Get Show InputMessage
* *
* @return boolean * @return bool
*/ */
public function getShowInputMessage() public function getShowInputMessage()
{ {
@ -316,19 +323,20 @@ class DataValidation
/** /**
* Set Show InputMessage * Set Show InputMessage
* *
* @param boolean $value * @param bool $value
* @return DataValidation * @return DataValidation
*/ */
public function setShowInputMessage($value = false) public function setShowInputMessage($value = false)
{ {
$this->showInputMessage = $value; $this->showInputMessage = $value;
return $this; return $this;
} }
/** /**
* Get Show ErrorMessage * Get Show ErrorMessage
* *
* @return boolean * @return bool
*/ */
public function getShowErrorMessage() public function getShowErrorMessage()
{ {
@ -338,12 +346,13 @@ class DataValidation
/** /**
* Set Show ErrorMessage * Set Show ErrorMessage
* *
* @param boolean $value * @param bool $value
* @return DataValidation * @return DataValidation
*/ */
public function setShowErrorMessage($value = false) public function setShowErrorMessage($value = false)
{ {
$this->showErrorMessage = $value; $this->showErrorMessage = $value;
return $this; return $this;
} }
@ -366,6 +375,7 @@ class DataValidation
public function setErrorTitle($value = '') public function setErrorTitle($value = '')
{ {
$this->errorTitle = $value; $this->errorTitle = $value;
return $this; return $this;
} }
@ -388,6 +398,7 @@ class DataValidation
public function setError($value = '') public function setError($value = '')
{ {
$this->error = $value; $this->error = $value;
return $this; return $this;
} }
@ -410,6 +421,7 @@ class DataValidation
public function setPromptTitle($value = '') public function setPromptTitle($value = '')
{ {
$this->promptTitle = $value; $this->promptTitle = $value;
return $this; return $this;
} }
@ -432,6 +444,7 @@ class DataValidation
public function setPrompt($value = '') public function setPrompt($value = '')
{ {
$this->prompt = $value; $this->prompt = $value;
return $this; return $this;
} }

View File

@ -31,7 +31,7 @@ class DefaultValueBinder implements IValueBinder
* *
* @param \PhpSpreadsheet\Cell $cell Cell to bind value to * @param \PhpSpreadsheet\Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell * @param mixed $value Value to bind in cell
* @return boolean * @return bool
*/ */
public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null) public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null)
{ {
@ -82,6 +82,7 @@ class DefaultValueBinder implements IValueBinder
} elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) { } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) {
return DataType::TYPE_STRING; return DataType::TYPE_STRING;
} }
return DataType::TYPE_NUMERIC; return DataType::TYPE_NUMERIC;
} elseif (is_string($pValue) && array_key_exists($pValue, DataType::getErrorCodes())) { } elseif (is_string($pValue) && array_key_exists($pValue, DataType::getErrorCodes())) {
return DataType::TYPE_ERROR; return DataType::TYPE_ERROR;

View File

@ -49,7 +49,7 @@ class Hyperlink
public function __construct($pUrl = '', $pTooltip = '') public function __construct($pUrl = '', $pTooltip = '')
{ {
// Initialise member variables // Initialise member variables
$this->url = $pUrl; $this->url = $pUrl;
$this->tooltip = $pTooltip; $this->tooltip = $pTooltip;
} }
@ -72,6 +72,7 @@ class Hyperlink
public function setUrl($value = '') public function setUrl($value = '')
{ {
$this->url = $value; $this->url = $value;
return $this; return $this;
} }
@ -94,13 +95,14 @@ class Hyperlink
public function setTooltip($value = '') public function setTooltip($value = '')
{ {
$this->tooltip = $value; $this->tooltip = $value;
return $this; return $this;
} }
/** /**
* Is this hyperlink internal? (to another worksheet) * Is this hyperlink internal? (to another worksheet)
* *
* @return boolean * @return bool
*/ */
public function isInternal() public function isInternal()
{ {

View File

@ -31,7 +31,7 @@ interface IValueBinder
* *
* @param \PhpSpreadsheet\Cell $cell Cell to bind value to * @param \PhpSpreadsheet\Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell * @param mixed $value Value to bind in cell
* @return boolean * @return bool
*/ */
public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null); public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null);
} }

View File

@ -78,7 +78,7 @@ class Chart
/** /**
* Plot Visible Only * Plot Visible Only
* *
* @var boolean * @var bool
*/ */
private $plotVisibleOnly = true; private $plotVisibleOnly = true;
@ -124,23 +124,20 @@ class Chart
*/ */
private $topLeftCellRef = 'A1'; private $topLeftCellRef = 'A1';
/** /**
* Top-Left X-Offset * Top-Left X-Offset
* *
* @var integer * @var int
*/ */
private $topLeftXOffset = 0; private $topLeftXOffset = 0;
/** /**
* Top-Left Y-Offset * Top-Left Y-Offset
* *
* @var integer * @var int
*/ */
private $topLeftYOffset = 0; private $topLeftYOffset = 0;
/** /**
* Bottom-Right Cell Position * Bottom-Right Cell Position
* *
@ -148,23 +145,20 @@ class Chart
*/ */
private $bottomRightCellRef = 'A1'; private $bottomRightCellRef = 'A1';
/** /**
* Bottom-Right X-Offset * Bottom-Right X-Offset
* *
* @var integer * @var int
*/ */
private $bottomRightXOffset = 10; private $bottomRightXOffset = 10;
/** /**
* Bottom-Right Y-Offset * Bottom-Right Y-Offset
* *
* @var integer * @var int
*/ */
private $bottomRightYOffset = 10; private $bottomRightYOffset = 10;
/** /**
* Create a new Chart * Create a new Chart
*/ */
@ -323,7 +317,7 @@ class Chart
/** /**
* Get Plot Visible Only * Get Plot Visible Only
* *
* @return boolean * @return bool
*/ */
public function getPlotVisibleOnly() public function getPlotVisibleOnly()
{ {
@ -333,7 +327,7 @@ class Chart
/** /**
* Set Plot Visible Only * Set Plot Visible Only
* *
* @param boolean $plotVisibleOnly * @param bool $plotVisibleOnly
* @return Chart * @return Chart
*/ */
public function setPlotVisibleOnly($plotVisibleOnly = true) public function setPlotVisibleOnly($plotVisibleOnly = true)
@ -364,7 +358,6 @@ class Chart
$this->displayBlanksAs = $displayBlanksAs; $this->displayBlanksAs = $displayBlanksAs;
} }
/** /**
* Get yAxis * Get yAxis
* *
@ -421,13 +414,12 @@ class Chart
return new Chart\GridLines(); return new Chart\GridLines();
} }
/** /**
* Set the Top Left position for the chart * Set the Top Left position for the chart
* *
* @param string $cell * @param string $cell
* @param integer $xOffset * @param int $xOffset
* @param integer $yOffset * @param int $yOffset
* @return Chart * @return Chart
*/ */
public function setTopLeftPosition($cell, $xOffset = null, $yOffset = null) public function setTopLeftPosition($cell, $xOffset = null, $yOffset = null)
@ -450,11 +442,11 @@ class Chart
*/ */
public function getTopLeftPosition() public function getTopLeftPosition()
{ {
return array( return [
'cell' => $this->topLeftCellRef, 'cell' => $this->topLeftCellRef,
'xOffset' => $this->topLeftXOffset, 'xOffset' => $this->topLeftXOffset,
'yOffset' => $this->topLeftYOffset 'yOffset' => $this->topLeftYOffset,
); ];
} }
/** /**
@ -483,8 +475,8 @@ class Chart
/** /**
* Set the offset position within the Top Left cell for the chart * Set the offset position within the Top Left cell for the chart
* *
* @param integer $xOffset * @param int $xOffset
* @param integer $yOffset * @param int $yOffset
* @return Chart * @return Chart
*/ */
public function setTopLeftOffset($xOffset = null, $yOffset = null) public function setTopLeftOffset($xOffset = null, $yOffset = null)
@ -502,14 +494,14 @@ class Chart
/** /**
* Get the offset position within the Top Left cell for the chart * Get the offset position within the Top Left cell for the chart
* *
* @return integer[] * @return int[]
*/ */
public function getTopLeftOffset() public function getTopLeftOffset()
{ {
return array( return [
'X' => $this->topLeftXOffset, 'X' => $this->topLeftXOffset,
'Y' => $this->topLeftYOffset 'Y' => $this->topLeftYOffset,
); ];
} }
public function setTopLeftXOffset($xOffset) public function setTopLeftXOffset($xOffset)
@ -540,8 +532,8 @@ class Chart
* Set the Bottom Right position of the chart * Set the Bottom Right position of the chart
* *
* @param string $cell * @param string $cell
* @param integer $xOffset * @param int $xOffset
* @param integer $yOffset * @param int $yOffset
* @return Chart * @return Chart
*/ */
public function setBottomRightPosition($cell, $xOffset = null, $yOffset = null) public function setBottomRightPosition($cell, $xOffset = null, $yOffset = null)
@ -564,11 +556,11 @@ class Chart
*/ */
public function getBottomRightPosition() public function getBottomRightPosition()
{ {
return array( return [
'cell' => $this->bottomRightCellRef, 'cell' => $this->bottomRightCellRef,
'xOffset' => $this->bottomRightXOffset, 'xOffset' => $this->bottomRightXOffset,
'yOffset' => $this->bottomRightYOffset 'yOffset' => $this->bottomRightYOffset,
); ];
} }
public function setBottomRightCell($cell) public function setBottomRightCell($cell)
@ -591,8 +583,8 @@ class Chart
/** /**
* Set the offset position within the Bottom Right cell for the chart * Set the offset position within the Bottom Right cell for the chart
* *
* @param integer $xOffset * @param int $xOffset
* @param integer $yOffset * @param int $yOffset
* @return Chart * @return Chart
*/ */
public function setBottomRightOffset($xOffset = null, $yOffset = null) public function setBottomRightOffset($xOffset = null, $yOffset = null)
@ -610,14 +602,14 @@ class Chart
/** /**
* Get the offset position within the Bottom Right cell for the chart * Get the offset position within the Bottom Right cell for the chart
* *
* @return integer[] * @return int[]
*/ */
public function getBottomRightOffset() public function getBottomRightOffset()
{ {
return array( return [
'X' => $this->bottomRightXOffset, 'X' => $this->bottomRightXOffset,
'Y' => $this->bottomRightYOffset 'Y' => $this->bottomRightYOffset,
); ];
} }
public function setBottomRightXOffset($xOffset) public function setBottomRightXOffset($xOffset)
@ -644,7 +636,6 @@ class Chart
return $this->bottomRightYOffset; return $this->bottomRightYOffset;
} }
public function refresh() public function refresh()
{ {
if ($this->worksheet !== null) { if ($this->worksheet !== null) {
@ -668,12 +659,13 @@ class Chart
set_include_path(get_include_path() . PATH_SEPARATOR . $libraryPath); set_include_path(get_include_path() . PATH_SEPARATOR . $libraryPath);
} }
$rendererName = '\\PhpSpreadsheet\\Chart\\Renderer\\'.$libraryName; $rendererName = '\\PhpSpreadsheet\\Chart\\Renderer\\' . $libraryName;
$renderer = new $rendererName($this); $renderer = new $rendererName($this);
if ($outputDestination == 'php://output') { if ($outputDestination == 'php://output') {
$outputDestination = null; $outputDestination = null;
} }
return $renderer->render($outputDestination); return $renderer->render($outputDestination);
} }
} }

View File

@ -8,7 +8,6 @@ namespace PhpSpreadsheet\Chart;
* Date: 6/17/14 * Date: 6/17/14
* Time: 12:11 PM * Time: 12:11 PM
*/ */
class Axis extends Properties class Axis extends Properties
{ {
/** /**
@ -16,17 +15,17 @@ class Axis extends Properties
* *
* @var array of mixed * @var array of mixed
*/ */
private $axisNumber = array( private $axisNumber = [
'format' => self::FORMAT_CODE_GENERAL, 'format' => self::FORMAT_CODE_GENERAL,
'source_linked' => 1 'source_linked' => 1,
); ];
/** /**
* Axis Options * Axis Options
* *
* @var array of mixed * @var array of mixed
*/ */
private $axisOptions = array( private $axisOptions = [
'minimum' => null, 'minimum' => null,
'maximum' => null, 'maximum' => null,
'major_unit' => null, 'major_unit' => null,
@ -36,101 +35,101 @@ class Axis extends Properties
'major_tick_mark' => self::TICK_MARK_NONE, 'major_tick_mark' => self::TICK_MARK_NONE,
'axis_labels' => self::AXIS_LABELS_NEXT_TO, 'axis_labels' => self::AXIS_LABELS_NEXT_TO,
'horizontal_crosses' => self::HORIZONTAL_CROSSES_AUTOZERO, 'horizontal_crosses' => self::HORIZONTAL_CROSSES_AUTOZERO,
'horizontal_crosses_value' => null 'horizontal_crosses_value' => null,
); ];
/** /**
* Fill Properties * Fill Properties
* *
* @var array of mixed * @var array of mixed
*/ */
private $fillProperties = array( private $fillProperties = [
'type' => self::EXCEL_COLOR_TYPE_ARGB, 'type' => self::EXCEL_COLOR_TYPE_ARGB,
'value' => null, 'value' => null,
'alpha' => 0 'alpha' => 0,
); ];
/** /**
* Line Properties * Line Properties
* *
* @var array of mixed * @var array of mixed
*/ */
private $lineProperties = array( private $lineProperties = [
'type' => self::EXCEL_COLOR_TYPE_ARGB, 'type' => self::EXCEL_COLOR_TYPE_ARGB,
'value' => null, 'value' => null,
'alpha' => 0 'alpha' => 0,
); ];
/** /**
* Line Style Properties * Line Style Properties
* *
* @var array of mixed * @var array of mixed
*/ */
private $lineStyleProperties = array( private $lineStyleProperties = [
'width' => '9525', 'width' => '9525',
'compound' => self::LINE_STYLE_COMPOUND_SIMPLE, 'compound' => self::LINE_STYLE_COMPOUND_SIMPLE,
'dash' => self::LINE_STYLE_DASH_SOLID, 'dash' => self::LINE_STYLE_DASH_SOLID,
'cap' => self::LINE_STYLE_CAP_FLAT, 'cap' => self::LINE_STYLE_CAP_FLAT,
'join' => self::LINE_STYLE_JOIN_BEVEL, 'join' => self::LINE_STYLE_JOIN_BEVEL,
'arrow' => array( 'arrow' => [
'head' => array( 'head' => [
'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW,
'size' => self::LINE_STYLE_ARROW_SIZE_5 'size' => self::LINE_STYLE_ARROW_SIZE_5,
), ],
'end' => array( 'end' => [
'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW,
'size' => self::LINE_STYLE_ARROW_SIZE_8 'size' => self::LINE_STYLE_ARROW_SIZE_8,
), ],
) ],
); ];
/** /**
* Shadow Properties * Shadow Properties
* *
* @var array of mixed * @var array of mixed
*/ */
private $shadowProperties = array( private $shadowProperties = [
'presets' => self::SHADOW_PRESETS_NOSHADOW, 'presets' => self::SHADOW_PRESETS_NOSHADOW,
'effect' => null, 'effect' => null,
'color' => array( 'color' => [
'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'type' => self::EXCEL_COLOR_TYPE_STANDARD,
'value' => 'black', 'value' => 'black',
'alpha' => 40, 'alpha' => 40,
), ],
'size' => array( 'size' => [
'sx' => null, 'sx' => null,
'sy' => null, 'sy' => null,
'kx' => null 'kx' => null,
), ],
'blur' => null, 'blur' => null,
'direction' => null, 'direction' => null,
'distance' => null, 'distance' => null,
'algn' => null, 'algn' => null,
'rotWithShape' => null 'rotWithShape' => null,
); ];
/** /**
* Glow Properties * Glow Properties
* *
* @var array of mixed * @var array of mixed
*/ */
private $glowProperties = array( private $glowProperties = [
'size' => null, 'size' => null,
'color' => array( 'color' => [
'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'type' => self::EXCEL_COLOR_TYPE_STANDARD,
'value' => 'black', 'value' => 'black',
'alpha' => 40 'alpha' => 40,
) ],
); ];
/** /**
* Soft Edge Properties * Soft Edge Properties
* *
* @var array of mixed * @var array of mixed
*/ */
private $softEdges = array( private $softEdges = [
'size' => null 'size' => null,
); ];
/** /**
* Get Series Data Type * Get Series Data Type
@ -176,7 +175,6 @@ class Axis extends Properties
* @param string $maximum * @param string $maximum
* @param string $major_unit * @param string $major_unit
* @param string $minor_unit * @param string $minor_unit
*
*/ */
public function setAxisOptionsProperties($axis_labels, $horizontal_crosses_value = null, $horizontal_crosses = null, $axis_orientation = null, $major_tmt = null, $minor_tmt = null, $minimum = null, $maximum = null, $major_unit = null, $minor_unit = null) public function setAxisOptionsProperties($axis_labels, $horizontal_crosses_value = null, $horizontal_crosses = null, $axis_orientation = null, $major_tmt = null, $minor_tmt = null, $minimum = null, $maximum = null, $major_unit = null, $minor_unit = null)
{ {
@ -209,7 +207,6 @@ class Axis extends Properties
* Set Axis Orientation Property * Set Axis Orientation Property
* *
* @param string $orientation * @param string $orientation
*
*/ */
public function setAxisOrientation($orientation) public function setAxisOrientation($orientation)
{ {
@ -222,7 +219,6 @@ class Axis extends Properties
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $type
*
*/ */
public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB)
{ {
@ -235,7 +231,6 @@ class Axis extends Properties
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $type
*
*/ */
public function setLineParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) public function setLineParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB)
{ {
@ -278,7 +273,6 @@ class Axis extends Properties
* @param string $head_arrow_size * @param string $head_arrow_size
* @param string $end_arrow_type * @param string $end_arrow_type
* @param string $end_arrow_size * @param string $end_arrow_size
*
*/ */
public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null)
{ {
@ -339,7 +333,6 @@ class Axis extends Properties
* @param float $sh_blur * @param float $sh_blur
* @param int $sh_angle * @param int $sh_angle
* @param float $sh_distance * @param float $sh_distance
*
*/ */
public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null)
{ {
@ -383,9 +376,9 @@ class Axis extends Properties
foreach ($properties_map as $property_key => $property_val) { foreach ($properties_map as $property_key => $property_val) {
if (is_array($property_val)) { if (is_array($property_val)) {
if ($reference === null) { if ($reference === null) {
$reference = & $this->shadowProperties[$property_key]; $reference = &$this->shadowProperties[$property_key];
} else { } else {
$reference = & $reference[$property_key]; $reference = &$reference[$property_key];
} }
$this->setShadowProperiesMapValues($property_val, $reference); $this->setShadowProperiesMapValues($property_val, $reference);
} else { } else {

View File

@ -26,40 +26,39 @@ namespace PhpSpreadsheet\Chart;
*/ */
class DataSeries class DataSeries
{ {
const TYPE_BARCHART = 'barChart'; const TYPE_BARCHART = 'barChart';
const TYPE_BARCHART_3D = 'bar3DChart'; const TYPE_BARCHART_3D = 'bar3DChart';
const TYPE_LINECHART = 'lineChart'; const TYPE_LINECHART = 'lineChart';
const TYPE_LINECHART_3D = 'line3DChart'; const TYPE_LINECHART_3D = 'line3DChart';
const TYPE_AREACHART = 'areaChart'; const TYPE_AREACHART = 'areaChart';
const TYPE_AREACHART_3D = 'area3DChart'; const TYPE_AREACHART_3D = 'area3DChart';
const TYPE_PIECHART = 'pieChart'; const TYPE_PIECHART = 'pieChart';
const TYPE_PIECHART_3D = 'pie3DChart'; const TYPE_PIECHART_3D = 'pie3DChart';
const TYPE_DOUGHTNUTCHART = 'doughnutChart'; const TYPE_DOUGHTNUTCHART = 'doughnutChart';
const TYPE_DONUTCHART = self::TYPE_DOUGHTNUTCHART; // Synonym const TYPE_DONUTCHART = self::TYPE_DOUGHTNUTCHART; // Synonym
const TYPE_SCATTERCHART = 'scatterChart'; const TYPE_SCATTERCHART = 'scatterChart';
const TYPE_SURFACECHART = 'surfaceChart'; const TYPE_SURFACECHART = 'surfaceChart';
const TYPE_SURFACECHART_3D = 'surface3DChart'; const TYPE_SURFACECHART_3D = 'surface3DChart';
const TYPE_RADARCHART = 'radarChart'; const TYPE_RADARCHART = 'radarChart';
const TYPE_BUBBLECHART = 'bubbleChart'; const TYPE_BUBBLECHART = 'bubbleChart';
const TYPE_STOCKCHART = 'stockChart'; const TYPE_STOCKCHART = 'stockChart';
const TYPE_CANDLECHART = self::TYPE_STOCKCHART; // Synonym const TYPE_CANDLECHART = self::TYPE_STOCKCHART; // Synonym
const GROUPING_CLUSTERED = 'clustered'; const GROUPING_CLUSTERED = 'clustered';
const GROUPING_STACKED = 'stacked'; const GROUPING_STACKED = 'stacked';
const GROUPING_PERCENT_STACKED = 'percentStacked'; const GROUPING_PERCENT_STACKED = 'percentStacked';
const GROUPING_STANDARD = 'standard'; const GROUPING_STANDARD = 'standard';
const DIRECTION_BAR = 'bar'; const DIRECTION_BAR = 'bar';
const DIRECTION_HORIZONTAL = self::DIRECTION_BAR; const DIRECTION_HORIZONTAL = self::DIRECTION_BAR;
const DIRECTION_COL = 'col'; const DIRECTION_COL = 'col';
const DIRECTION_COLUMN = self::DIRECTION_COL; const DIRECTION_COLUMN = self::DIRECTION_COL;
const DIRECTION_VERTICAL = self::DIRECTION_COL; const DIRECTION_VERTICAL = self::DIRECTION_COL;
const STYLE_LINEMARKER = 'lineMarker'; const STYLE_LINEMARKER = 'lineMarker';
const STYLE_SMOOTHMARKER = 'smoothMarker'; const STYLE_SMOOTHMARKER = 'smoothMarker';
const STYLE_MARKER = 'marker'; const STYLE_MARKER = 'marker';
const STYLE_FILLED = 'filled'; const STYLE_FILLED = 'filled';
/** /**
* Series Plot Type * Series Plot Type
@ -71,14 +70,14 @@ class DataSeries
/** /**
* Plot Grouping Type * Plot Grouping Type
* *
* @var boolean * @var bool
*/ */
private $plotGrouping; private $plotGrouping;
/** /**
* Plot Direction * Plot Direction
* *
* @var boolean * @var bool
*/ */
private $plotDirection; private $plotDirection;
@ -94,21 +93,21 @@ class DataSeries
* *
* @var array of integer * @var array of integer
*/ */
private $plotOrder = array(); private $plotOrder = [];
/** /**
* Plot Label * Plot Label
* *
* @var array of DataSeriesValues * @var array of DataSeriesValues
*/ */
private $plotLabel = array(); private $plotLabel = [];
/** /**
* Plot Category * Plot Category
* *
* @var array of DataSeriesValues * @var array of DataSeriesValues
*/ */
private $plotCategory = array(); private $plotCategory = [];
/** /**
* Smooth Line * Smooth Line
@ -122,12 +121,12 @@ class DataSeries
* *
* @var array of DataSeriesValues * @var array of DataSeriesValues
*/ */
private $plotValues = array(); private $plotValues = [];
/** /**
* Create a new DataSeries * Create a new DataSeries
*/ */
public function __construct($plotType = null, $plotGrouping = null, $plotOrder = array(), $plotLabel = array(), $plotCategory = array(), $plotValues = array(), $plotDirection = null, $smoothLine = null, $plotStyle = null) public function __construct($plotType = null, $plotGrouping = null, $plotOrder = [], $plotLabel = [], $plotCategory = [], $plotValues = [], $plotDirection = null, $smoothLine = null, $plotStyle = null)
{ {
$this->plotType = $plotType; $this->plotType = $plotType;
$this->plotGrouping = $plotGrouping; $this->plotGrouping = $plotGrouping;
@ -171,6 +170,7 @@ class DataSeries
public function setPlotType($plotType = '') public function setPlotType($plotType = '')
{ {
$this->plotType = $plotType; $this->plotType = $plotType;
return $this; return $this;
} }
@ -193,6 +193,7 @@ class DataSeries
public function setPlotGrouping($groupingType = null) public function setPlotGrouping($groupingType = null)
{ {
$this->plotGrouping = $groupingType; $this->plotGrouping = $groupingType;
return $this; return $this;
} }
@ -215,6 +216,7 @@ class DataSeries
public function setPlotDirection($plotDirection = null) public function setPlotDirection($plotDirection = null)
{ {
$this->plotDirection = $plotDirection; $this->plotDirection = $plotDirection;
return $this; return $this;
} }
@ -251,6 +253,7 @@ class DataSeries
} elseif (isset($keys[$index])) { } elseif (isset($keys[$index])) {
return $this->plotLabel[$keys[$index]]; return $this->plotLabel[$keys[$index]];
} }
return false; return false;
} }
@ -277,6 +280,7 @@ class DataSeries
} elseif (isset($keys[$index])) { } elseif (isset($keys[$index])) {
return $this->plotCategory[$keys[$index]]; return $this->plotCategory[$keys[$index]];
} }
return false; return false;
} }
@ -299,6 +303,7 @@ class DataSeries
public function setPlotStyle($plotStyle = null) public function setPlotStyle($plotStyle = null)
{ {
$this->plotStyle = $plotStyle; $this->plotStyle = $plotStyle;
return $this; return $this;
} }
@ -325,13 +330,14 @@ class DataSeries
} elseif (isset($keys[$index])) { } elseif (isset($keys[$index])) {
return $this->plotValues[$keys[$index]]; return $this->plotValues[$keys[$index]];
} }
return false; return false;
} }
/** /**
* Get Number of Plot Series * Get Number of Plot Series
* *
* @return integer * @return int
*/ */
public function getPlotSeriesCount() public function getPlotSeriesCount()
{ {
@ -341,7 +347,7 @@ class DataSeries
/** /**
* Get Smooth Line * Get Smooth Line
* *
* @return boolean * @return bool
*/ */
public function getSmoothLine() public function getSmoothLine()
{ {
@ -351,12 +357,13 @@ class DataSeries
/** /**
* Set Smooth Line * Set Smooth Line
* *
* @param boolean $smoothLine * @param bool $smoothLine
* @return DataSeries * @return DataSeries
*/ */
public function setSmoothLine($smoothLine = true) public function setSmoothLine($smoothLine = true)
{ {
$this->smoothLine = $smoothLine; $this->smoothLine = $smoothLine;
return $this; return $this;
} }

View File

@ -28,14 +28,13 @@ namespace PhpSpreadsheet\Chart;
*/ */
class DataSeriesValues class DataSeriesValues
{ {
const DATASERIES_TYPE_STRING = 'String';
const DATASERIES_TYPE_NUMBER = 'Number';
const DATASERIES_TYPE_STRING = 'String'; private static $dataTypeValues = [
const DATASERIES_TYPE_NUMBER = 'Number';
private static $dataTypeValues = array(
self::DATASERIES_TYPE_STRING, self::DATASERIES_TYPE_STRING,
self::DATASERIES_TYPE_NUMBER, self::DATASERIES_TYPE_NUMBER,
); ];
/** /**
* Series Data Type * Series Data Type
@ -68,7 +67,7 @@ class DataSeriesValues
/** /**
* Point Count (The number of datapoints in the dataseries) * Point Count (The number of datapoints in the dataseries)
* *
* @var integer * @var int
*/ */
private $pointCount = 0; private $pointCount = 0;
@ -77,12 +76,12 @@ class DataSeriesValues
* *
* @var array of mixed * @var array of mixed
*/ */
private $dataValues = array(); private $dataValues = [];
/** /**
* Create a new DataSeriesValues object * Create a new DataSeriesValues object
*/ */
public function __construct($dataType = self::DATASERIES_TYPE_NUMBER, $dataSource = null, $formatCode = null, $pointCount = 0, $dataValues = array(), $marker = null) public function __construct($dataType = self::DATASERIES_TYPE_NUMBER, $dataSource = null, $formatCode = null, $pointCount = 0, $dataValues = [], $marker = null)
{ {
$this->setDataType($dataType); $this->setDataType($dataType);
$this->dataSource = $dataSource; $this->dataSource = $dataSource;
@ -111,8 +110,8 @@ class DataSeriesValues
* Normally used for axis point values * Normally used for axis point values
* \PhpSpreadsheet\Chart\DataSeriesValues::DATASERIES_TYPE_NUMBER * \PhpSpreadsheet\Chart\DataSeriesValues::DATASERIES_TYPE_NUMBER
* Normally used for chart data values * Normally used for chart data values
* @return DataSeriesValues
* @throws Exception * @throws Exception
* @return DataSeriesValues
*/ */
public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER) public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER)
{ {
@ -200,7 +199,7 @@ class DataSeriesValues
/** /**
* Get Series Point Count * Get Series Point Count
* *
* @return integer * @return int
*/ */
public function getPointCount() public function getPointCount()
{ {
@ -210,20 +209,21 @@ class DataSeriesValues
/** /**
* Identify if the Data Series is a multi-level or a simple series * Identify if the Data Series is a multi-level or a simple series
* *
* @return boolean * @return bool
*/ */
public function isMultiLevelSeries() public function isMultiLevelSeries()
{ {
if (count($this->dataValues) > 0) { if (count($this->dataValues) > 0) {
return is_array($this->dataValues[0]); return is_array($this->dataValues[0]);
} }
return null; return null;
} }
/** /**
* Return the level count of a multi-level Data Series * Return the level count of a multi-level Data Series
* *
* @return boolean * @return bool
*/ */
public function multiLevelCount() public function multiLevelCount()
{ {
@ -231,6 +231,7 @@ class DataSeriesValues
foreach ($this->dataValues as $dataValueSet) { foreach ($this->dataValues as $dataValueSet) {
$levelCount = max($levelCount, count($dataValueSet)); $levelCount = max($levelCount, count($dataValueSet));
} }
return $levelCount; return $levelCount;
} }
@ -257,6 +258,7 @@ class DataSeriesValues
} elseif ($count == 1) { } elseif ($count == 1) {
return $this->dataValues[0]; return $this->dataValues[0];
} }
return $this->dataValues; return $this->dataValues;
} }
@ -264,12 +266,12 @@ class DataSeriesValues
* Set Series Data Values * Set Series Data Values
* *
* @param array $dataValues * @param array $dataValues
* @param boolean $refreshDataSource * @param bool $refreshDataSource
* TRUE - refresh the value of dataSource based on the values of $dataValues * TRUE - refresh the value of dataSource based on the values of $dataValues
* FALSE - don't change the value of dataSource * FALSE - don't change the value of dataSource
* @return DataSeriesValues * @return DataSeriesValues
*/ */
public function setDataValues($dataValues = array(), $refreshDataSource = true) public function setDataValues($dataValues = [], $refreshDataSource = true)
{ {
$this->dataValues = \PhpSpreadsheet\Calculation\Functions::flattenArray($dataValues); $this->dataValues = \PhpSpreadsheet\Calculation\Functions::flattenArray($dataValues);
$this->pointCount = count($dataValues); $this->pointCount = count($dataValues);
@ -292,7 +294,7 @@ class DataSeriesValues
$calcEngine = \PhpSpreadsheet\Calculation::getInstance($worksheet->getParent()); $calcEngine = \PhpSpreadsheet\Calculation::getInstance($worksheet->getParent());
$newDataValues = \PhpSpreadsheet\Calculation::unwrapResult( $newDataValues = \PhpSpreadsheet\Calculation::unwrapResult(
$calcEngine->_calculateFormulaValue( $calcEngine->_calculateFormulaValue(
'='.$this->dataSource, '=' . $this->dataSource,
null, null,
$worksheet->getCell('A1') $worksheet->getCell('A1')
) )
@ -317,7 +319,7 @@ class DataSeriesValues
} else { } else {
$newArray = array_values(array_shift($newDataValues)); $newArray = array_values(array_shift($newDataValues));
foreach ($newArray as $i => $newDataSet) { foreach ($newArray as $i => $newDataSet) {
$newArray[$i] = array($newDataSet); $newArray[$i] = [$newDataSet];
} }
foreach ($newDataValues as $newDataSet) { foreach ($newDataValues as $newDataSet) {

View File

@ -8,86 +8,81 @@ namespace PhpSpreadsheet\Chart;
* Date: 7/2/14 * Date: 7/2/14
* Time: 2:36 PM * Time: 2:36 PM
*/ */
class GridLines extends Properties class GridLines extends Properties
{ {
/**
/** * Properties of Class:
* Properties of Class: * Object State (State for Minor Tick Mark) @var bool
* Object State (State for Minor Tick Mark) @var bool * Line Properties @var array of mixed
* Line Properties @var array of mixed * Shadow Properties @var array of mixed
* Shadow Properties @var array of mixed * Glow Properties @var array of mixed
* Glow Properties @var array of mixed * Soft Properties @var array of mixed
* Soft Properties @var array of mixed */
*
*/
private $objectState = false; private $objectState = false;
private $lineProperties = array( private $lineProperties = [
'color' => array( 'color' => [
'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'type' => self::EXCEL_COLOR_TYPE_STANDARD,
'value' => null, 'value' => null,
'alpha' => 0 'alpha' => 0,
), ],
'style' => array( 'style' => [
'width' => '9525', 'width' => '9525',
'compound' => self::LINE_STYLE_COMPOUND_SIMPLE, 'compound' => self::LINE_STYLE_COMPOUND_SIMPLE,
'dash' => self::LINE_STYLE_DASH_SOLID, 'dash' => self::LINE_STYLE_DASH_SOLID,
'cap' => self::LINE_STYLE_CAP_FLAT, 'cap' => self::LINE_STYLE_CAP_FLAT,
'join' => self::LINE_STYLE_JOIN_BEVEL, 'join' => self::LINE_STYLE_JOIN_BEVEL,
'arrow' => array( 'arrow' => [
'head' => array( 'head' => [
'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW,
'size' => self::LINE_STYLE_ARROW_SIZE_5 'size' => self::LINE_STYLE_ARROW_SIZE_5,
), ],
'end' => array( 'end' => [
'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW,
'size' => self::LINE_STYLE_ARROW_SIZE_8 'size' => self::LINE_STYLE_ARROW_SIZE_8,
), ],
) ],
) ],
); ];
private $shadowProperties = array( private $shadowProperties = [
'presets' => self::SHADOW_PRESETS_NOSHADOW, 'presets' => self::SHADOW_PRESETS_NOSHADOW,
'effect' => null, 'effect' => null,
'color' => array( 'color' => [
'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'type' => self::EXCEL_COLOR_TYPE_STANDARD,
'value' => 'black', 'value' => 'black',
'alpha' => 85, 'alpha' => 85,
), ],
'size' => array( 'size' => [
'sx' => null, 'sx' => null,
'sy' => null, 'sy' => null,
'kx' => null 'kx' => null,
), ],
'blur' => null, 'blur' => null,
'direction' => null, 'direction' => null,
'distance' => null, 'distance' => null,
'algn' => null, 'algn' => null,
'rotWithShape' => null 'rotWithShape' => null,
); ];
private $glowProperties = array( private $glowProperties = [
'size' => null, 'size' => null,
'color' => array( 'color' => [
'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'type' => self::EXCEL_COLOR_TYPE_STANDARD,
'value' => 'black', 'value' => 'black',
'alpha' => 40 'alpha' => 40,
) ],
); ];
private $softEdges = array( private $softEdges = [
'size' => null 'size' => null,
); ];
/** /**
* Get Object State * Get Object State
* *
* @return bool * @return bool
*/ */
public function getObjectState() public function getObjectState()
{ {
return $this->objectState; return $this->objectState;
@ -98,7 +93,6 @@ class GridLines extends Properties
* *
* @return GridLines * @return GridLines
*/ */
private function activateObject() private function activateObject()
{ {
$this->objectState = true; $this->objectState = true;
@ -113,7 +107,6 @@ class GridLines extends Properties
* @param int $alpha * @param int $alpha
* @param string $type * @param string $type
*/ */
public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD) public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD)
{ {
$this->activateObject() $this->activateObject()
@ -137,7 +130,6 @@ class GridLines extends Properties
* @param string $end_arrow_type * @param string $end_arrow_type
* @param string $end_arrow_size * @param string $end_arrow_size
*/ */
public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null)
{ {
$this->activateObject(); $this->activateObject();
@ -177,7 +169,6 @@ class GridLines extends Properties
* *
* @return string * @return string
*/ */
public function getLineColorProperty($parameter) public function getLineColorProperty($parameter)
{ {
return $this->lineProperties['color'][$parameter]; return $this->lineProperties['color'][$parameter];
@ -190,7 +181,6 @@ class GridLines extends Properties
* *
* @return string * @return string
*/ */
public function getLineStyleProperty($elements) public function getLineStyleProperty($elements)
{ {
return $this->getArrayElementsValue($this->lineProperties['style'], $elements); return $this->getArrayElementsValue($this->lineProperties['style'], $elements);
@ -203,9 +193,7 @@ class GridLines extends Properties
* @param string $color_value * @param string $color_value
* @param int $color_alpha * @param int $color_alpha
* @param string $color_type * @param string $color_type
*
*/ */
public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null)
{ {
$this $this
@ -221,7 +209,6 @@ class GridLines extends Properties
* *
* @return string * @return string
*/ */
public function getGlowColor($property) public function getGlowColor($property)
{ {
return $this->glowProperties['color'][$property]; return $this->glowProperties['color'][$property];
@ -232,7 +219,6 @@ class GridLines extends Properties
* *
* @return string * @return string
*/ */
public function getGlowSize() public function getGlowSize()
{ {
return $this->glowProperties['size']; return $this->glowProperties['size'];
@ -245,7 +231,6 @@ class GridLines extends Properties
* *
* @return GridLines * @return GridLines
*/ */
private function setGlowSize($size) private function setGlowSize($size)
{ {
$this->glowProperties['size'] = $this->getExcelPointsWidth((float) $size); $this->glowProperties['size'] = $this->getExcelPointsWidth((float) $size);
@ -262,7 +247,6 @@ class GridLines extends Properties
* *
* @return GridLines * @return GridLines
*/ */
private function setGlowColor($color, $alpha, $type) private function setGlowColor($color, $alpha, $type)
{ {
if (!is_null($color)) { if (!is_null($color)) {
@ -286,7 +270,6 @@ class GridLines extends Properties
* *
* @return string * @return string
*/ */
public function getLineStyleArrowParameters($arrow_selector, $property_selector) public function getLineStyleArrowParameters($arrow_selector, $property_selector)
{ {
return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrow_selector]['size'], $property_selector); return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrow_selector]['size'], $property_selector);
@ -302,9 +285,7 @@ class GridLines extends Properties
* @param string $sh_blur * @param string $sh_blur
* @param int $sh_angle * @param int $sh_angle
* @param float $sh_distance * @param float $sh_distance
*
*/ */
public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null)
{ {
$this->activateObject() $this->activateObject()
@ -326,7 +307,6 @@ class GridLines extends Properties
* *
* @return GridLines * @return GridLines
*/ */
private function setShadowPresetsProperties($shadow_presets) private function setShadowPresetsProperties($shadow_presets)
{ {
$this->shadowProperties['presets'] = $shadow_presets; $this->shadowProperties['presets'] = $shadow_presets;
@ -343,16 +323,15 @@ class GridLines extends Properties
* *
* @return GridLines * @return GridLines
*/ */
private function setShadowProperiesMapValues(array $properties_map, &$reference = null) private function setShadowProperiesMapValues(array $properties_map, &$reference = null)
{ {
$base_reference = $reference; $base_reference = $reference;
foreach ($properties_map as $property_key => $property_val) { foreach ($properties_map as $property_key => $property_val) {
if (is_array($property_val)) { if (is_array($property_val)) {
if ($reference === null) { if ($reference === null) {
$reference = & $this->shadowProperties[$property_key]; $reference = &$this->shadowProperties[$property_key];
} else { } else {
$reference = & $reference[$property_key]; $reference = &$reference[$property_key];
} }
$this->setShadowProperiesMapValues($property_val, $reference); $this->setShadowProperiesMapValues($property_val, $reference);
} else { } else {
@ -412,7 +391,6 @@ class GridLines extends Properties
* @param int $angle * @param int $angle
* @return GridLines * @return GridLines
*/ */
private function setShadowAngle($angle) private function setShadowAngle($angle)
{ {
if ($angle !== null) { if ($angle !== null) {

View File

@ -81,7 +81,7 @@ class Layout
* show legend key * show legend key
* Specifies that legend keys should be shown in data labels * Specifies that legend keys should be shown in data labels
* *
* @var boolean * @var bool
*/ */
private $showLegendKey; private $showLegendKey;
@ -89,7 +89,7 @@ class Layout
* show value * show value
* Specifies that the value should be shown in a data label. * Specifies that the value should be shown in a data label.
* *
* @var boolean * @var bool
*/ */
private $showVal; private $showVal;
@ -97,7 +97,7 @@ class Layout
* show category name * show category name
* Specifies that the category name should be shown in the data label. * Specifies that the category name should be shown in the data label.
* *
* @var boolean * @var bool
*/ */
private $showCatName; private $showCatName;
@ -105,7 +105,7 @@ class Layout
* show data series name * show data series name
* Specifies that the series name should be shown in the data label. * Specifies that the series name should be shown in the data label.
* *
* @var boolean * @var bool
*/ */
private $showSerName; private $showSerName;
@ -113,14 +113,14 @@ class Layout
* show percentage * show percentage
* Specifies that the percentage should be shown in the data label. * Specifies that the percentage should be shown in the data label.
* *
* @var boolean * @var bool
*/ */
private $showPercent; private $showPercent;
/** /**
* show bubble size * show bubble size
* *
* @var boolean * @var bool
*/ */
private $showBubbleSize; private $showBubbleSize;
@ -128,15 +128,14 @@ class Layout
* show leader lines * show leader lines
* Specifies that leader lines should be shown for the data label. * Specifies that leader lines should be shown for the data label.
* *
* @var boolean * @var bool
*/ */
private $showLeaderLines; private $showLeaderLines;
/** /**
* Create a new Layout * Create a new Layout
*/ */
public function __construct($layout = array()) public function __construct($layout = [])
{ {
if (isset($layout['layoutTarget'])) { if (isset($layout['layoutTarget'])) {
$this->layoutTarget = $layout['layoutTarget']; $this->layoutTarget = $layout['layoutTarget'];
@ -180,6 +179,7 @@ class Layout
public function setLayoutTarget($value) public function setLayoutTarget($value)
{ {
$this->layoutTarget = $value; $this->layoutTarget = $value;
return $this; return $this;
} }
@ -202,6 +202,7 @@ class Layout
public function setXMode($value) public function setXMode($value)
{ {
$this->xMode = $value; $this->xMode = $value;
return $this; return $this;
} }
@ -224,6 +225,7 @@ class Layout
public function setYMode($value) public function setYMode($value)
{ {
$this->yMode = $value; $this->yMode = $value;
return $this; return $this;
} }
@ -246,6 +248,7 @@ class Layout
public function setXPosition($value) public function setXPosition($value)
{ {
$this->xPos = $value; $this->xPos = $value;
return $this; return $this;
} }
@ -268,6 +271,7 @@ class Layout
public function setYPosition($value) public function setYPosition($value)
{ {
$this->yPos = $value; $this->yPos = $value;
return $this; return $this;
} }
@ -290,6 +294,7 @@ class Layout
public function setWidth($value) public function setWidth($value)
{ {
$this->width = $value; $this->width = $value;
return $this; return $this;
} }
@ -312,14 +317,14 @@ class Layout
public function setHeight($value) public function setHeight($value)
{ {
$this->height = $value; $this->height = $value;
return $this; return $this;
} }
/** /**
* Get show legend key * Get show legend key
* *
* @return boolean * @return bool
*/ */
public function getShowLegendKey() public function getShowLegendKey()
{ {
@ -330,19 +335,20 @@ class Layout
* Set show legend key * Set show legend key
* Specifies that legend keys should be shown in data labels. * Specifies that legend keys should be shown in data labels.
* *
* @param boolean $value Show legend key * @param bool $value Show legend key
* @return Layout * @return Layout
*/ */
public function setShowLegendKey($value) public function setShowLegendKey($value)
{ {
$this->showLegendKey = $value; $this->showLegendKey = $value;
return $this; return $this;
} }
/** /**
* Get show value * Get show value
* *
* @return boolean * @return bool
*/ */
public function getShowVal() public function getShowVal()
{ {
@ -353,19 +359,20 @@ class Layout
* Set show val * Set show val
* Specifies that the value should be shown in data labels. * Specifies that the value should be shown in data labels.
* *
* @param boolean $value Show val * @param bool $value Show val
* @return Layout * @return Layout
*/ */
public function setShowVal($value) public function setShowVal($value)
{ {
$this->showVal = $value; $this->showVal = $value;
return $this; return $this;
} }
/** /**
* Get show category name * Get show category name
* *
* @return boolean * @return bool
*/ */
public function getShowCatName() public function getShowCatName()
{ {
@ -376,19 +383,20 @@ class Layout
* Set show cat name * Set show cat name
* Specifies that the category name should be shown in data labels. * Specifies that the category name should be shown in data labels.
* *
* @param boolean $value Show cat name * @param bool $value Show cat name
* @return Layout * @return Layout
*/ */
public function setShowCatName($value) public function setShowCatName($value)
{ {
$this->showCatName = $value; $this->showCatName = $value;
return $this; return $this;
} }
/** /**
* Get show data series name * Get show data series name
* *
* @return boolean * @return bool
*/ */
public function getShowSerName() public function getShowSerName()
{ {
@ -399,19 +407,20 @@ class Layout
* Set show ser name * Set show ser name
* Specifies that the series name should be shown in data labels. * Specifies that the series name should be shown in data labels.
* *
* @param boolean $value Show series name * @param bool $value Show series name
* @return Layout * @return Layout
*/ */
public function setShowSerName($value) public function setShowSerName($value)
{ {
$this->showSerName = $value; $this->showSerName = $value;
return $this; return $this;
} }
/** /**
* Get show percentage * Get show percentage
* *
* @return boolean * @return bool
*/ */
public function getShowPercent() public function getShowPercent()
{ {
@ -422,19 +431,20 @@ class Layout
* Set show percentage * Set show percentage
* Specifies that the percentage should be shown in data labels. * Specifies that the percentage should be shown in data labels.
* *
* @param boolean $value Show percentage * @param bool $value Show percentage
* @return Layout * @return Layout
*/ */
public function setShowPercent($value) public function setShowPercent($value)
{ {
$this->showPercent = $value; $this->showPercent = $value;
return $this; return $this;
} }
/** /**
* Get show bubble size * Get show bubble size
* *
* @return boolean * @return bool
*/ */
public function getShowBubbleSize() public function getShowBubbleSize()
{ {
@ -445,19 +455,20 @@ class Layout
* Set show bubble size * Set show bubble size
* Specifies that the bubble size should be shown in data labels. * Specifies that the bubble size should be shown in data labels.
* *
* @param boolean $value Show bubble size * @param bool $value Show bubble size
* @return Layout * @return Layout
*/ */
public function setShowBubbleSize($value) public function setShowBubbleSize($value)
{ {
$this->showBubbleSize = $value; $this->showBubbleSize = $value;
return $this; return $this;
} }
/** /**
* Get show leader lines * Get show leader lines
* *
* @return boolean * @return bool
*/ */
public function getShowLeaderLines() public function getShowLeaderLines()
{ {
@ -468,12 +479,13 @@ class Layout
* Set show leader lines * Set show leader lines
* Specifies that leader lines should be shown in data labels. * Specifies that leader lines should be shown in data labels.
* *
* @param boolean $value Show leader lines * @param bool $value Show leader lines
* @return Layout * @return Layout
*/ */
public function setShowLeaderLines($value) public function setShowLeaderLines($value)
{ {
$this->showLeaderLines = $value; $this->showLeaderLines = $value;
return $this; return $this;
} }
} }

View File

@ -32,24 +32,24 @@ class Legend
const XL_LEGEND_POSITION_BOTTOM = -4107; // Below the chart. const XL_LEGEND_POSITION_BOTTOM = -4107; // Below the chart.
const XL_LEGEND_POSITION_CORNER = 2; // In the upper right-hand corner of the chart border. const XL_LEGEND_POSITION_CORNER = 2; // In the upper right-hand corner of the chart border.
const XL_LEGEND_POSITION_CUSTOM = -4161; // A custom position. const XL_LEGEND_POSITION_CUSTOM = -4161; // A custom position.
const XL_LEGEND_POSITION_LEFT = -4131; // Left of the chart. const XL_LEGEND_POSITION_LEFT = -4131; // Left of the chart.
const XL_LEGEND_POSITION_RIGHT = -4152; // Right of the chart. const XL_LEGEND_POSITION_RIGHT = -4152; // Right of the chart.
const XL_LEGEND_POSITION_TOP = -4160; // Above the chart. const XL_LEGEND_POSITION_TOP = -4160; // Above the chart.
const POSITION_RIGHT = 'r'; const POSITION_RIGHT = 'r';
const POSITION_LEFT = 'l'; const POSITION_LEFT = 'l';
const POSITION_BOTTOM = 'b'; const POSITION_BOTTOM = 'b';
const POSITION_TOP = 't'; const POSITION_TOP = 't';
const POSITION_TOPRIGHT = 'tr'; const POSITION_TOPRIGHT = 'tr';
private static $positionXLref = array( private static $positionXLref = [
self::XL_LEGEND_POSITION_BOTTOM => self::POSITION_BOTTOM, self::XL_LEGEND_POSITION_BOTTOM => self::POSITION_BOTTOM,
self::XL_LEGEND_POSITION_CORNER => self::POSITION_TOPRIGHT, self::XL_LEGEND_POSITION_CORNER => self::POSITION_TOPRIGHT,
self::XL_LEGEND_POSITION_CUSTOM => '??', self::XL_LEGEND_POSITION_CUSTOM => '??',
self::XL_LEGEND_POSITION_LEFT => self::POSITION_LEFT, self::XL_LEGEND_POSITION_LEFT => self::POSITION_LEFT,
self::XL_LEGEND_POSITION_RIGHT => self::POSITION_RIGHT, self::XL_LEGEND_POSITION_RIGHT => self::POSITION_RIGHT,
self::XL_LEGEND_POSITION_TOP => self::POSITION_TOP self::XL_LEGEND_POSITION_TOP => self::POSITION_TOP,
); ];
/** /**
* Legend position * Legend position
@ -61,7 +61,7 @@ class Legend
/** /**
* Allow overlay of other elements? * Allow overlay of other elements?
* *
* @var boolean * @var bool
*/ */
private $overlay = true; private $overlay = true;
@ -72,7 +72,6 @@ class Legend
*/ */
private $layout = null; private $layout = null;
/** /**
* Create a new Legend * Create a new Legend
*/ */
@ -105,6 +104,7 @@ class Legend
} }
$this->position = $position; $this->position = $position;
return true; return true;
} }
@ -130,13 +130,14 @@ class Legend
} }
$this->position = self::$positionXLref[$positionXL]; $this->position = self::$positionXLref[$positionXL];
return true; return true;
} }
/** /**
* Get allow overlay of other elements? * Get allow overlay of other elements?
* *
* @return boolean * @return bool
*/ */
public function getOverlay() public function getOverlay()
{ {
@ -146,8 +147,8 @@ class Legend
/** /**
* Set allow overlay of other elements? * Set allow overlay of other elements?
* *
* @param boolean $overlay * @param bool $overlay
* @return boolean * @return bool
*/ */
public function setOverlay($overlay = false) public function setOverlay($overlay = false)
{ {
@ -156,6 +157,7 @@ class Legend
} }
$this->overlay = $overlay; $this->overlay = $overlay;
return true; return true;
} }

View File

@ -38,12 +38,12 @@ class PlotArea
* *
* @var array of DataSeries * @var array of DataSeries
*/ */
private $plotSeries = array(); private $plotSeries = [];
/** /**
* Create a new PlotArea * Create a new PlotArea
*/ */
public function __construct(Layout $layout = null, $plotSeries = array()) public function __construct(Layout $layout = null, $plotSeries = [])
{ {
$this->layout = $layout; $this->layout = $layout;
$this->plotSeries = $plotSeries; $this->plotSeries = $plotSeries;
@ -72,7 +72,7 @@ class PlotArea
/** /**
* Get Number of Plot Series * Get Number of Plot Series
* *
* @return integer * @return int
*/ */
public function getPlotSeriesCount() public function getPlotSeriesCount()
{ {
@ -80,6 +80,7 @@ class PlotArea
foreach ($this->plotSeries as $plot) { foreach ($this->plotSeries as $plot) {
$seriesCount += $plot->getPlotSeriesCount(); $seriesCount += $plot->getPlotSeriesCount();
} }
return $seriesCount; return $seriesCount;
} }
@ -109,7 +110,7 @@ class PlotArea
* @param DataSeries[] * @param DataSeries[]
* @return PlotArea * @return PlotArea
*/ */
public function setPlotSeries($plotSeries = array()) public function setPlotSeries($plotSeries = [])
{ {
$this->plotSeries = $plotSeries; $this->plotSeries = $plotSeries;

View File

@ -8,7 +8,6 @@ namespace PhpSpreadsheet\Chart;
* Date: 7/2/14 * Date: 7/2/14
* Time: 5:45 PM * Time: 5:45 PM
*/ */
abstract class Properties abstract class Properties
{ {
const const
@ -133,234 +132,235 @@ abstract class Properties
protected function setColorProperties($color, $alpha, $type) protected function setColorProperties($color, $alpha, $type)
{ {
return array( return [
'type' => (string) $type, 'type' => (string) $type,
'value' => (string) $color, 'value' => (string) $color,
'alpha' => (string) $this->getTrueAlpha($alpha) 'alpha' => (string) $this->getTrueAlpha($alpha),
); ];
} }
protected function getLineStyleArrowSize($array_selector, $array_kay_selector) protected function getLineStyleArrowSize($array_selector, $array_kay_selector)
{ {
$sizes = array( $sizes = [
1 => array('w' => 'sm', 'len' => 'sm'), 1 => ['w' => 'sm', 'len' => 'sm'],
2 => array('w' => 'sm', 'len' => 'med'), 2 => ['w' => 'sm', 'len' => 'med'],
3 => array('w' => 'sm', 'len' => 'lg'), 3 => ['w' => 'sm', 'len' => 'lg'],
4 => array('w' => 'med', 'len' => 'sm'), 4 => ['w' => 'med', 'len' => 'sm'],
5 => array('w' => 'med', 'len' => 'med'), 5 => ['w' => 'med', 'len' => 'med'],
6 => array('w' => 'med', 'len' => 'lg'), 6 => ['w' => 'med', 'len' => 'lg'],
7 => array('w' => 'lg', 'len' => 'sm'), 7 => ['w' => 'lg', 'len' => 'sm'],
8 => array('w' => 'lg', 'len' => 'med'), 8 => ['w' => 'lg', 'len' => 'med'],
9 => array('w' => 'lg', 'len' => 'lg') 9 => ['w' => 'lg', 'len' => 'lg'],
); ];
return $sizes[$array_selector][$array_kay_selector]; return $sizes[$array_selector][$array_kay_selector];
} }
protected function getShadowPresetsMap($shadow_presets_option) protected function getShadowPresetsMap($shadow_presets_option)
{ {
$presets_options = array( $presets_options = [
//OUTER //OUTER
1 => array( 1 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'direction' => '2700000', 'direction' => '2700000',
'algn' => 'tl', 'algn' => 'tl',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
2 => array( 2 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'direction' => '5400000', 'direction' => '5400000',
'algn' => 't', 'algn' => 't',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
3 => array( 3 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'direction' => '8100000', 'direction' => '8100000',
'algn' => 'tr', 'algn' => 'tr',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
4 => array( 4 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'algn' => 'l', 'algn' => 'l',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
5 => array( 5 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'size' => array( 'size' => [
'sx' => '102000', 'sx' => '102000',
'sy' => '102000' 'sy' => '102000',
) ],
,
'blur' => '63500', 'blur' => '63500',
'distance' => '38100', 'distance' => '38100',
'algn' => 'ctr', 'algn' => 'ctr',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
6 => array( 6 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'direction' => '10800000', 'direction' => '10800000',
'algn' => 'r', 'algn' => 'r',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
7 => array( 7 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'direction' => '18900000', 'direction' => '18900000',
'algn' => 'bl', 'algn' => 'bl',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
8 => array( 8 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'direction' => '16200000', 'direction' => '16200000',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
9 => array( 9 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '50800', 'blur' => '50800',
'distance' => '38100', 'distance' => '38100',
'direction' => '13500000', 'direction' => '13500000',
'algn' => 'br', 'algn' => 'br',
'rotWithShape' => '0' 'rotWithShape' => '0',
), ],
//INNER //INNER
10 => array( 10 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
'direction' => '2700000', 'direction' => '2700000',
), ],
11 => array( 11 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
'direction' => '5400000', 'direction' => '5400000',
), ],
12 => array( 12 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
'direction' => '8100000', 'direction' => '8100000',
), ],
13 => array( 13 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
), ],
14 => array( 14 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '114300', 'blur' => '114300',
), ],
15 => array( 15 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
'direction' => '10800000', 'direction' => '10800000',
), ],
16 => array( 16 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
'direction' => '18900000', 'direction' => '18900000',
), ],
17 => array( 17 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
'direction' => '16200000', 'direction' => '16200000',
), ],
18 => array( 18 => [
'effect' => 'innerShdw', 'effect' => 'innerShdw',
'blur' => '63500', 'blur' => '63500',
'distance' => '50800', 'distance' => '50800',
'direction' => '13500000', 'direction' => '13500000',
), ],
//perspective //perspective
19 => array( 19 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '152400', 'blur' => '152400',
'distance' => '317500', 'distance' => '317500',
'size' => array( 'size' => [
'sx' => '90000', 'sx' => '90000',
'sy' => '-19000', 'sy' => '-19000',
), ],
'direction' => '5400000', 'direction' => '5400000',
'rotWithShape' => '0', 'rotWithShape' => '0',
), ],
20 => array( 20 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '76200', 'blur' => '76200',
'direction' => '18900000', 'direction' => '18900000',
'size' => array( 'size' => [
'sy' => '23000', 'sy' => '23000',
'kx' => '-1200000', 'kx' => '-1200000',
), ],
'algn' => 'bl', 'algn' => 'bl',
'rotWithShape' => '0', 'rotWithShape' => '0',
), ],
21 => array( 21 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '76200', 'blur' => '76200',
'direction' => '13500000', 'direction' => '13500000',
'size' => array( 'size' => [
'sy' => '23000', 'sy' => '23000',
'kx' => '1200000', 'kx' => '1200000',
), ],
'algn' => 'br', 'algn' => 'br',
'rotWithShape' => '0', 'rotWithShape' => '0',
), ],
22 => array( 22 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '76200', 'blur' => '76200',
'distance' => '12700', 'distance' => '12700',
'direction' => '2700000', 'direction' => '2700000',
'size' => array( 'size' => [
'sy' => '-23000', 'sy' => '-23000',
'kx' => '-800400', 'kx' => '-800400',
), ],
'algn' => 'bl', 'algn' => 'bl',
'rotWithShape' => '0', 'rotWithShape' => '0',
), ],
23 => array( 23 => [
'effect' => 'outerShdw', 'effect' => 'outerShdw',
'blur' => '76200', 'blur' => '76200',
'distance' => '12700', 'distance' => '12700',
'direction' => '8100000', 'direction' => '8100000',
'size' => array( 'size' => [
'sy' => '-23000', 'sy' => '-23000',
'kx' => '800400', 'kx' => '800400',
), ],
'algn' => 'br', 'algn' => 'br',
'rotWithShape' => '0', 'rotWithShape' => '0',
), ],
); ];
return $presets_options[$shadow_presets_option]; return $presets_options[$shadow_presets_option];
} }
protected function getArrayElementsValue($properties, $elements) protected function getArrayElementsValue($properties, $elements)
{ {
$reference = & $properties; $reference = &$properties;
if (!is_array($elements)) { if (!is_array($elements)) {
return $reference[$elements]; return $reference[$elements];
} else { } else {
foreach ($elements as $keys) { foreach ($elements as $keys) {
$reference = & $reference[$keys]; $reference = &$reference[$keys];
} }
return $reference; return $reference;
} }
return $this; return $this;
} }
} }

View File

@ -2,7 +2,7 @@
namespace PhpSpreadsheet\Chart\Renderer; namespace PhpSpreadsheet\Chart\Renderer;
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'/jpgraph.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . '/jpgraph.php';
/** /**
* Copyright (c) 2006 - 2016 PhpSpreadsheet * Copyright (c) 2006 - 2016 PhpSpreadsheet
@ -28,31 +28,30 @@ require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'/jpgraph.php');
*/ */
class JpGraph class JpGraph
{ {
private static $width = 640; private static $width = 640;
private static $height = 480; private static $height = 480;
private static $colourSet = [ private static $colourSet = [
'mediumpurple1', 'palegreen3', 'gold1', 'cadetblue1', 'mediumpurple1', 'palegreen3', 'gold1', 'cadetblue1',
'darkmagenta', 'coral', 'dodgerblue3', 'eggplant', 'darkmagenta', 'coral', 'dodgerblue3', 'eggplant',
'mediumblue', 'magenta', 'sandybrown', 'cyan', 'mediumblue', 'magenta', 'sandybrown', 'cyan',
'firebrick1', 'forestgreen', 'deeppink4', 'darkolivegreen', 'firebrick1', 'forestgreen', 'deeppink4', 'darkolivegreen',
'goldenrod2' 'goldenrod2',
]; ];
private static $markSet = [ private static $markSet = [
'diamond' => MARK_DIAMOND, 'diamond' => MARK_DIAMOND,
'square' => MARK_SQUARE, 'square' => MARK_SQUARE,
'triangle' => MARK_UTRIANGLE, 'triangle' => MARK_UTRIANGLE,
'x' => MARK_X, 'x' => MARK_X,
'star' => MARK_STAR, 'star' => MARK_STAR,
'dot' => MARK_FILLEDCIRCLE, 'dot' => MARK_FILLEDCIRCLE,
'dash' => MARK_DTRIANGLE, 'dash' => MARK_DTRIANGLE,
'circle' => MARK_CIRCLE, 'circle' => MARK_CIRCLE,
'plus' => MARK_CROSS 'plus' => MARK_CROSS,
]; ];
private $chart; private $chart;
private $graph; private $graph;
@ -61,7 +60,6 @@ class JpGraph
private static $plotMark = 0; private static $plotMark = 0;
private function formatPointMarker($seriesPlot, $markerID) private function formatPointMarker($seriesPlot, $markerID)
{ {
$plotMarkKeys = array_keys(self::$markSet); $plotMarkKeys = array_keys(self::$markSet);
@ -89,7 +87,6 @@ class JpGraph
return $seriesPlot; return $seriesPlot;
} }
private function formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') private function formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '')
{ {
$datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode();
@ -102,7 +99,7 @@ class JpGraph
foreach ($datasetLabels as $i => $datasetLabel) { foreach ($datasetLabels as $i => $datasetLabel) {
if (is_array($datasetLabel)) { if (is_array($datasetLabel)) {
if ($rotation == 'bar') { if ($rotation == 'bar') {
$datasetLabels[$i] = implode(" ", $datasetLabel); $datasetLabels[$i] = implode(' ', $datasetLabel);
} else { } else {
$datasetLabel = array_reverse($datasetLabel); $datasetLabel = array_reverse($datasetLabel);
$datasetLabels[$i] = implode("\n", $datasetLabel); $datasetLabels[$i] = implode("\n", $datasetLabel);
@ -119,7 +116,6 @@ class JpGraph
return $datasetLabels; return $datasetLabels;
} }
private function percentageSumCalculation($groupID, $seriesCount) private function percentageSumCalculation($groupID, $seriesCount)
{ {
// Adjust our values to a percentage value across all series in the group // Adjust our values to a percentage value across all series in the group
@ -141,7 +137,6 @@ class JpGraph
return $sumValues; return $sumValues;
} }
private function percentageAdjustValues($dataValues, $sumValues) private function percentageAdjustValues($dataValues, $sumValues)
{ {
foreach ($dataValues as $k => $dataValue) { foreach ($dataValues as $k => $dataValue) {
@ -151,7 +146,6 @@ class JpGraph
return $dataValues; return $dataValues;
} }
private function getCaption($captionElement) private function getCaption($captionElement)
{ {
// Read any caption // Read any caption
@ -164,10 +158,10 @@ class JpGraph
$caption = implode('', $caption); $caption = implode('', $caption);
} }
} }
return $caption; return $caption;
} }
private function renderTitle() private function renderTitle()
{ {
$title = $this->getCaption($this->chart->getTitle()); $title = $this->getCaption($this->chart->getTitle());
@ -176,7 +170,6 @@ class JpGraph
} }
} }
private function renderLegend() private function renderLegend()
{ {
$legend = $this->chart->getLegend(); $legend = $this->chart->getLegend();
@ -208,7 +201,6 @@ class JpGraph
} }
} }
private function renderCartesianPlotArea($type = 'textlin') private function renderCartesianPlotArea($type = 'textlin')
{ {
$this->graph = new Graph(self::$width, self::$height); $this->graph = new Graph(self::$width, self::$height);
@ -246,7 +238,6 @@ class JpGraph
} }
} }
private function renderPiePlotArea($doughnut = false) private function renderPiePlotArea($doughnut = false)
{ {
$this->graph = new PieGraph(self::$width, self::$height); $this->graph = new PieGraph(self::$width, self::$height);
@ -254,7 +245,6 @@ class JpGraph
$this->renderTitle(); $this->renderTitle();
} }
private function renderRadarPlotArea() private function renderRadarPlotArea()
{ {
$this->graph = new RadarGraph(self::$width, self::$height); $this->graph = new RadarGraph(self::$width, self::$height);
@ -263,7 +253,6 @@ class JpGraph
$this->renderTitle(); $this->renderTitle();
} }
private function renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') private function renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d')
{ {
$grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping();
@ -276,7 +265,7 @@ class JpGraph
} }
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = array(); $seriesPlots = [];
if ($grouping == 'percentStacked') { if ($grouping == 'percentStacked') {
$sumValues = $this->percentageSumCalculation($groupID, $seriesCount); $sumValues = $this->percentageSumCalculation($groupID, $seriesCount);
} }
@ -327,7 +316,6 @@ class JpGraph
$this->graph->Add($groupPlot); $this->graph->Add($groupPlot);
} }
private function renderPlotBar($groupID, $dimensions = '2d') private function renderPlotBar($groupID, $dimensions = '2d')
{ {
$rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection();
@ -351,9 +339,8 @@ class JpGraph
$this->graph->xaxis->SetTickLabels($datasetLabels); $this->graph->xaxis->SetTickLabels($datasetLabels);
} }
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = array(); $seriesPlots = [];
if ($grouping == 'percentStacked') { if ($grouping == 'percentStacked') {
$sumValues = $this->percentageSumCalculation($groupID, $seriesCount); $sumValues = $this->percentageSumCalculation($groupID, $seriesCount);
} }
@ -413,14 +400,13 @@ class JpGraph
$this->graph->Add($groupPlot); $this->graph->Add($groupPlot);
} }
private function renderPlotScatter($groupID, $bubble) private function renderPlotScatter($groupID, $bubble)
{ {
$grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping();
$scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle();
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = array(); $seriesPlots = [];
// Loop through each data series in turn // Loop through each data series in turn
for ($i = 0; $i < $seriesCount; ++$i) { for ($i = 0; $i < $seriesCount; ++$i) {
@ -459,13 +445,12 @@ class JpGraph
} }
} }
private function renderPlotRadar($groupID) private function renderPlotRadar($groupID)
{ {
$radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle();
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = array(); $seriesPlots = [];
// Loop through each data series in turn // Loop through each data series in turn
for ($i = 0; $i < $seriesCount; ++$i) { for ($i = 0; $i < $seriesCount; ++$i) {
@ -473,7 +458,7 @@ class JpGraph
$dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues();
$marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker();
$dataValues = array(); $dataValues = [];
foreach ($dataValuesY as $k => $dataValueY) { foreach ($dataValuesY as $k => $dataValueY) {
$dataValues[$k] = implode(' ', array_reverse($dataValueY)); $dataValues[$k] = implode(' ', array_reverse($dataValueY));
} }
@ -498,15 +483,14 @@ class JpGraph
} }
} }
private function renderPlotContour($groupID) private function renderPlotContour($groupID)
{ {
$contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle();
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = array(); $seriesPlots = [];
$dataValues = array(); $dataValues = [];
// Loop through each data series in turn // Loop through each data series in turn
for ($i = 0; $i < $seriesCount; ++$i) { for ($i = 0; $i < $seriesCount; ++$i) {
$dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues();
@ -519,13 +503,12 @@ class JpGraph
$this->graph->Add($seriesPlot); $this->graph->Add($seriesPlot);
} }
private function renderPlotStock($groupID) private function renderPlotStock($groupID)
{ {
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder();
$dataValues = array(); $dataValues = [];
// Loop through each data series in turn and build the plot arrays // Loop through each data series in turn and build the plot arrays
foreach ($plotOrder as $i => $v) { foreach ($plotOrder as $i => $v) {
$dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues();
@ -537,7 +520,7 @@ class JpGraph
return; return;
} }
$dataValuesPlot = array(); $dataValuesPlot = [];
// Flatten the plot arrays to a single dimensional array to work with jpgraph // Flatten the plot arrays to a single dimensional array to work with jpgraph
for ($j = 0; $j < count($dataValues[0]); ++$j) { for ($j = 0; $j < count($dataValues[0]); ++$j) {
for ($i = 0; $i < $seriesCount; ++$i) { for ($i = 0; $i < $seriesCount; ++$i) {
@ -559,10 +542,9 @@ class JpGraph
$this->graph->Add($seriesPlot); $this->graph->Add($seriesPlot);
} }
private function renderAreaChart($groupCount, $dimensions = '2d') private function renderAreaChart($groupCount, $dimensions = '2d')
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php';
$this->renderCartesianPlotArea(); $this->renderCartesianPlotArea();
@ -571,10 +553,9 @@ class JpGraph
} }
} }
private function renderLineChart($groupCount, $dimensions = '2d') private function renderLineChart($groupCount, $dimensions = '2d')
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php';
$this->renderCartesianPlotArea(); $this->renderCartesianPlotArea();
@ -583,10 +564,9 @@ class JpGraph
} }
} }
private function renderBarChart($groupCount, $dimensions = '2d') private function renderBarChart($groupCount, $dimensions = '2d')
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_bar.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_bar.php';
$this->renderCartesianPlotArea(); $this->renderCartesianPlotArea();
@ -595,12 +575,11 @@ class JpGraph
} }
} }
private function renderScatterChart($groupCount) private function renderScatterChart($groupCount)
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_scatter.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_scatter.php';
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_regstat.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_regstat.php';
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php';
$this->renderCartesianPlotArea('linlin'); $this->renderCartesianPlotArea('linlin');
@ -609,10 +588,9 @@ class JpGraph
} }
} }
private function renderBubbleChart($groupCount) private function renderBubbleChart($groupCount)
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_scatter.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_scatter.php';
$this->renderCartesianPlotArea('linlin'); $this->renderCartesianPlotArea('linlin');
@ -621,12 +599,11 @@ class JpGraph
} }
} }
private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = false, $multiplePlots = false) private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = false, $multiplePlots = false)
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_pie.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_pie.php';
if ($dimensions == '3d') { if ($dimensions == '3d') {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_pie3d.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_pie3d.php';
} }
$this->renderPiePlotArea($doughnut); $this->renderPiePlotArea($doughnut);
@ -644,7 +621,7 @@ class JpGraph
} }
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = array(); $seriesPlots = [];
// For pie charts, we only display the first series: doughnut charts generally display all series // For pie charts, we only display the first series: doughnut charts generally display all series
$jLimit = ($multiplePlots) ? $seriesCount : 1; $jLimit = ($multiplePlots) ? $seriesCount : 1;
// Loop through each data series in turn // Loop through each data series in turn
@ -672,7 +649,7 @@ class JpGraph
} }
if ($multiplePlots) { if ($multiplePlots) {
$seriesPlot->SetSize(($jLimit-$j) / ($jLimit * 4)); $seriesPlot->SetSize(($jLimit - $j) / ($jLimit * 4));
} }
if ($doughnut) { if ($doughnut) {
@ -698,10 +675,9 @@ class JpGraph
} }
} }
private function renderRadarChart($groupCount) private function renderRadarChart($groupCount)
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_radar.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_radar.php';
$this->renderRadarPlotArea(); $this->renderRadarPlotArea();
@ -710,10 +686,9 @@ class JpGraph
} }
} }
private function renderStockChart($groupCount) private function renderStockChart($groupCount)
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_stock.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_stock.php';
$this->renderCartesianPlotArea('intint'); $this->renderCartesianPlotArea('intint');
@ -722,10 +697,9 @@ class JpGraph
} }
} }
private function renderContourChart($groupCount, $dimensions) private function renderContourChart($groupCount, $dimensions)
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_contour.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_contour.php';
$this->renderCartesianPlotArea('intint'); $this->renderCartesianPlotArea('intint');
@ -734,14 +708,13 @@ class JpGraph
} }
} }
private function renderCombinationChart($groupCount, $dimensions, $outputDestination) private function renderCombinationChart($groupCount, $dimensions, $outputDestination)
{ {
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php';
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_bar.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_bar.php';
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_scatter.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_scatter.php';
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_regstat.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_regstat.php';
require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php';
$this->renderCartesianPlotArea(); $this->renderCartesianPlotArea();
@ -775,6 +748,7 @@ class JpGraph
break; break;
default: default:
$this->graph = null; $this->graph = null;
return false; return false;
} }
} }
@ -782,10 +756,10 @@ class JpGraph
$this->renderLegend(); $this->renderLegend();
$this->graph->Stroke($outputDestination); $this->graph->Stroke($outputDestination);
return true; return true;
} }
public function render($outputDestination) public function render($outputDestination)
{ {
self::$plotColour = 0; self::$plotColour = 0;
@ -796,7 +770,7 @@ class JpGraph
if ($groupCount == 1) { if ($groupCount == 1) {
$chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType();
} else { } else {
$chartTypes = array(); $chartTypes = [];
for ($i = 0; $i < $groupCount; ++$i) { for ($i = 0; $i < $groupCount; ++$i) {
$chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType();
} }
@ -805,6 +779,7 @@ class JpGraph
$chartType = array_pop($chartTypes); $chartType = array_pop($chartTypes);
} elseif (count($chartTypes) == 0) { } elseif (count($chartTypes) == 0) {
echo 'Chart is not yet implemented<br />'; echo 'Chart is not yet implemented<br />';
return false; return false;
} else { } else {
return $this->renderCombinationChart($groupCount, $dimensions, $outputDestination); return $this->renderCombinationChart($groupCount, $dimensions, $outputDestination);
@ -861,22 +836,23 @@ class JpGraph
$this->renderStockChart($groupCount, $dimensions); $this->renderStockChart($groupCount, $dimensions);
break; break;
default: default:
echo $chartType.' is not yet implemented<br />'; echo $chartType . ' is not yet implemented<br />';
return false; return false;
} }
$this->renderLegend(); $this->renderLegend();
$this->graph->Stroke($outputDestination); $this->graph->Stroke($outputDestination);
return true; return true;
} }
/** /**
* Create a new jpgraph * Create a new jpgraph
*/ */
public function __construct(\PhpSpreadsheet\Chart $chart) public function __construct(\PhpSpreadsheet\Chart $chart)
{ {
$this->graph = null; $this->graph = null;
$this->chart = $chart; $this->chart = $chart;
} }
} }

View File

@ -26,7 +26,6 @@ namespace PhpSpreadsheet\Chart;
*/ */
class Title class Title
{ {
/** /**
* Title Caption * Title Caption
* *

View File

@ -64,7 +64,7 @@ class Comment implements IComparable
/** /**
* Visible * Visible
* *
* @var boolean * @var bool
*/ */
private $visible = false; private $visible = false;
@ -97,8 +97,8 @@ class Comment implements IComparable
public function __construct() public function __construct()
{ {
// Initialise variables // Initialise variables
$this->author = 'Author'; $this->author = 'Author';
$this->text = new RichText(); $this->text = new RichText();
$this->fillColor = new Style\Color('FFFFFFE1'); $this->fillColor = new Style\Color('FFFFFFE1');
$this->alignment = Style\Alignment::HORIZONTAL_GENERAL; $this->alignment = Style\Alignment::HORIZONTAL_GENERAL;
} }
@ -122,6 +122,7 @@ class Comment implements IComparable
public function setAuthor($pValue = '') public function setAuthor($pValue = '')
{ {
$this->author = $pValue; $this->author = $pValue;
return $this; return $this;
} }
@ -144,6 +145,7 @@ class Comment implements IComparable
public function setText(RichText $pValue) public function setText(RichText $pValue)
{ {
$this->text = $pValue; $this->text = $pValue;
return $this; return $this;
} }
@ -166,6 +168,7 @@ class Comment implements IComparable
public function setWidth($value = '96pt') public function setWidth($value = '96pt')
{ {
$this->width = $value; $this->width = $value;
return $this; return $this;
} }
@ -188,6 +191,7 @@ class Comment implements IComparable
public function setHeight($value = '55.5pt') public function setHeight($value = '55.5pt')
{ {
$this->height = $value; $this->height = $value;
return $this; return $this;
} }
@ -210,6 +214,7 @@ class Comment implements IComparable
public function setMarginLeft($value = '59.25pt') public function setMarginLeft($value = '59.25pt')
{ {
$this->marginLeft = $value; $this->marginLeft = $value;
return $this; return $this;
} }
@ -232,13 +237,14 @@ class Comment implements IComparable
public function setMarginTop($value = '1.5pt') public function setMarginTop($value = '1.5pt')
{ {
$this->marginTop = $value; $this->marginTop = $value;
return $this; return $this;
} }
/** /**
* Is the comment visible by default? * Is the comment visible by default?
* *
* @return boolean * @return bool
*/ */
public function getVisible() public function getVisible()
{ {
@ -248,12 +254,13 @@ class Comment implements IComparable
/** /**
* Set comment default visibility * Set comment default visibility
* *
* @param boolean $value * @param bool $value
* @return Comment * @return Comment
*/ */
public function setVisible($value = false) public function setVisible($value = false)
{ {
$this->visible = $value; $this->visible = $value;
return $this; return $this;
} }
@ -276,6 +283,7 @@ class Comment implements IComparable
public function setAlignment($pValue = Style\Alignment::HORIZONTAL_GENERAL) public function setAlignment($pValue = Style\Alignment::HORIZONTAL_GENERAL)
{ {
$this->alignment = $pValue; $this->alignment = $pValue;
return $this; return $this;
} }

View File

@ -29,9 +29,9 @@ class Properties
/** constants */ /** constants */
const PROPERTY_TYPE_BOOLEAN = 'b'; const PROPERTY_TYPE_BOOLEAN = 'b';
const PROPERTY_TYPE_INTEGER = 'i'; const PROPERTY_TYPE_INTEGER = 'i';
const PROPERTY_TYPE_FLOAT = 'f'; const PROPERTY_TYPE_FLOAT = 'f';
const PROPERTY_TYPE_DATE = 'd'; const PROPERTY_TYPE_DATE = 'd';
const PROPERTY_TYPE_STRING = 's'; const PROPERTY_TYPE_STRING = 's';
const PROPERTY_TYPE_UNKNOWN = 'u'; const PROPERTY_TYPE_UNKNOWN = 'u';
/** /**
@ -116,8 +116,7 @@ class Properties
* *
* @var string * @var string
*/ */
private $customProperties = array(); private $customProperties = [];
/** /**
* Create a new Document Properties instance * Create a new Document Properties instance
@ -126,7 +125,7 @@ class Properties
{ {
// Initialise values // Initialise values
$this->lastModifiedBy = $this->creator; $this->lastModifiedBy = $this->creator;
$this->created = time(); $this->created = time();
$this->modified = time(); $this->modified = time();
} }
@ -149,6 +148,7 @@ class Properties
public function setCreator($pValue = '') public function setCreator($pValue = '')
{ {
$this->creator = $pValue; $this->creator = $pValue;
return $this; return $this;
} }
@ -171,6 +171,7 @@ class Properties
public function setLastModifiedBy($pValue = '') public function setLastModifiedBy($pValue = '')
{ {
$this->lastModifiedBy = $pValue; $this->lastModifiedBy = $pValue;
return $this; return $this;
} }
@ -203,6 +204,7 @@ class Properties
} }
$this->created = $pValue; $this->created = $pValue;
return $this; return $this;
} }
@ -235,6 +237,7 @@ class Properties
} }
$this->modified = $pValue; $this->modified = $pValue;
return $this; return $this;
} }
@ -257,6 +260,7 @@ class Properties
public function setTitle($pValue = '') public function setTitle($pValue = '')
{ {
$this->title = $pValue; $this->title = $pValue;
return $this; return $this;
} }
@ -279,6 +283,7 @@ class Properties
public function setDescription($pValue = '') public function setDescription($pValue = '')
{ {
$this->description = $pValue; $this->description = $pValue;
return $this; return $this;
} }
@ -301,6 +306,7 @@ class Properties
public function setSubject($pValue = '') public function setSubject($pValue = '')
{ {
$this->subject = $pValue; $this->subject = $pValue;
return $this; return $this;
} }
@ -323,6 +329,7 @@ class Properties
public function setKeywords($pValue = '') public function setKeywords($pValue = '')
{ {
$this->keywords = $pValue; $this->keywords = $pValue;
return $this; return $this;
} }
@ -345,6 +352,7 @@ class Properties
public function setCategory($pValue = '') public function setCategory($pValue = '')
{ {
$this->category = $pValue; $this->category = $pValue;
return $this; return $this;
} }
@ -367,6 +375,7 @@ class Properties
public function setCompany($pValue = '') public function setCompany($pValue = '')
{ {
$this->company = $pValue; $this->company = $pValue;
return $this; return $this;
} }
@ -389,6 +398,7 @@ class Properties
public function setManager($pValue = '') public function setManager($pValue = '')
{ {
$this->manager = $pValue; $this->manager = $pValue;
return $this; return $this;
} }
@ -406,7 +416,7 @@ class Properties
* Check if a Custom Property is defined * Check if a Custom Property is defined
* *
* @param string $propertyName * @param string $propertyName
* @return boolean * @return bool
*/ */
public function isCustomPropertySet($propertyName) public function isCustomPropertySet($propertyName)
{ {
@ -454,11 +464,11 @@ class Properties
*/ */
public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null) public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null)
{ {
if (($propertyType === null) || (!in_array($propertyType, array(self::PROPERTY_TYPE_INTEGER, if (($propertyType === null) || (!in_array($propertyType, [self::PROPERTY_TYPE_INTEGER,
self::PROPERTY_TYPE_FLOAT, self::PROPERTY_TYPE_FLOAT,
self::PROPERTY_TYPE_STRING, self::PROPERTY_TYPE_STRING,
self::PROPERTY_TYPE_DATE, self::PROPERTY_TYPE_DATE,
self::PROPERTY_TYPE_BOOLEAN)))) { self::PROPERTY_TYPE_BOOLEAN, ]))) {
if ($propertyValue === null) { if ($propertyValue === null) {
$propertyType = self::PROPERTY_TYPE_STRING; $propertyType = self::PROPERTY_TYPE_STRING;
} elseif (is_float($propertyValue)) { } elseif (is_float($propertyValue)) {
@ -472,10 +482,11 @@ class Properties
} }
} }
$this->customProperties[$propertyName] = array( $this->customProperties[$propertyName] = [
'value' => $propertyValue, 'value' => $propertyValue,
'type' => $propertyType 'type' => $propertyType,
); ];
return $this; return $this;
} }
@ -550,6 +561,7 @@ class Properties
return $propertyValue; return $propertyValue;
break; break;
} }
return $propertyValue; return $propertyValue;
} }
@ -603,6 +615,7 @@ class Properties
return self::PROPERTY_TYPE_UNKNOWN; return self::PROPERTY_TYPE_UNKNOWN;
break; break;
} }
return self::PROPERTY_TYPE_UNKNOWN; return self::PROPERTY_TYPE_UNKNOWN;
} }
} }

View File

@ -29,21 +29,21 @@ class Security
/** /**
* LockRevision * LockRevision
* *
* @var boolean * @var bool
*/ */
private $lockRevision = false; private $lockRevision = false;
/** /**
* LockStructure * LockStructure
* *
* @var boolean * @var bool
*/ */
private $lockStructure = false; private $lockStructure = false;
/** /**
* LockWindows * LockWindows
* *
* @var boolean * @var bool
*/ */
private $lockWindows = false; private $lockWindows = false;
@ -71,7 +71,7 @@ class Security
/** /**
* Is some sort of document security enabled? * Is some sort of document security enabled?
* *
* @return boolean * @return bool
*/ */
public function isSecurityEnabled() public function isSecurityEnabled()
{ {
@ -83,7 +83,7 @@ class Security
/** /**
* Get LockRevision * Get LockRevision
* *
* @return boolean * @return bool
*/ */
public function getLockRevision() public function getLockRevision()
{ {
@ -93,19 +93,20 @@ class Security
/** /**
* Set LockRevision * Set LockRevision
* *
* @param boolean $pValue * @param bool $pValue
* @return Security * @return Security
*/ */
public function setLockRevision($pValue = false) public function setLockRevision($pValue = false)
{ {
$this->lockRevision = $pValue; $this->lockRevision = $pValue;
return $this; return $this;
} }
/** /**
* Get LockStructure * Get LockStructure
* *
* @return boolean * @return bool
*/ */
public function getLockStructure() public function getLockStructure()
{ {
@ -115,19 +116,20 @@ class Security
/** /**
* Set LockStructure * Set LockStructure
* *
* @param boolean $pValue * @param bool $pValue
* @return Security * @return Security
*/ */
public function setLockStructure($pValue = false) public function setLockStructure($pValue = false)
{ {
$this->lockStructure = $pValue; $this->lockStructure = $pValue;
return $this; return $this;
} }
/** /**
* Get LockWindows * Get LockWindows
* *
* @return boolean * @return bool
*/ */
public function getLockWindows() public function getLockWindows()
{ {
@ -137,12 +139,13 @@ class Security
/** /**
* Set LockWindows * Set LockWindows
* *
* @param boolean $pValue * @param bool $pValue
* @return Security * @return Security
*/ */
public function setLockWindows($pValue = false) public function setLockWindows($pValue = false)
{ {
$this->lockWindows = $pValue; $this->lockWindows = $pValue;
return $this; return $this;
} }
@ -160,7 +163,7 @@ class Security
* Set RevisionsPassword * Set RevisionsPassword
* *
* @param string $pValue * @param string $pValue
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
* @return Security * @return Security
*/ */
public function setRevisionsPassword($pValue = '', $pAlreadyHashed = false) public function setRevisionsPassword($pValue = '', $pAlreadyHashed = false)
@ -169,6 +172,7 @@ class Security
$pValue = \PhpSpreadsheet\Shared\PasswordHasher::hashPassword($pValue); $pValue = \PhpSpreadsheet\Shared\PasswordHasher::hashPassword($pValue);
} }
$this->revisionsPassword = $pValue; $this->revisionsPassword = $pValue;
return $this; return $this;
} }
@ -186,7 +190,7 @@ class Security
* Set WorkbookPassword * Set WorkbookPassword
* *
* @param string $pValue * @param string $pValue
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
* @return Security * @return Security
*/ */
public function setWorkbookPassword($pValue = '', $pAlreadyHashed = false) public function setWorkbookPassword($pValue = '', $pAlreadyHashed = false)
@ -195,6 +199,7 @@ class Security
$pValue = \PhpSpreadsheet\Shared\PasswordHasher::hashPassword($pValue); $pValue = \PhpSpreadsheet\Shared\PasswordHasher::hashPassword($pValue);
} }
$this->workbookPassword = $pValue; $this->workbookPassword = $pValue;
return $this; return $this;
} }

View File

@ -119,12 +119,11 @@ class HashTable
/** /**
* Clear HashTable * Clear HashTable
*
*/ */
public function clear() public function clear()
{ {
$this->items = array(); $this->items = [];
$this->keyMap = array(); $this->keyMap = [];
} }
/** /**
@ -153,7 +152,6 @@ class HashTable
* *
* @param int $pIndex * @param int $pIndex
* @return IComparable * @return IComparable
*
*/ */
public function getByIndex($pIndex = 0) public function getByIndex($pIndex = 0)
{ {
@ -169,7 +167,6 @@ class HashTable
* *
* @param string $pHashCode * @param string $pHashCode
* @return IComparable * @return IComparable
*
*/ */
public function getByHashCode($pHashCode = '') public function getByHashCode($pHashCode = '')
{ {

View File

@ -557,7 +557,7 @@ class HTML
protected $subscript = false; protected $subscript = false;
protected $strikethrough = false; protected $strikethrough = false;
protected $startTagCallbacks = array( protected $startTagCallbacks = [
'font' => 'startFontTag', 'font' => 'startFontTag',
'b' => 'startBoldTag', 'b' => 'startBoldTag',
'strong' => 'startBoldTag', 'strong' => 'startBoldTag',
@ -568,9 +568,9 @@ class HTML
'del' => 'startStrikethruTag', 'del' => 'startStrikethruTag',
'sup' => 'startSuperscriptTag', 'sup' => 'startSuperscriptTag',
'sub' => 'startSubscriptTag', 'sub' => 'startSubscriptTag',
); ];
protected $endTagCallbacks = array( protected $endTagCallbacks = [
'font' => 'endFontTag', 'font' => 'endFontTag',
'b' => 'endBoldTag', 'b' => 'endBoldTag',
'strong' => 'endBoldTag', 'strong' => 'endBoldTag',
@ -589,9 +589,9 @@ class HTML
'h4' => 'breakTag', 'h4' => 'breakTag',
'h5' => 'breakTag', 'h5' => 'breakTag',
'h6' => 'breakTag', 'h6' => 'breakTag',
); ];
protected $stack = array(); protected $stack = [];
protected $stringData = ''; protected $stringData = '';
@ -602,7 +602,7 @@ class HTML
$this->face = $this->size = $this->color = null; $this->face = $this->size = $this->color = null;
$this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false; $this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false;
$this->stack = array(); $this->stack = [];
$this->stringData = ''; $this->stringData = '';
} }
@ -612,7 +612,7 @@ class HTML
$this->initialise(); $this->initialise();
// Create a new DOM object // Create a new DOM object
$dom = new \DOMDocument; $dom = new \DOMDocument();
// Load the HTML file into the DOM object // Load the HTML file into the DOM object
// Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup // Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup
$loaded = @$dom->loadHTML($html); $loaded = @$dom->loadHTML($html);
@ -687,6 +687,7 @@ class HTML
foreach ($values[0] as &$value) { foreach ($values[0] as &$value) {
$value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
} }
return implode($values[0]); return implode($values[0]);
} }
@ -801,7 +802,7 @@ class HTML
if (isset($callbacks[$callbackTag])) { if (isset($callbacks[$callbackTag])) {
$elementHandler = $callbacks[$callbackTag]; $elementHandler = $callbacks[$callbackTag];
if (method_exists($this, $elementHandler)) { if (method_exists($this, $elementHandler)) {
call_user_func(array($this, $elementHandler), $element); call_user_func([$this, $elementHandler], $element);
} }
} }
} }

View File

@ -30,22 +30,20 @@ class IOFactory
* Search locations * Search locations
* *
* @var array * @var array
* @access private
* @static * @static
*/ */
private static $searchLocations = array( private static $searchLocations = [
array( 'type' => 'IWriter', 'path' => 'PhpSpreadsheet/Writer/{0}.php', 'class' => '\\PhpSpreadsheet\\Writer\\{0}' ), ['type' => 'IWriter', 'path' => 'PhpSpreadsheet/Writer/{0}.php', 'class' => '\\PhpSpreadsheet\\Writer\\{0}'],
array( 'type' => 'IReader', 'path' => 'PhpSpreadsheet/Reader/{0}.php', 'class' => '\\PhpSpreadsheet\\Reader\\{0}' ) ['type' => 'IReader', 'path' => 'PhpSpreadsheet/Reader/{0}.php', 'class' => '\\PhpSpreadsheet\\Reader\\{0}'],
); ];
/** /**
* Autoresolve classes * Autoresolve classes
* *
* @var array * @var array
* @access private
* @static * @static
*/ */
private static $autoResolveClasses = array( private static $autoResolveClasses = [
'Excel2007', 'Excel2007',
'Excel5', 'Excel5',
'Excel2003XML', 'Excel2003XML',
@ -54,7 +52,7 @@ class IOFactory
'Gnumeric', 'Gnumeric',
'HTML', 'HTML',
'CSV', 'CSV',
); ];
/** /**
* Private constructor for IOFactory * Private constructor for IOFactory
@ -67,7 +65,6 @@ class IOFactory
* Get search locations * Get search locations
* *
* @static * @static
* @access public
* @return array * @return array
*/ */
public static function getSearchLocations() public static function getSearchLocations()
@ -79,7 +76,6 @@ class IOFactory
* Set search locations * Set search locations
* *
* @static * @static
* @access public
* @param array $value * @param array $value
* @throws Reader\Exception * @throws Reader\Exception
*/ */
@ -96,25 +92,23 @@ class IOFactory
* Add search location * Add search location
* *
* @static * @static
* @access public
* @param string $type Example: IWriter * @param string $type Example: IWriter
* @param string $location Example: PhpSpreadsheet/Writer/{0}.php * @param string $location Example: PhpSpreadsheet/Writer/{0}.php
* @param string $classname Example: Writer\{0} * @param string $classname Example: Writer\{0}
*/ */
public static function addSearchLocation($type = '', $location = '', $classname = '') public static function addSearchLocation($type = '', $location = '', $classname = '')
{ {
self::$searchLocations[] = array( 'type' => $type, 'path' => $location, 'class' => $classname ); self::$searchLocations[] = ['type' => $type, 'path' => $location, 'class' => $classname];
} }
/** /**
* Create Writer\IWriter * Create Writer\IWriter
* *
* @static * @static
* @access public
* @param Spreadsheet $spreadsheet * @param Spreadsheet $spreadsheet
* @param string $writerType Example: Excel2007 * @param string $writerType Example: Excel2007
* @return Writer\IWriter
* @throws Writer\Exception * @throws Writer\Exception
* @return Writer\IWriter
*/ */
public static function createWriter(Spreadsheet $spreadsheet, $writerType = '') public static function createWriter(Spreadsheet $spreadsheet, $writerType = '')
{ {
@ -141,10 +135,9 @@ class IOFactory
* Create Reader\IReader * Create Reader\IReader
* *
* @static * @static
* @access public
* @param string $readerType Example: Excel2007 * @param string $readerType Example: Excel2007
* @return Reader\IReader
* @throws Reader\Exception * @throws Reader\Exception
* @return Reader\IReader
*/ */
public static function createReader($readerType = '') public static function createReader($readerType = '')
{ {
@ -171,14 +164,14 @@ class IOFactory
* Loads Spreadsheet from file using automatic Reader\IReader resolution * Loads Spreadsheet from file using automatic Reader\IReader resolution
* *
* @static * @static
* @access public
* @param string $pFilename The name of the spreadsheet file * @param string $pFilename The name of the spreadsheet file
* @return Spreadsheet
* @throws Reader\Exception * @throws Reader\Exception
* @return Spreadsheet
*/ */
public static function load($pFilename) public static function load($pFilename)
{ {
$reader = self::createReaderForFile($pFilename); $reader = self::createReaderForFile($pFilename);
return $reader->load($pFilename); return $reader->load($pFilename);
} }
@ -186,10 +179,9 @@ class IOFactory
* Identify file type using automatic Reader\IReader resolution * Identify file type using automatic Reader\IReader resolution
* *
* @static * @static
* @access public
* @param string $pFilename The name of the spreadsheet file to identify * @param string $pFilename The name of the spreadsheet file to identify
* @return string
* @throws Reader\Exception * @throws Reader\Exception
* @return string
*/ */
public static function identify($pFilename) public static function identify($pFilename)
{ {
@ -197,6 +189,7 @@ class IOFactory
$className = get_class($reader); $className = get_class($reader);
$classType = explode('\\', $className); $classType = explode('\\', $className);
unset($reader); unset($reader);
return array_pop($classType); return array_pop($classType);
} }
@ -204,10 +197,9 @@ class IOFactory
* Create Reader\IReader for file using automatic Reader\IReader resolution * Create Reader\IReader for file using automatic Reader\IReader resolution
* *
* @static * @static
* @access public
* @param string $pFilename The name of the spreadsheet file * @param string $pFilename The name of the spreadsheet file
* @return Reader\IReader
* @throws Reader\Exception * @throws Reader\Exception
* @return Reader\IReader
*/ */
public static function createReaderForFile($pFilename) public static function createReaderForFile($pFilename)
{ {

View File

@ -81,11 +81,11 @@ class NamedRange
} }
// Set local members // Set local members
$this->name = $pName; $this->name = $pName;
$this->worksheet = $pWorksheet; $this->worksheet = $pWorksheet;
$this->range = $pRange; $this->range = $pRange;
$this->localOnly = $pLocalOnly; $this->localOnly = $pLocalOnly;
$this->scope = ($pLocalOnly == true) ? (($pScope == null) ? $pWorksheet : $pScope) : null; $this->scope = ($pLocalOnly == true) ? (($pScope == null) ? $pWorksheet : $pScope) : null;
} }
/** /**
@ -124,6 +124,7 @@ class NamedRange
$newTitle = $this->name; $newTitle = $this->name;
ReferenceHelper::getInstance()->updateNamedFormulas($this->worksheet->getParent(), $oldTitle, $newTitle); ReferenceHelper::getInstance()->updateNamedFormulas($this->worksheet->getParent(), $oldTitle, $newTitle);
} }
return $this; return $this;
} }
@ -148,6 +149,7 @@ class NamedRange
if ($value !== null) { if ($value !== null) {
$this->worksheet = $value; $this->worksheet = $value;
} }
return $this; return $this;
} }
@ -172,6 +174,7 @@ class NamedRange
if ($value !== null) { if ($value !== null) {
$this->range = $value; $this->range = $value;
} }
return $this; return $this;
} }
@ -195,6 +198,7 @@ class NamedRange
{ {
$this->localOnly = $value; $this->localOnly = $value;
$this->scope = $value ? $this->worksheet : null; $this->scope = $value ? $this->worksheet : null;
return $this; return $this;
} }
@ -218,6 +222,7 @@ class NamedRange
{ {
$this->scope = $value; $this->scope = $value;
$this->localOnly = ($value == null) ? false : true; $this->localOnly = ($value == null) ? false : true;
return $this; return $this;
} }

View File

@ -31,7 +31,7 @@ abstract class BaseReader implements IReader
* Identifies whether the Reader should only read data values for cells, and ignore any formatting information; * Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
* or whether it should read both data and formatting * or whether it should read both data and formatting
* *
* @var boolean * @var bool
*/ */
protected $readDataOnly = false; protected $readDataOnly = false;
@ -40,7 +40,7 @@ abstract class BaseReader implements IReader
* Identifies whether the Reader should read data values for cells all cells, or should ignore cells containing * Identifies whether the Reader should read data values for cells all cells, or should ignore cells containing
* null value or empty string * null value or empty string
* *
* @var boolean * @var bool
*/ */
protected $readEmptyCells = true; protected $readEmptyCells = true;
@ -48,7 +48,7 @@ abstract class BaseReader implements IReader
* Read charts that are defined in the workbook? * Read charts that are defined in the workbook?
* Identifies whether the Reader should read the definitions for any charts that exist in the workbook; * Identifies whether the Reader should read the definitions for any charts that exist in the workbook;
* *
* @var boolean * @var bool
*/ */
protected $includeCharts = false; protected $includeCharts = false;
@ -69,13 +69,12 @@ abstract class BaseReader implements IReader
protected $fileHandle = null; protected $fileHandle = null;
/** /**
* Read data only? * Read data only?
* If this is true, then the Reader will only read data values for cells, it will not read any formatting information. * If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
* If false (the default) it will read data and formatting. * If false (the default) it will read data and formatting.
* *
* @return boolean * @return bool
*/ */
public function getReadDataOnly() public function getReadDataOnly()
{ {
@ -87,13 +86,14 @@ abstract class BaseReader implements IReader
* Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information. * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
* Set to false (the default) to advise the Reader to read both data and formatting for cells. * Set to false (the default) to advise the Reader to read both data and formatting for cells.
* *
* @param boolean $pValue * @param bool $pValue
* *
* @return IReader * @return IReader
*/ */
public function setReadDataOnly($pValue = false) public function setReadDataOnly($pValue = false)
{ {
$this->readDataOnly = (boolean) $pValue; $this->readDataOnly = (boolean) $pValue;
return $this; return $this;
} }
@ -102,7 +102,7 @@ abstract class BaseReader implements IReader
* If this is true (the default), then the Reader will read data values for all cells, irrespective of value. * If this is true (the default), then the Reader will read data values for all cells, irrespective of value.
* If false it will not read data for cells containing a null value or an empty string. * If false it will not read data for cells containing a null value or an empty string.
* *
* @return boolean * @return bool
*/ */
public function getReadEmptyCells() public function getReadEmptyCells()
{ {
@ -114,13 +114,14 @@ abstract class BaseReader implements IReader
* Set to true (the default) to advise the Reader read data values for all cells, irrespective of value. * Set to true (the default) to advise the Reader read data values for all cells, irrespective of value.
* Set to false to advise the Reader to ignore cells containing a null value or an empty string. * Set to false to advise the Reader to ignore cells containing a null value or an empty string.
* *
* @param boolean $pValue * @param bool $pValue
* *
* @return IReader * @return IReader
*/ */
public function setReadEmptyCells($pValue = true) public function setReadEmptyCells($pValue = true)
{ {
$this->readEmptyCells = (boolean) $pValue; $this->readEmptyCells = (boolean) $pValue;
return $this; return $this;
} }
@ -130,7 +131,7 @@ abstract class BaseReader implements IReader
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* If false (the default) it will ignore any charts defined in the workbook file. * If false (the default) it will ignore any charts defined in the workbook file.
* *
* @return boolean * @return bool
*/ */
public function getIncludeCharts() public function getIncludeCharts()
{ {
@ -143,13 +144,14 @@ abstract class BaseReader implements IReader
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* Set to false (the default) to discard charts. * Set to false (the default) to discard charts.
* *
* @param boolean $pValue * @param bool $pValue
* *
* @return IReader * @return IReader
*/ */
public function setIncludeCharts($pValue = false) public function setIncludeCharts($pValue = false)
{ {
$this->includeCharts = (boolean) $pValue; $this->includeCharts = (boolean) $pValue;
return $this; return $this;
} }
@ -180,7 +182,8 @@ abstract class BaseReader implements IReader
return $this->setLoadAllSheets(); return $this->setLoadAllSheets();
} }
$this->loadSheetsOnly = is_array($value) ? $value : array($value); $this->loadSheetsOnly = is_array($value) ? $value : [$value];
return $this; return $this;
} }
@ -193,6 +196,7 @@ abstract class BaseReader implements IReader
public function setLoadAllSheets() public function setLoadAllSheets()
{ {
$this->loadSheetsOnly = null; $this->loadSheetsOnly = null;
return $this; return $this;
} }
@ -215,6 +219,7 @@ abstract class BaseReader implements IReader
public function setReadFilter(IReadFilter $pValue) public function setReadFilter(IReadFilter $pValue)
{ {
$this->readFilter = $pValue; $this->readFilter = $pValue;
return $this; return $this;
} }
@ -229,13 +234,13 @@ abstract class BaseReader implements IReader
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename) || !is_readable($pFilename)) { if (!file_exists($pFilename) || !is_readable($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
// Open file // Open file
$this->fileHandle = fopen($pFilename, 'r'); $this->fileHandle = fopen($pFilename, 'r');
if ($this->fileHandle === false) { if ($this->fileHandle === false) {
throw new Exception("Could not open file " . $pFilename . " for reading."); throw new Exception('Could not open file ' . $pFilename . ' for reading.');
} }
} }
@ -243,8 +248,8 @@ abstract class BaseReader implements IReader
* Can the current IReader read the file? * Can the current IReader read the file?
* *
* @param string $pFilename * @param string $pFilename
* @return boolean
* @throws Exception * @throws Exception
* @return bool
*/ */
public function canRead($pFilename) public function canRead($pFilename)
{ {
@ -257,6 +262,7 @@ abstract class BaseReader implements IReader
$readable = $this->isValidFormat(); $readable = $this->isValidFormat();
fclose($this->fileHandle); fclose($this->fileHandle);
return $readable; return $readable;
} }
@ -272,6 +278,7 @@ abstract class BaseReader implements IReader
if (preg_match($pattern, $xml)) { if (preg_match($pattern, $xml)) {
throw new Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); throw new Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks');
} }
return $xml; return $xml;
} }

View File

@ -31,7 +31,6 @@ class CSV extends BaseReader implements IReader
/** /**
* Input encoding * Input encoding
* *
* @access private
* @var string * @var string
*/ */
private $inputEncoding = 'UTF-8'; private $inputEncoding = 'UTF-8';
@ -39,7 +38,6 @@ class CSV extends BaseReader implements IReader
/** /**
* Delimiter * Delimiter
* *
* @access private
* @var string * @var string
*/ */
private $delimiter = ','; private $delimiter = ',';
@ -47,7 +45,6 @@ class CSV extends BaseReader implements IReader
/** /**
* Enclosure * Enclosure
* *
* @access private
* @var string * @var string
*/ */
private $enclosure = '"'; private $enclosure = '"';
@ -55,7 +52,6 @@ class CSV extends BaseReader implements IReader
/** /**
* Sheet index to read * Sheet index to read
* *
* @access private
* @var int * @var int
*/ */
private $sheetIndex = 0; private $sheetIndex = 0;
@ -63,7 +59,6 @@ class CSV extends BaseReader implements IReader
/** /**
* Load rows contiguously * Load rows contiguously
* *
* @access private
* @var int * @var int
*/ */
private $contiguous = false; private $contiguous = false;
@ -75,7 +70,6 @@ class CSV extends BaseReader implements IReader
*/ */
private $contiguousRow = -1; private $contiguousRow = -1;
/** /**
* Create a new CSV Reader instance * Create a new CSV Reader instance
*/ */
@ -87,7 +81,7 @@ class CSV extends BaseReader implements IReader
/** /**
* Validate that the current file is a CSV file * Validate that the current file is a CSV file
* *
* @return boolean * @return bool
*/ */
protected function isValidFormat() protected function isValidFormat()
{ {
@ -102,6 +96,7 @@ class CSV extends BaseReader implements IReader
public function setInputEncoding($pValue = 'UTF-8') public function setInputEncoding($pValue = 'UTF-8')
{ {
$this->inputEncoding = $pValue; $this->inputEncoding = $pValue;
return $this; return $this;
} }
@ -117,7 +112,6 @@ class CSV extends BaseReader implements IReader
/** /**
* Move filepointer past any BOM marker * Move filepointer past any BOM marker
*
*/ */
protected function skipBOM() protected function skipBOM()
{ {
@ -151,7 +145,6 @@ class CSV extends BaseReader implements IReader
/** /**
* Identify any separator that is explicitly set in the file * Identify any separator that is explicitly set in the file
*
*/ */
protected function checkSeparator() protected function checkSeparator()
{ {
@ -162,8 +155,10 @@ class CSV extends BaseReader implements IReader
if ((strlen(trim($line, "\r\n")) == 5) && (stripos($line, 'sep=') === 0)) { if ((strlen(trim($line, "\r\n")) == 5) && (stripos($line, 'sep=') === 0)) {
$this->delimiter = substr($line, 4, 1); $this->delimiter = substr($line, 4, 1);
return; return;
} }
return $this->skipBOM(); return $this->skipBOM();
} }
@ -179,7 +174,7 @@ class CSV extends BaseReader implements IReader
$this->openFile($pFilename); $this->openFile($pFilename);
if (!$this->isValidFormat()) { if (!$this->isValidFormat()) {
fclose($this->fileHandle); fclose($this->fileHandle);
throw new Exception($pFilename . " is an Invalid Spreadsheet file."); throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
} }
$fileHandle = $this->fileHandle; $fileHandle = $this->fileHandle;
@ -187,9 +182,9 @@ class CSV extends BaseReader implements IReader
$this->skipBOM(); $this->skipBOM();
$this->checkSeparator(); $this->checkSeparator();
$escapeEnclosures = array( "\\" . $this->enclosure, $this->enclosure . $this->enclosure ); $escapeEnclosures = ['\\' . $this->enclosure, $this->enclosure . $this->enclosure];
$worksheetInfo = array(); $worksheetInfo = [];
$worksheetInfo[0]['worksheetName'] = 'Worksheet'; $worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0; $worksheetInfo[0]['lastColumnIndex'] = 0;
@ -198,7 +193,7 @@ class CSV extends BaseReader implements IReader
// Loop through each line of the file in turn // Loop through each line of the file in turn
while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure)) !== false) { while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure)) !== false) {
$worksheetInfo[0]['totalRows']++; ++$worksheetInfo[0]['totalRows'];
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1); $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1);
} }
@ -215,8 +210,8 @@ class CSV extends BaseReader implements IReader
* Loads Spreadsheet from file * Loads Spreadsheet from file
* *
* @param string $pFilename * @param string $pFilename
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function load($pFilename) public function load($pFilename)
{ {
@ -232,8 +227,8 @@ class CSV extends BaseReader implements IReader
* *
* @param string $pFilename * @param string $pFilename
* @param Spreadsheet $spreadsheet * @param Spreadsheet $spreadsheet
* @return Spreadsheet
* @throws Exception * @throws Exception
* @return Spreadsheet
*/ */
public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
{ {
@ -244,7 +239,7 @@ class CSV extends BaseReader implements IReader
$this->openFile($pFilename); $this->openFile($pFilename);
if (!$this->isValidFormat()) { if (!$this->isValidFormat()) {
fclose($this->fileHandle); fclose($this->fileHandle);
throw new Exception($pFilename . " is an Invalid Spreadsheet file."); throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
} }
$fileHandle = $this->fileHandle; $fileHandle = $this->fileHandle;
@ -258,9 +253,9 @@ class CSV extends BaseReader implements IReader
} }
$sheet = $spreadsheet->setActiveSheetIndex($this->sheetIndex); $sheet = $spreadsheet->setActiveSheetIndex($this->sheetIndex);
$escapeEnclosures = array( "\\" . $this->enclosure, $escapeEnclosures = ['\\' . $this->enclosure,
$this->enclosure . $this->enclosure $this->enclosure . $this->enclosure,
); ];
// Set our starting row based on whether we're in contiguous mode or not // Set our starting row based on whether we're in contiguous mode or not
$currentRow = 1; $currentRow = 1;
@ -321,6 +316,7 @@ class CSV extends BaseReader implements IReader
public function setDelimiter($pValue = ',') public function setDelimiter($pValue = ',')
{ {
$this->delimiter = $pValue; $this->delimiter = $pValue;
return $this; return $this;
} }
@ -346,13 +342,14 @@ class CSV extends BaseReader implements IReader
$pValue = '"'; $pValue = '"';
} }
$this->enclosure = $pValue; $this->enclosure = $pValue;
return $this; return $this;
} }
/** /**
* Get sheet index * Get sheet index
* *
* @return integer * @return int
*/ */
public function getSheetIndex() public function getSheetIndex()
{ {
@ -362,19 +359,20 @@ class CSV extends BaseReader implements IReader
/** /**
* Set sheet index * Set sheet index
* *
* @param integer $pValue Sheet index * @param int $pValue Sheet index
* @return CSV * @return CSV
*/ */
public function setSheetIndex($pValue = 0) public function setSheetIndex($pValue = 0)
{ {
$this->sheetIndex = $pValue; $this->sheetIndex = $pValue;
return $this; return $this;
} }
/** /**
* Set Contiguous * Set Contiguous
* *
* @param boolean $contiguous * @param bool $contiguous
*/ */
public function setContiguous($contiguous = false) public function setContiguous($contiguous = false)
{ {
@ -389,7 +387,7 @@ class CSV extends BaseReader implements IReader
/** /**
* Get Contiguous * Get Contiguous
* *
* @return boolean * @return bool
*/ */
public function getContiguous() public function getContiguous()
{ {

View File

@ -32,7 +32,7 @@ class DefaultReadFilter implements IReadFilter
* @param $column Column address (as a string value like "A", or "IV") * @param $column Column address (as a string value like "A", or "IV")
* @param $row Row number * @param $row Row number
* @param $worksheetName Optional worksheet name * @param $worksheetName Optional worksheet name
* @return boolean * @return bool
*/ */
public function readCell($column, $row, $worksheetName = '') public function readCell($column, $row, $worksheetName = '')
{ {

View File

@ -31,7 +31,7 @@ class Excel2003XML extends BaseReader implements IReader
* *
* @var array * @var array
*/ */
protected $styles = array(); protected $styles = [];
/** /**
* Character set used in the file * Character set used in the file
@ -48,13 +48,12 @@ class Excel2003XML extends BaseReader implements IReader
$this->readFilter = new DefaultReadFilter(); $this->readFilter = new DefaultReadFilter();
} }
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
* *
* @param string $pFilename * @param string $pFilename
* @return boolean
* @throws Exception * @throws Exception
* @return bool
*/ */
public function canRead($pFilename) public function canRead($pFilename)
{ {
@ -69,10 +68,10 @@ class Excel2003XML extends BaseReader implements IReader
// Rowset xmlns:z="#RowsetSchema" // Rowset xmlns:z="#RowsetSchema"
// //
$signature = array( $signature = [
'<?xml version="1.0"', '<?xml version="1.0"',
'<?mso-application progid="Excel.Sheet"?>' '<?mso-application progid="Excel.Sheet"?>',
); ];
// Open file // Open file
$this->openFile($pFilename); $this->openFile($pFilename);
@ -100,7 +99,6 @@ class Excel2003XML extends BaseReader implements IReader
return $valid; return $valid;
} }
/** /**
* Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object
* *
@ -111,13 +109,13 @@ class Excel2003XML extends BaseReader implements IReader
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
if (!$this->canRead($pFilename)) { if (!$this->canRead($pFilename)) {
throw new Exception($pFilename . " is an Invalid Spreadsheet file."); throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
} }
$worksheetNames = array(); $worksheetNames = [];
$xml = simplexml_load_string( $xml = simplexml_load_string(
$this->securityScan(file_get_contents($pFilename)), $this->securityScan(file_get_contents($pFilename)),
@ -135,7 +133,6 @@ class Excel2003XML extends BaseReader implements IReader
return $worksheetNames; return $worksheetNames;
} }
/** /**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
* *
@ -146,10 +143,10 @@ class Excel2003XML extends BaseReader implements IReader
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$worksheetInfo = array(); $worksheetInfo = [];
$xml = simplexml_load_string( $xml = simplexml_load_string(
$this->securityScan(file_get_contents($pFilename)), $this->securityScan(file_get_contents($pFilename)),
@ -163,7 +160,7 @@ class Excel2003XML extends BaseReader implements IReader
foreach ($xml_ss->Worksheet as $worksheet) { foreach ($xml_ss->Worksheet as $worksheet) {
$worksheet_ss = $worksheet->attributes($namespaces['ss']); $worksheet_ss = $worksheet->attributes($namespaces['ss']);
$tmpInfo = array(); $tmpInfo = [];
$tmpInfo['worksheetName'] = ''; $tmpInfo['worksheetName'] = '';
$tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnLetter'] = 'A';
$tmpInfo['lastColumnIndex'] = 0; $tmpInfo['lastColumnIndex'] = 0;
@ -210,13 +207,12 @@ class Excel2003XML extends BaseReader implements IReader
return $worksheetInfo; return $worksheetInfo;
} }
/** /**
* Loads PhpSpreadsheet from file * Loads PhpSpreadsheet from file
* *
* @param string $pFilename * @param string $pFilename
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function load($pFilename) public function load($pFilename)
{ {
@ -234,9 +230,11 @@ class Excel2003XML extends BaseReader implements IReader
foreach ($styleList as $style) { foreach ($styleList as $style) {
if ($styleAttributeValue == strtolower($style)) { if ($styleAttributeValue == strtolower($style)) {
$styleAttributeValue = $style; $styleAttributeValue = $style;
return true; return true;
} }
} }
return false; return false;
} }
@ -247,10 +245,11 @@ class Excel2003XML extends BaseReader implements IReader
*/ */
protected static function pixel2WidthUnits($pxs) protected static function pixel2WidthUnits($pxs)
{ {
$UNIT_OFFSET_MAP = array(0, 36, 73, 109, 146, 182, 219); $UNIT_OFFSET_MAP = [0, 36, 73, 109, 146, 182, 219];
$widthUnits = 256 * ($pxs / 7); $widthUnits = 256 * ($pxs / 7);
$widthUnits += $UNIT_OFFSET_MAP[($pxs % 7)]; $widthUnits += $UNIT_OFFSET_MAP[($pxs % 7)];
return $widthUnits; return $widthUnits;
} }
@ -264,6 +263,7 @@ class Excel2003XML extends BaseReader implements IReader
$pixels = ($widthUnits / 256) * 7; $pixels = ($widthUnits / 256) * 7;
$offsetWidthUnits = $widthUnits % 256; $offsetWidthUnits = $widthUnits % 256;
$pixels += round($offsetWidthUnits / (256 / 7)); $pixels += round($offsetWidthUnits / (256 / 7));
return $pixels; return $pixels;
} }
@ -277,46 +277,46 @@ class Excel2003XML extends BaseReader implements IReader
* *
* @param string $pFilename * @param string $pFilename
* @param \PhpSpreadsheet\Spreadsheet $spreadsheet * @param \PhpSpreadsheet\Spreadsheet $spreadsheet
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet)
{ {
$fromFormats = array('\-', '\ '); $fromFormats = ['\-', '\ '];
$toFormats = array('-', ' '); $toFormats = ['-', ' '];
$underlineStyles = array ( $underlineStyles = [
\PhpSpreadsheet\Style\Font::UNDERLINE_NONE, \PhpSpreadsheet\Style\Font::UNDERLINE_NONE,
\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE, \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE,
\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING, \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING,
\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE, \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE,
\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING,
); ];
$verticalAlignmentStyles = array ( $verticalAlignmentStyles = [
\PhpSpreadsheet\Style\Alignment::VERTICAL_BOTTOM, \PhpSpreadsheet\Style\Alignment::VERTICAL_BOTTOM,
\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP, \PhpSpreadsheet\Style\Alignment::VERTICAL_TOP,
\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, \PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
\PhpSpreadsheet\Style\Alignment::VERTICAL_JUSTIFY \PhpSpreadsheet\Style\Alignment::VERTICAL_JUSTIFY,
); ];
$horizontalAlignmentStyles = array ( $horizontalAlignmentStyles = [
\PhpSpreadsheet\Style\Alignment::HORIZONTAL_GENERAL, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_GENERAL,
\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT,
\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT,
\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER_CONTINUOUS, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER_CONTINUOUS,
\PhpSpreadsheet\Style\Alignment::HORIZONTAL_JUSTIFY \PhpSpreadsheet\Style\Alignment::HORIZONTAL_JUSTIFY,
); ];
$timezoneObj = new \DateTimeZone('Europe/London'); $timezoneObj = new \DateTimeZone('Europe/London');
$GMT = new \DateTimeZone('UTC'); $GMT = new \DateTimeZone('UTC');
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
if (!$this->canRead($pFilename)) { if (!$this->canRead($pFilename)) {
throw new Exception($pFilename . " is an Invalid Spreadsheet file."); throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
} }
$xml = simplexml_load_string( $xml = simplexml_load_string(
@ -403,14 +403,14 @@ class Excel2003XML extends BaseReader implements IReader
$style_ss = $style->attributes($namespaces['ss']); $style_ss = $style->attributes($namespaces['ss']);
$styleID = (string) $style_ss['ID']; $styleID = (string) $style_ss['ID'];
// echo 'Style ID = '.$styleID.'<br />'; // echo 'Style ID = '.$styleID.'<br />';
$this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : array(); $this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : [];
foreach ($style as $styleType => $styleData) { foreach ($style as $styleType => $styleData) {
$styleAttributes = $styleData->attributes($namespaces['ss']); $styleAttributes = $styleData->attributes($namespaces['ss']);
// echo $styleType.'<br />'; // echo $styleType.'<br />';
switch ($styleType) { switch ($styleType) {
case 'Alignment': case 'Alignment':
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
$styleAttributeValue = (string) $styleAttributeValue; $styleAttributeValue = (string) $styleAttributeValue;
switch ($styleAttributeKey) { switch ($styleAttributeKey) {
case 'Vertical': case 'Vertical':
@ -432,9 +432,9 @@ class Excel2003XML extends BaseReader implements IReader
case 'Borders': case 'Borders':
foreach ($styleData->Border as $borderStyle) { foreach ($styleData->Border as $borderStyle) {
$borderAttributes = $borderStyle->attributes($namespaces['ss']); $borderAttributes = $borderStyle->attributes($namespaces['ss']);
$thisBorder = array(); $thisBorder = [];
foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) { foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) {
// echo $borderStyleKey.' = '.$borderStyleValue.'<br />'; // echo $borderStyleKey.' = '.$borderStyleValue.'<br />';
switch ($borderStyleKey) { switch ($borderStyleKey) {
case 'LineStyle': case 'LineStyle':
$thisBorder['style'] = \PhpSpreadsheet\Style\Border::BORDER_MEDIUM; $thisBorder['style'] = \PhpSpreadsheet\Style\Border::BORDER_MEDIUM;
@ -461,7 +461,7 @@ class Excel2003XML extends BaseReader implements IReader
break; break;
case 'Font': case 'Font':
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
$styleAttributeValue = (string) $styleAttributeValue; $styleAttributeValue = (string) $styleAttributeValue;
switch ($styleAttributeKey) { switch ($styleAttributeKey) {
case 'FontName': case 'FontName':
@ -489,7 +489,7 @@ class Excel2003XML extends BaseReader implements IReader
break; break;
case 'Interior': case 'Interior':
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
switch ($styleAttributeKey) { switch ($styleAttributeKey) {
case 'Color': case 'Color':
$this->styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue, 1); $this->styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue, 1);
@ -499,7 +499,7 @@ class Excel2003XML extends BaseReader implements IReader
break; break;
case 'NumberFormat': case 'NumberFormat':
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
$styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue);
switch ($styleAttributeValue) { switch ($styleAttributeValue) {
case 'Short Date': case 'Short Date':
@ -513,7 +513,7 @@ class Excel2003XML extends BaseReader implements IReader
break; break;
case 'Protection': case 'Protection':
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; // echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
} }
break; break;
} }
@ -552,7 +552,7 @@ class Excel2003XML extends BaseReader implements IReader
foreach ($worksheet->Table->Column as $columnData) { foreach ($worksheet->Table->Column as $columnData) {
$columnData_ss = $columnData->attributes($namespaces['ss']); $columnData_ss = $columnData->attributes($namespaces['ss']);
if (isset($columnData_ss['Index'])) { if (isset($columnData_ss['Index'])) {
$columnID = \PhpSpreadsheet\Cell::stringFromColumnIndex($columnData_ss['Index']-1); $columnID = \PhpSpreadsheet\Cell::stringFromColumnIndex($columnData_ss['Index'] - 1);
} }
if (isset($columnData_ss['Width'])) { if (isset($columnData_ss['Width'])) {
$columnWidth = $columnData_ss['Width']; $columnWidth = $columnData_ss['Width'];
@ -578,9 +578,9 @@ class Excel2003XML extends BaseReader implements IReader
foreach ($rowData->Cell as $cell) { foreach ($rowData->Cell as $cell) {
$cell_ss = $cell->attributes($namespaces['ss']); $cell_ss = $cell->attributes($namespaces['ss']);
if (isset($cell_ss['Index'])) { if (isset($cell_ss['Index'])) {
$columnID = \PhpSpreadsheet\Cell::stringFromColumnIndex($cell_ss['Index']-1); $columnID = \PhpSpreadsheet\Cell::stringFromColumnIndex($cell_ss['Index'] - 1);
} }
$cellRange = $columnID.$rowID; $cellRange = $columnID . $rowID;
if ($this->getReadFilter() !== null) { if ($this->getReadFilter() !== null) {
if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
@ -591,14 +591,14 @@ class Excel2003XML extends BaseReader implements IReader
if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) { if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) {
$columnTo = $columnID; $columnTo = $columnID;
if (isset($cell_ss['MergeAcross'])) { if (isset($cell_ss['MergeAcross'])) {
$additionalMergedCells += (int)$cell_ss['MergeAcross']; $additionalMergedCells += (int) $cell_ss['MergeAcross'];
$columnTo = \PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] -1); $columnTo = \PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] - 1);
} }
$rowTo = $rowID; $rowTo = $rowID;
if (isset($cell_ss['MergeDown'])) { if (isset($cell_ss['MergeDown'])) {
$rowTo = $rowTo + $cell_ss['MergeDown']; $rowTo = $rowTo + $cell_ss['MergeDown'];
} }
$cellRange .= ':'.$columnTo.$rowTo; $cellRange .= ':' . $columnTo . $rowTo;
$spreadsheet->getActiveSheet()->mergeCells($cellRange); $spreadsheet->getActiveSheet()->mergeCells($cellRange);
} }
@ -655,7 +655,7 @@ class Excel2003XML extends BaseReader implements IReader
} }
if ($hasCalculatedValue) { if ($hasCalculatedValue) {
// echo 'FORMULA<br />'; // echo 'FORMULA<br />';
$type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA; $type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA;
$columnNumber = \PhpSpreadsheet\Cell::columnIndexFromString($columnID); $columnNumber = \PhpSpreadsheet\Cell::columnIndexFromString($columnID);
if (substr($cellDataFormula, 0, 3) == 'of:') { if (substr($cellDataFormula, 0, 3) == 'of:') {
@ -666,7 +666,7 @@ class Excel2003XML extends BaseReader implements IReader
foreach ($temp as &$value) { foreach ($temp as &$value) {
// Only replace in alternate array entries (i.e. non-quoted blocks) // Only replace in alternate array entries (i.e. non-quoted blocks)
if ($key = !$key) { if ($key = !$key) {
$value = str_replace(array('[.', '.', ']'), '', $value); $value = str_replace(['[.', '.', ']'], '', $value);
} }
} }
} else { } else {
@ -703,7 +703,7 @@ class Excel2003XML extends BaseReader implements IReader
if ($columnReference{0} == '[') { if ($columnReference{0} == '[') {
$columnReference = $columnNumber + trim($columnReference, '[]'); $columnReference = $columnNumber + trim($columnReference, '[]');
} }
$A1CellReference = \PhpSpreadsheet\Cell::stringFromColumnIndex($columnReference-1).$rowReference; $A1CellReference = \PhpSpreadsheet\Cell::stringFromColumnIndex($columnReference - 1) . $rowReference;
$value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
} }
} }
@ -717,20 +717,20 @@ class Excel2003XML extends BaseReader implements IReader
// echo 'Cell '.$columnID.$rowID.' is a '.$type.' with a value of '.(($hasCalculatedValue) ? $cellDataFormula : $cellValue).'<br />'; // echo 'Cell '.$columnID.$rowID.' is a '.$type.' with a value of '.(($hasCalculatedValue) ? $cellDataFormula : $cellValue).'<br />';
// //
$spreadsheet->getActiveSheet()->getCell($columnID.$rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type); $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type);
if ($hasCalculatedValue) { if ($hasCalculatedValue) {
// echo 'Formula result is '.$cellValue.'<br />'; // echo 'Formula result is '.$cellValue.'<br />';
$spreadsheet->getActiveSheet()->getCell($columnID.$rowID)->setCalculatedValue($cellValue); $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setCalculatedValue($cellValue);
} }
$cellIsSet = $rowHasData = true; $cellIsSet = $rowHasData = true;
} }
if (isset($cell->Comment)) { if (isset($cell->Comment)) {
// echo '<b>comment found</b><br />'; // echo '<b>comment found</b><br />';
$commentAttributes = $cell->Comment->attributes($namespaces['ss']); $commentAttributes = $cell->Comment->attributes($namespaces['ss']);
$author = 'unknown'; $author = 'unknown';
if (isset($commentAttributes->Author)) { if (isset($commentAttributes->Author)) {
$author = (string)$commentAttributes->Author; $author = (string) $commentAttributes->Author;
// echo 'Author: ', $author,'<br />'; // echo 'Author: ', $author,'<br />';
} }
$node = $cell->Comment->Data->asXML(); $node = $cell->Comment->Data->asXML();
@ -738,18 +738,18 @@ class Excel2003XML extends BaseReader implements IReader
// echo $annotation,'<br />'; // echo $annotation,'<br />';
$annotation = strip_tags($node); $annotation = strip_tags($node);
// echo 'Annotation: ', $annotation,'<br />'; // echo 'Annotation: ', $annotation,'<br />';
$spreadsheet->getActiveSheet()->getComment($columnID.$rowID)->setAuthor(self::convertStringEncoding($author, $this->charSet))->setText($this->parseRichText($annotation)); $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setAuthor(self::convertStringEncoding($author, $this->charSet))->setText($this->parseRichText($annotation));
} }
if (($cellIsSet) && (isset($cell_ss['StyleID']))) { if (($cellIsSet) && (isset($cell_ss['StyleID']))) {
$style = (string) $cell_ss['StyleID']; $style = (string) $cell_ss['StyleID'];
// echo 'Cell style for '.$columnID.$rowID.' is '.$style.'<br />'; // echo 'Cell style for '.$columnID.$rowID.' is '.$style.'<br />';
if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) { if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) {
// echo 'Cell '.$columnID.$rowID.'<br />'; // echo 'Cell '.$columnID.$rowID.'<br />';
// print_r($this->styles[$style]); // print_r($this->styles[$style]);
// echo '<br />'; // echo '<br />';
if (!$spreadsheet->getActiveSheet()->cellExists($columnID.$rowID)) { if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) {
$spreadsheet->getActiveSheet()->getCell($columnID.$rowID)->setValue(null); $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null);
} }
$spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]); $spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]);
} }
@ -757,7 +757,7 @@ class Excel2003XML extends BaseReader implements IReader
++$columnID; ++$columnID;
while ($additionalMergedCells > 0) { while ($additionalMergedCells > 0) {
++$columnID; ++$columnID;
$additionalMergedCells--; --$additionalMergedCells;
} }
} }
@ -782,16 +782,15 @@ class Excel2003XML extends BaseReader implements IReader
return $spreadsheet; return $spreadsheet;
} }
protected static function convertStringEncoding($string, $charset) protected static function convertStringEncoding($string, $charset)
{ {
if ($charset != 'UTF-8') { if ($charset != 'UTF-8') {
return \PhpSpreadsheet\Shared\StringHelper::convertEncoding($string, 'UTF-8', $charset); return \PhpSpreadsheet\Shared\StringHelper::convertEncoding($string, 'UTF-8', $charset);
} }
return $string; return $string;
} }
protected function parseRichText($is = '') protected function parseRichText($is = '')
{ {
$value = new \PhpSpreadsheet\RichText(); $value = new \PhpSpreadsheet\RichText();

File diff suppressed because it is too large Load Diff

View File

@ -40,16 +40,16 @@ class Chart
return (float) $attributes[$name]; return (float) $attributes[$name];
} }
} }
return null; return null;
} }
private static function readColor($color, $background = false) private static function readColor($color, $background = false)
{ {
if (isset($color["rgb"])) { if (isset($color['rgb'])) {
return (string)$color["rgb"]; return (string) $color['rgb'];
} elseif (isset($color["indexed"])) { } elseif (isset($color['indexed'])) {
return \PhpSpreadsheet\Style\Color::indexedColor($color["indexed"]-7, $background)->getARGB(); return \PhpSpreadsheet\Style\Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
} }
} }
@ -63,90 +63,90 @@ class Chart
foreach ($chartElementsC as $chartElementKey => $chartElement) { foreach ($chartElementsC as $chartElementKey => $chartElement) {
switch ($chartElementKey) { switch ($chartElementKey) {
case "chart": case 'chart':
foreach ($chartElement as $chartDetailsKey => $chartDetails) { foreach ($chartElement as $chartDetailsKey => $chartDetails) {
$chartDetailsC = $chartDetails->children($namespacesChartMeta['c']); $chartDetailsC = $chartDetails->children($namespacesChartMeta['c']);
switch ($chartDetailsKey) { switch ($chartDetailsKey) {
case "plotArea": case 'plotArea':
$plotAreaLayout = $XaxisLable = $YaxisLable = null; $plotAreaLayout = $XaxisLable = $YaxisLable = null;
$plotSeries = $plotAttributes = array(); $plotSeries = $plotAttributes = [];
foreach ($chartDetails as $chartDetailKey => $chartDetail) { foreach ($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) { switch ($chartDetailKey) {
case "layout": case 'layout':
$plotAreaLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'plotArea'); $plotAreaLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'plotArea');
break; break;
case "catAx": case 'catAx':
if (isset($chartDetail->title)) { if (isset($chartDetail->title)) {
$XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); $XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat');
} }
break; break;
case "dateAx": case 'dateAx':
if (isset($chartDetail->title)) { if (isset($chartDetail->title)) {
$XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); $XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat');
} }
break; break;
case "valAx": case 'valAx':
if (isset($chartDetail->title)) { if (isset($chartDetail->title)) {
$YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); $YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat');
} }
break; break;
case "barChart": case 'barChart':
case "bar3DChart": case 'bar3DChart':
$barDirection = self::getAttribute($chartDetail->barDir, 'val', 'string'); $barDirection = self::getAttribute($chartDetail->barDir, 'val', 'string');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotDirection($barDirection); $plotSer->setPlotDirection($barDirection);
$plotSeries[] = $plotSer; $plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "lineChart": case 'lineChart':
case "line3DChart": case 'line3DChart':
$plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "areaChart": case 'areaChart':
case "area3DChart": case 'area3DChart':
$plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "doughnutChart": case 'doughnutChart':
case "pieChart": case 'pieChart':
case "pie3DChart": case 'pie3DChart':
$explosion = isset($chartDetail->ser->explosion); $explosion = isset($chartDetail->ser->explosion);
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($explosion); $plotSer->setPlotStyle($explosion);
$plotSeries[] = $plotSer; $plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "scatterChart": case 'scatterChart':
$scatterStyle = self::getAttribute($chartDetail->scatterStyle, 'val', 'string'); $scatterStyle = self::getAttribute($chartDetail->scatterStyle, 'val', 'string');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($scatterStyle); $plotSer->setPlotStyle($scatterStyle);
$plotSeries[] = $plotSer; $plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "bubbleChart": case 'bubbleChart':
$bubbleScale = self::getAttribute($chartDetail->bubbleScale, 'val', 'integer'); $bubbleScale = self::getAttribute($chartDetail->bubbleScale, 'val', 'integer');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($bubbleScale); $plotSer->setPlotStyle($bubbleScale);
$plotSeries[] = $plotSer; $plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "radarChart": case 'radarChart':
$radarStyle = self::getAttribute($chartDetail->radarStyle, 'val', 'string'); $radarStyle = self::getAttribute($chartDetail->radarStyle, 'val', 'string');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($radarStyle); $plotSer->setPlotStyle($radarStyle);
$plotSeries[] = $plotSer; $plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "surfaceChart": case 'surfaceChart':
case "surface3DChart": case 'surface3DChart':
$wireFrame = self::getAttribute($chartDetail->wireframe, 'val', 'boolean'); $wireFrame = self::getAttribute($chartDetail->wireframe, 'val', 'boolean');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($wireFrame); $plotSer->setPlotStyle($wireFrame);
$plotSeries[] = $plotSer; $plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail); $plotAttributes = self::readChartAttributes($chartDetail);
break; break;
case "stockChart": case 'stockChart':
$plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotAttributes = self::readChartAttributes($plotAreaLayout); $plotAttributes = self::readChartAttributes($plotAreaLayout);
break; break;
@ -158,28 +158,28 @@ class Chart
$plotArea = new \PhpSpreadsheet\Chart\PlotArea($plotAreaLayout, $plotSeries); $plotArea = new \PhpSpreadsheet\Chart\PlotArea($plotAreaLayout, $plotSeries);
self::setChartAttributes($plotAreaLayout, $plotAttributes); self::setChartAttributes($plotAreaLayout, $plotAttributes);
break; break;
case "plotVisOnly": case 'plotVisOnly':
$plotVisOnly = self::getAttribute($chartDetails, 'val', 'string'); $plotVisOnly = self::getAttribute($chartDetails, 'val', 'string');
break; break;
case "dispBlanksAs": case 'dispBlanksAs':
$dispBlanksAs = self::getAttribute($chartDetails, 'val', 'string'); $dispBlanksAs = self::getAttribute($chartDetails, 'val', 'string');
break; break;
case "title": case 'title':
$title = self::chartTitle($chartDetails, $namespacesChartMeta, 'title'); $title = self::chartTitle($chartDetails, $namespacesChartMeta, 'title');
break; break;
case "legend": case 'legend':
$legendPos = 'r'; $legendPos = 'r';
$legendLayout = null; $legendLayout = null;
$legendOverlay = false; $legendOverlay = false;
foreach ($chartDetails as $chartDetailKey => $chartDetail) { foreach ($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) { switch ($chartDetailKey) {
case "legendPos": case 'legendPos':
$legendPos = self::getAttribute($chartDetail, 'val', 'string'); $legendPos = self::getAttribute($chartDetail, 'val', 'string');
break; break;
case "overlay": case 'overlay':
$legendOverlay = self::getAttribute($chartDetail, 'val', 'boolean'); $legendOverlay = self::getAttribute($chartDetail, 'val', 'boolean');
break; break;
case "layout": case 'layout':
$legendLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'legend'); $legendLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'legend');
break; break;
} }
@ -197,21 +197,21 @@ class Chart
private static function chartTitle($titleDetails, $namespacesChartMeta, $type) private static function chartTitle($titleDetails, $namespacesChartMeta, $type)
{ {
$caption = array(); $caption = [];
$titleLayout = null; $titleLayout = null;
foreach ($titleDetails as $titleDetailKey => $chartDetail) { foreach ($titleDetails as $titleDetailKey => $chartDetail) {
switch ($titleDetailKey) { switch ($titleDetailKey) {
case "tx": case 'tx':
$titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']); $titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']);
foreach ($titleDetails as $titleKey => $titleDetail) { foreach ($titleDetails as $titleKey => $titleDetail) {
switch ($titleKey) { switch ($titleKey) {
case "p": case 'p':
$titleDetailPart = $titleDetail->children($namespacesChartMeta['a']); $titleDetailPart = $titleDetail->children($namespacesChartMeta['a']);
$caption[] = self::parseRichText($titleDetailPart); $caption[] = self::parseRichText($titleDetailPart);
} }
} }
break; break;
case "layout": case 'layout':
$titleLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta); $titleLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta);
break; break;
} }
@ -229,11 +229,12 @@ class Chart
if (is_null($details)) { if (is_null($details)) {
return null; return null;
} }
$layout = array(); $layout = [];
foreach ($details as $detailKey => $detail) { foreach ($details as $detailKey => $detail) {
// echo $detailKey, ' => ',self::getAttribute($detail, 'val', 'string'),PHP_EOL; // echo $detailKey, ' => ',self::getAttribute($detail, 'val', 'string'),PHP_EOL;
$layout[$detailKey] = self::getAttribute($detail, 'val', 'string'); $layout[$detailKey] = self::getAttribute($detail, 'val', 'string');
} }
return new \PhpSpreadsheet\Chart\Layout($layout); return new \PhpSpreadsheet\Chart\Layout($layout);
} }
@ -241,54 +242,54 @@ class Chart
{ {
$multiSeriesType = null; $multiSeriesType = null;
$smoothLine = false; $smoothLine = false;
$seriesLabel = $seriesCategory = $seriesValues = $plotOrder = array(); $seriesLabel = $seriesCategory = $seriesValues = $plotOrder = [];
$seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']); $seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']);
foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) { foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) {
switch ($seriesDetailKey) { switch ($seriesDetailKey) {
case "grouping": case 'grouping':
$multiSeriesType = self::getAttribute($chartDetail->grouping, 'val', 'string'); $multiSeriesType = self::getAttribute($chartDetail->grouping, 'val', 'string');
break; break;
case "ser": case 'ser':
$marker = null; $marker = null;
foreach ($seriesDetails as $seriesKey => $seriesDetail) { foreach ($seriesDetails as $seriesKey => $seriesDetail) {
switch ($seriesKey) { switch ($seriesKey) {
case "idx": case 'idx':
$seriesIndex = self::getAttribute($seriesDetail, 'val', 'integer'); $seriesIndex = self::getAttribute($seriesDetail, 'val', 'integer');
break; break;
case "order": case 'order':
$seriesOrder = self::getAttribute($seriesDetail, 'val', 'integer'); $seriesOrder = self::getAttribute($seriesDetail, 'val', 'integer');
$plotOrder[$seriesIndex] = $seriesOrder; $plotOrder[$seriesIndex] = $seriesOrder;
break; break;
case "tx": case 'tx':
$seriesLabel[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta); $seriesLabel[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta);
break; break;
case "marker": case 'marker':
$marker = self::getAttribute($seriesDetail->symbol, 'val', 'string'); $marker = self::getAttribute($seriesDetail->symbol, 'val', 'string');
break; break;
case "smooth": case 'smooth':
$smoothLine = self::getAttribute($seriesDetail, 'val', 'boolean'); $smoothLine = self::getAttribute($seriesDetail, 'val', 'boolean');
break; break;
case "cat": case 'cat':
$seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta); $seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta);
break; break;
case "val": case 'val':
$seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); $seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker);
break; break;
case "xVal": case 'xVal':
$seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); $seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker);
break; break;
case "yVal": case 'yVal':
$seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); $seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker);
break; break;
} }
} }
} }
} }
return new \PhpSpreadsheet\Chart\DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $smoothLine); return new \PhpSpreadsheet\Chart\DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $smoothLine);
} }
private static function chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null, $smoothLine = false) private static function chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null, $smoothLine = false)
{ {
if (isset($seriesDetail->strRef)) { if (isset($seriesDetail->strRef)) {
@ -314,13 +315,13 @@ class Chart
return new \PhpSpreadsheet\Chart\DataSeriesValues('String', $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker, $smoothLine); return new \PhpSpreadsheet\Chart\DataSeriesValues('String', $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker, $smoothLine);
} }
return null; return null;
} }
private static function chartDataSeriesValues($seriesValueSet, $dataType = 'n') private static function chartDataSeriesValues($seriesValueSet, $dataType = 'n')
{ {
$seriesVal = array(); $seriesVal = [];
$formatCode = ''; $formatCode = '';
$pointCount = 0; $pointCount = 0;
@ -343,16 +344,16 @@ class Chart
} }
} }
return array( return [
'formatCode' => $formatCode, 'formatCode' => $formatCode,
'pointCount' => $pointCount, 'pointCount' => $pointCount,
'dataValues' => $seriesVal 'dataValues' => $seriesVal,
); ];
} }
private static function chartDataSeriesValuesMultiLevel($seriesValueSet, $dataType = 'n') private static function chartDataSeriesValuesMultiLevel($seriesValueSet, $dataType = 'n')
{ {
$seriesVal = array(); $seriesVal = [];
$formatCode = ''; $formatCode = '';
$pointCount = 0; $pointCount = 0;
@ -377,11 +378,11 @@ class Chart
} }
} }
return array( return [
'formatCode' => $formatCode, 'formatCode' => $formatCode,
'pointCount' => $pointCount, 'pointCount' => $pointCount,
'dataValues' => $seriesVal 'dataValues' => $seriesVal,
); ];
} }
private static function parseRichText($titleDetailPart = null) private static function parseRichText($titleDetailPart = null)
@ -393,8 +394,8 @@ class Chart
$objText = $value->createTextRun((string) $titleDetailElement->t); $objText = $value->createTextRun((string) $titleDetailElement->t);
} }
if (isset($titleDetailElement->rPr)) { if (isset($titleDetailElement->rPr)) {
if (isset($titleDetailElement->rPr->rFont["val"])) { if (isset($titleDetailElement->rPr->rFont['val'])) {
$objText->getFont()->setName((string) $titleDetailElement->rPr->rFont["val"]); $objText->getFont()->setName((string) $titleDetailElement->rPr->rFont['val']);
} }
$fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer')); $fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer'));
@ -453,7 +454,7 @@ class Chart
private static function readChartAttributes($chartDetail) private static function readChartAttributes($chartDetail)
{ {
$plotAttributes = array(); $plotAttributes = [];
if (isset($chartDetail->dLbls)) { if (isset($chartDetail->dLbls)) {
if (isset($chartDetail->dLbls->howLegendKey)) { if (isset($chartDetail->dLbls->howLegendKey)) {
$plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string'); $plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string');

View File

@ -47,7 +47,6 @@ class Theme
*/ */
private $colourMapValues; private $colourMapValues;
/** /**
* Colour Map * Colour Map
* *
@ -55,17 +54,15 @@ class Theme
*/ */
private $colourMap; private $colourMap;
/** /**
* Create a new Theme * Create a new Theme
*
*/ */
public function __construct($themeName, $colourSchemeName, $colourMap) public function __construct($themeName, $colourSchemeName, $colourMap)
{ {
// Initialise values // Initialise values
$this->themeName = $themeName; $this->themeName = $themeName;
$this->colourSchemeName = $colourSchemeName; $this->colourSchemeName = $colourSchemeName;
$this->colourMap = $colourMap; $this->colourMap = $colourMap;
} }
/** /**
@ -98,6 +95,7 @@ class Theme
if (isset($this->colourMap[$index])) { if (isset($this->colourMap[$index])) {
return $this->colourMap[$index]; return $this->colourMap[$index];
} }
return null; return null;
} }

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5\Color;
class BIFF5 class BIFF5
{ {
protected static $map = array( protected static $map = [
0x08 => '000000', 0x08 => '000000',
0x09 => 'FFFFFF', 0x09 => 'FFFFFF',
0x0A => 'FF0000', 0x0A => 'FF0000',
@ -61,7 +61,7 @@ class BIFF5
0x3D => '85396A', 0x3D => '85396A',
0x3E => '4A3285', 0x3E => '4A3285',
0x3F => '424242', 0x3F => '424242',
); ];
/** /**
* Map color array from BIFF5 built-in color index * Map color array from BIFF5 built-in color index
@ -72,8 +72,9 @@ class BIFF5
public static function lookup($color) public static function lookup($color)
{ {
if (isset(self::$map[$color])) { if (isset(self::$map[$color])) {
return array('rgb' => self::$map[$color]); return ['rgb' => self::$map[$color]];
} }
return array('rgb' => '000000');
return ['rgb' => '000000'];
} }
} }

View File

@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5\Color;
class BIFF8 class BIFF8
{ {
protected static $map = array( protected static $map = [
0x08 => '000000', 0x08 => '000000',
0x09 => 'FFFFFF', 0x09 => 'FFFFFF',
0x0A => 'FF0000', 0x0A => 'FF0000',
@ -61,9 +61,9 @@ class BIFF8
0x3D => '993366', 0x3D => '993366',
0x3E => '333399', 0x3E => '333399',
0x3F => '333333', 0x3F => '333333',
); ];
/** /**
* Map color array from BIFF8 built-in color index * Map color array from BIFF8 built-in color index
* *
* @param int $color * @param int $color
@ -72,8 +72,9 @@ class BIFF8
public static function lookup($color) public static function lookup($color)
{ {
if (isset(self::$map[$color])) { if (isset(self::$map[$color])) {
return array('rgb' => self::$map[$color]); return ['rgb' => self::$map[$color]];
} }
return array('rgb' => '000000');
return ['rgb' => '000000'];
} }
} }

View File

@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5\Color;
class BuiltIn class BuiltIn
{ {
protected static $map = array( protected static $map = [
0x00 => '000000', 0x00 => '000000',
0x01 => 'FFFFFF', 0x01 => 'FFFFFF',
0x02 => 'FF0000', 0x02 => 'FF0000',
@ -15,7 +15,7 @@ class BuiltIn
0x07 => '00FFFF', 0x07 => '00FFFF',
0x40 => '000000', // system window text color 0x40 => '000000', // system window text color
0x41 => 'FFFFFF', // system window background color 0x41 => 'FFFFFF', // system window background color
); ];
/** /**
* Map built-in color to RGB value * Map built-in color to RGB value
@ -26,8 +26,9 @@ class BuiltIn
public static function lookup($color) public static function lookup($color)
{ {
if (isset(self::$map[$color])) { if (isset(self::$map[$color])) {
return array('rgb' => self::$map[$color]); return ['rgb' => self::$map[$color]];
} }
return array('rgb' => '000000');
return ['rgb' => '000000'];
} }
} }

View File

@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5;
class ErrorCode class ErrorCode
{ {
protected static $map = array( protected static $map = [
0x00 => '#NULL!', 0x00 => '#NULL!',
0x07 => '#DIV/0!', 0x07 => '#DIV/0!',
0x0F => '#VALUE!', 0x0F => '#VALUE!',
@ -12,19 +12,20 @@ class ErrorCode
0x1D => '#NAME?', 0x1D => '#NAME?',
0x24 => '#NUM!', 0x24 => '#NUM!',
0x2A => '#N/A', 0x2A => '#N/A',
); ];
/** /**
* Map error code, e.g. '#N/A' * Map error code, e.g. '#N/A'
* *
* @param int $code * @param int $code
* @return string|boolean * @return string|bool
*/ */
public static function lookup($code) public static function lookup($code)
{ {
if (isset(self::$map[$code])) { if (isset(self::$map[$code])) {
return self::$map[$code]; return self::$map[$code];
} }
return false; return false;
} }
} }

View File

@ -26,24 +26,24 @@ namespace PhpSpreadsheet\Reader\Excel5;
*/ */
class Escher class Escher
{ {
const DGGCONTAINER = 0xF000; const DGGCONTAINER = 0xF000;
const BSTORECONTAINER = 0xF001; const BSTORECONTAINER = 0xF001;
const DGCONTAINER = 0xF002; const DGCONTAINER = 0xF002;
const SPGRCONTAINER = 0xF003; const SPGRCONTAINER = 0xF003;
const SPCONTAINER = 0xF004; const SPCONTAINER = 0xF004;
const DGG = 0xF006; const DGG = 0xF006;
const BSE = 0xF007; const BSE = 0xF007;
const DG = 0xF008; const DG = 0xF008;
const SPGR = 0xF009; const SPGR = 0xF009;
const SP = 0xF00A; const SP = 0xF00A;
const OPT = 0xF00B; const OPT = 0xF00B;
const CLIENTTEXTBOX = 0xF00D; const CLIENTTEXTBOX = 0xF00D;
const CLIENTANCHOR = 0xF010; const CLIENTANCHOR = 0xF010;
const CLIENTDATA = 0xF011; const CLIENTDATA = 0xF011;
const BLIPJPEG = 0xF01D; const BLIPJPEG = 0xF01D;
const BLIPPNG = 0xF01E; const BLIPPNG = 0xF01E;
const SPLITMENUCOLORS = 0xF11E; const SPLITMENUCOLORS = 0xF11E;
const TERTIARYOPT = 0xF122; const TERTIARYOPT = 0xF122;
/** /**
* Escher stream data (binary) * Escher stream data (binary)
@ -201,7 +201,7 @@ class Escher
// record is a container, read contents // record is a container, read contents
$dggContainer = new \PhpSpreadsheet\Shared\Escher\DggContainer(); $dggContainer = new \PhpSpreadsheet\Shared\Escher\DggContainer();
$this->object->setDggContainer($dggContainer); $this->object->setDggContainer($dggContainer);
$reader = new Escher($dggContainer); $reader = new self($dggContainer);
$reader->load($recordData); $reader->load($recordData);
} }
@ -231,7 +231,7 @@ class Escher
// record is a container, read contents // record is a container, read contents
$bstoreContainer = new \PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer(); $bstoreContainer = new \PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer();
$this->object->setBstoreContainer($bstoreContainer); $this->object->setBstoreContainer($bstoreContainer);
$reader = new Escher($bstoreContainer); $reader = new self($bstoreContainer);
$reader->load($recordData); $reader->load($recordData);
} }
@ -324,7 +324,7 @@ class Escher
$pos += 16; $pos += 16;
// offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3
if (in_array($recInstance, array(0x046B, 0x06E3))) { if (in_array($recInstance, [0x046B, 0x06E3])) {
$rgbUid2 = substr($recordData, 16, 16); $rgbUid2 = substr($recordData, 16, 16);
$pos += 16; $pos += 16;
} }
@ -485,7 +485,7 @@ class Escher
$this->object->addChild($spgrContainer); $this->object->addChild($spgrContainer);
} }
$reader = new Escher($spgrContainer); $reader = new self($spgrContainer);
$escher = $reader->load($recordData); $escher = $reader->load($recordData);
} }
@ -505,7 +505,7 @@ class Escher
$this->pos += 8 + $length; $this->pos += 8 + $length;
// record is a container, read contents // record is a container, read contents
$reader = new Escher($spContainer); $reader = new self($spContainer);
$escher = $reader->load($recordData); $escher = $reader->load($recordData);
} }

View File

@ -59,7 +59,7 @@ class MD5
public function getContext() public function getContext()
{ {
$s = ''; $s = '';
foreach (array('a', 'b', 'c', 'd') as $i) { foreach (['a', 'b', 'c', 'd'] as $i) {
$v = $this->{$i}; $v = $this->{$i};
$s .= chr($v & 0xff); $s .= chr($v & 0xff);
$s .= chr(($v >> 8) & 0xff); $s .= chr(($v >> 8) & 0xff);
@ -84,10 +84,10 @@ class MD5
$C = $this->c; $C = $this->c;
$D = $this->d; $D = $this->d;
$F = ['self','f']; $F = ['self', 'f'];
$G = ['self','g']; $G = ['self', 'g'];
$H = ['self','h']; $H = ['self', 'h'];
$I = ['self','i']; $I = ['self', 'i'];
/* ROUND 1 */ /* ROUND 1 */
self::step($F, $A, $B, $C, $D, $words[0], 7, 0xd76aa478); self::step($F, $A, $B, $C, $D, $words[0], 7, 0xd76aa478);
@ -169,22 +169,22 @@ class MD5
private static function f($X, $Y, $Z) private static function f($X, $Y, $Z)
{ {
return (($X & $Y) | ((~ $X) & $Z)); // X AND Y OR NOT X AND Z return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z
} }
private static function g($X, $Y, $Z) private static function g($X, $Y, $Z)
{ {
return (($X & $Z) | ($Y & (~ $Z))); // X AND Z OR Y AND NOT Z return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z
} }
private static function h($X, $Y, $Z) private static function h($X, $Y, $Z)
{ {
return ($X ^ $Y ^ $Z); // X XOR Y XOR Z return $X ^ $Y ^ $Z; // X XOR Y XOR Z
} }
private static function i($X, $Y, $Z) private static function i($X, $Y, $Z)
{ {
return ($Y ^ ($X | (~ $Z))) ; // Y XOR (X OR NOT Z) return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z)
} }
private static function step($func, &$A, $B, $C, $D, $M, $s, $t) private static function step($func, &$A, $B, $C, $D, $M, $s, $t)
@ -196,7 +196,8 @@ class MD5
private static function rotate($decimal, $bits) private static function rotate($decimal, $bits)
{ {
$binary = str_pad(decbin($decimal), 32, "0", STR_PAD_LEFT); $binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT);
return bindec(substr($binary, $bits).substr($binary, 0, $bits));
return bindec(substr($binary, $bits) . substr($binary, 0, $bits));
} }
} }

View File

@ -27,7 +27,7 @@ namespace PhpSpreadsheet\Reader\Excel5;
class RC4 class RC4
{ {
// Context // Context
protected $s = array(); protected $s = [];
protected $i = 0; protected $i = 0;
protected $j = 0; protected $j = 0;
@ -40,12 +40,12 @@ class RC4
{ {
$len = strlen($key); $len = strlen($key);
for ($this->i = 0; $this->i < 256; $this->i++) { for ($this->i = 0; $this->i < 256; ++$this->i) {
$this->s[$this->i] = $this->i; $this->s[$this->i] = $this->i;
} }
$this->j = 0; $this->j = 0;
for ($this->i = 0; $this->i < 256; $this->i++) { for ($this->i = 0; $this->i < 256; ++$this->i) {
$this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256; $this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256;
$t = $this->s[$this->i]; $t = $this->s[$this->i];
$this->s[$this->i] = $this->s[$this->j]; $this->s[$this->i] = $this->s[$this->j];
@ -64,7 +64,7 @@ class RC4
public function RC4($data) public function RC4($data)
{ {
$len = strlen($data); $len = strlen($data);
for ($c = 0; $c < $len; $c++) { for ($c = 0; $c < $len; ++$c) {
$this->i = ($this->i + 1) % 256; $this->i = ($this->i + 1) % 256;
$this->j = ($this->j + $this->s[$this->i]) % 256; $this->j = ($this->j + $this->s[$this->i]) % 256;
$t = $this->s[$this->i]; $t = $this->s[$this->i];
@ -75,6 +75,7 @@ class RC4
$data[$c] = chr(ord($data[$c]) ^ $this->s[$t]); $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]);
} }
return $data; return $data;
} }
} }

View File

@ -2,11 +2,11 @@
namespace PhpSpreadsheet\Reader\Excel5\Style; namespace PhpSpreadsheet\Reader\Excel5\Style;
use \PhpSpreadsheet\Style\Border as StyleBorder; use PhpSpreadsheet\Style\Border as StyleBorder;
class Border class Border
{ {
protected static $map = array( protected static $map = [
0x00 => StyleBorder::BORDER_NONE, 0x00 => StyleBorder::BORDER_NONE,
0x01 => StyleBorder::BORDER_THIN, 0x01 => StyleBorder::BORDER_THIN,
0x02 => StyleBorder::BORDER_MEDIUM, 0x02 => StyleBorder::BORDER_MEDIUM,
@ -21,7 +21,7 @@ class Border
0x0B => StyleBorder::BORDER_DASHDOTDOT, 0x0B => StyleBorder::BORDER_DASHDOTDOT,
0x0C => StyleBorder::BORDER_MEDIUMDASHDOTDOT, 0x0C => StyleBorder::BORDER_MEDIUMDASHDOTDOT,
0x0D => StyleBorder::BORDER_SLANTDASHDOT, 0x0D => StyleBorder::BORDER_SLANTDASHDOT,
); ];
/** /**
* Map border style * Map border style
@ -35,6 +35,7 @@ class Border
if (isset(self::$map[$index])) { if (isset(self::$map[$index])) {
return self::$map[$index]; return self::$map[$index];
} }
return StyleBorder::BORDER_NONE; return StyleBorder::BORDER_NONE;
} }
} }

View File

@ -2,11 +2,11 @@
namespace PhpSpreadsheet\Reader\Excel5\Style; namespace PhpSpreadsheet\Reader\Excel5\Style;
use \PhpSpreadsheet\Style\Fill; use PhpSpreadsheet\Style\Fill;
class FillPattern class FillPattern
{ {
protected static $map = array( protected static $map = [
0x00 => Fill::FILL_NONE, 0x00 => Fill::FILL_NONE,
0x01 => Fill::FILL_SOLID, 0x01 => Fill::FILL_SOLID,
0x02 => Fill::FILL_PATTERN_MEDIUMGRAY, 0x02 => Fill::FILL_PATTERN_MEDIUMGRAY,
@ -26,7 +26,7 @@ class FillPattern
0x10 => Fill::FILL_PATTERN_LIGHTTRELLIS, 0x10 => Fill::FILL_PATTERN_LIGHTTRELLIS,
0x11 => Fill::FILL_PATTERN_GRAY125, 0x11 => Fill::FILL_PATTERN_GRAY125,
0x12 => Fill::FILL_PATTERN_GRAY0625, 0x12 => Fill::FILL_PATTERN_GRAY0625,
); ];
/** /**
* Get fill pattern from index * Get fill pattern from index
@ -40,6 +40,7 @@ class FillPattern
if (isset(self::$map[$index])) { if (isset(self::$map[$index])) {
return self::$map[$index]; return self::$map[$index];
} }
return Fill::FILL_NONE; return Fill::FILL_NONE;
} }
} }

View File

@ -31,14 +31,14 @@ class Gnumeric extends BaseReader implements IReader
* *
* @var array * @var array
*/ */
private $styles = array(); private $styles = [];
/** /**
* Shared Expressions * Shared Expressions
* *
* @var array * @var array
*/ */
private $expressions = array(); private $expressions = [];
private $referenceHelper = null; private $referenceHelper = null;
@ -47,7 +47,7 @@ class Gnumeric extends BaseReader implements IReader
*/ */
public function __construct() public function __construct()
{ {
$this->readFilter = new DefaultReadFilter(); $this->readFilter = new DefaultReadFilter();
$this->referenceHelper = \PhpSpreadsheet\ReferenceHelper::getInstance(); $this->referenceHelper = \PhpSpreadsheet\ReferenceHelper::getInstance();
} }
@ -55,19 +55,19 @@ class Gnumeric extends BaseReader implements IReader
* Can the current IReader read the file? * Can the current IReader read the file?
* *
* @param string $pFilename * @param string $pFilename
* @return boolean
* @throws Exception * @throws Exception
* @return bool
*/ */
public function canRead($pFilename) public function canRead($pFilename)
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
// Check if gzlib functions are available // Check if gzlib functions are available
if (!function_exists('gzread')) { if (!function_exists('gzread')) {
throw new Exception("gzlib library is not enabled"); throw new Exception('gzlib library is not enabled');
} }
// Read signature data (first 3 bytes) // Read signature data (first 3 bytes)
@ -75,7 +75,7 @@ class Gnumeric extends BaseReader implements IReader
$data = fread($fh, 2); $data = fread($fh, 2);
fclose($fh); fclose($fh);
if ($data != chr(0x1F).chr(0x8B)) { if ($data != chr(0x1F) . chr(0x8B)) {
return false; return false;
} }
@ -92,14 +92,14 @@ class Gnumeric extends BaseReader implements IReader
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$xml = new XMLReader(); $xml = new XMLReader();
$xml->xml($this->securityScanFile('compress.zlib://'.realpath($pFilename)), null, \PhpSpreadsheet\Settings::getLibXmlLoaderOptions()); $xml->xml($this->securityScanFile('compress.zlib://' . realpath($pFilename)), null, \PhpSpreadsheet\Settings::getLibXmlLoaderOptions());
$xml->setParserProperty(2, true); $xml->setParserProperty(2, true);
$worksheetNames = array(); $worksheetNames = [];
while ($xml->read()) { while ($xml->read()) {
if ($xml->name == 'gnm:SheetName' && $xml->nodeType == XMLReader::ELEMENT) { if ($xml->name == 'gnm:SheetName' && $xml->nodeType == XMLReader::ELEMENT) {
$xml->read(); // Move onto the value node $xml->read(); // Move onto the value node
@ -123,23 +123,23 @@ class Gnumeric extends BaseReader implements IReader
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$xml = new XMLReader(); $xml = new XMLReader();
$xml->xml($this->securityScanFile('compress.zlib://'.realpath($pFilename)), null, \PhpSpreadsheet\Settings::getLibXmlLoaderOptions()); $xml->xml($this->securityScanFile('compress.zlib://' . realpath($pFilename)), null, \PhpSpreadsheet\Settings::getLibXmlLoaderOptions());
$xml->setParserProperty(2, true); $xml->setParserProperty(2, true);
$worksheetInfo = array(); $worksheetInfo = [];
while ($xml->read()) { while ($xml->read()) {
if ($xml->name == 'gnm:Sheet' && $xml->nodeType == XMLReader::ELEMENT) { if ($xml->name == 'gnm:Sheet' && $xml->nodeType == XMLReader::ELEMENT) {
$tmpInfo = array( $tmpInfo = [
'worksheetName' => '', 'worksheetName' => '',
'lastColumnLetter' => 'A', 'lastColumnLetter' => 'A',
'lastColumnIndex' => 0, 'lastColumnIndex' => 0,
'totalRows' => 0, 'totalRows' => 0,
'totalColumns' => 0, 'totalColumns' => 0,
); ];
while ($xml->read()) { while ($xml->read()) {
if ($xml->name == 'gnm:Name' && $xml->nodeType == XMLReader::ELEMENT) { if ($xml->name == 'gnm:Name' && $xml->nodeType == XMLReader::ELEMENT) {
@ -173,6 +173,7 @@ class Gnumeric extends BaseReader implements IReader
} }
gzclose($file); gzclose($file);
} }
return $data; return $data;
} }
@ -180,8 +181,8 @@ class Gnumeric extends BaseReader implements IReader
* Loads PhpSpreadsheet from file * Loads PhpSpreadsheet from file
* *
* @param string $pFilename * @param string $pFilename
* @return PhpSpreadsheet
* @throws Exception * @throws Exception
* @return PhpSpreadsheet
*/ */
public function load($pFilename) public function load($pFilename)
{ {
@ -197,14 +198,14 @@ class Gnumeric extends BaseReader implements IReader
* *
* @param string $pFilename * @param string $pFilename
* @param \PhpSpreadsheet\Spreadsheet $spreadsheet * @param \PhpSpreadsheet\Spreadsheet $spreadsheet
* @return PhpSpreadsheet
* @throws Exception * @throws Exception
* @return PhpSpreadsheet
*/ */
public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet)
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$timezoneObj = new DateTimeZone('Europe/London'); $timezoneObj = new DateTimeZone('Europe/London');
@ -231,7 +232,7 @@ class Gnumeric extends BaseReader implements IReader
$officeDocMetaXML = $officeDocXML->meta; $officeDocMetaXML = $officeDocXML->meta;
foreach ($officeDocMetaXML as $officePropertyData) { foreach ($officeDocMetaXML as $officePropertyData) {
$officePropertyDC = array(); $officePropertyDC = [];
if (isset($namespacesMeta['dc'])) { if (isset($namespacesMeta['dc'])) {
$officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
} }
@ -258,7 +259,7 @@ class Gnumeric extends BaseReader implements IReader
break; break;
} }
} }
$officePropertyMeta = array(); $officePropertyMeta = [];
if (isset($namespacesMeta['meta'])) { if (isset($namespacesMeta['meta'])) {
$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
} }
@ -407,11 +408,11 @@ class Gnumeric extends BaseReader implements IReader
$type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA; $type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA;
if ($ExprID > '') { if ($ExprID > '') {
if (((string) $cell) > '') { if (((string) $cell) > '') {
$this->expressions[$ExprID] = array( $this->expressions[$ExprID] = [
'column' => $cellAttributes->Col, 'column' => $cellAttributes->Col,
'row' => $cellAttributes->Row, 'row' => $cellAttributes->Row,
'formula' => (string) $cell 'formula' => (string) $cell,
); ];
// echo 'NEW EXPRESSION ', $ExprID,'<br />'; // echo 'NEW EXPRESSION ', $ExprID,'<br />';
} else { } else {
$expression = $this->expressions[$ExprID]; $expression = $this->expressions[$ExprID];
@ -452,7 +453,7 @@ class Gnumeric extends BaseReader implements IReader
case '80': // Array case '80': // Array
} }
} }
$spreadsheet->getActiveSheet()->getCell($column.$row)->setValueExplicit($cell, $type); $spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit($cell, $type);
} }
if ((!$this->readDataOnly) && (isset($sheet->Objects))) { if ((!$this->readDataOnly) && (isset($sheet->Objects))) {
@ -460,7 +461,7 @@ class Gnumeric extends BaseReader implements IReader
$commentAttributes = $comment->attributes(); $commentAttributes = $comment->attributes();
// Only comment objects are handled at the moment // Only comment objects are handled at the moment
if ($commentAttributes->Text) { if ($commentAttributes->Text) {
$spreadsheet->getActiveSheet()->getComment((string)$commentAttributes->ObjectBound)->setAuthor((string)$commentAttributes->Author)->setText($this->parseRichText((string)$commentAttributes->Text)); $spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound)->setAuthor((string) $commentAttributes->Author)->setText($this->parseRichText((string) $commentAttributes->Text));
} }
} }
} }
@ -477,7 +478,7 @@ class Gnumeric extends BaseReader implements IReader
$endColumn = \PhpSpreadsheet\Cell::stringFromColumnIndex($endColumn); $endColumn = \PhpSpreadsheet\Cell::stringFromColumnIndex($endColumn);
$endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow']; $endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow'];
$endRow += 1; $endRow += 1;
$cellRange = $startColumn.$startRow.':'.$endColumn.$endRow; $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow;
// echo $cellRange,'<br />'; // echo $cellRange,'<br />';
$styleAttributes = $styleRegion->Style->attributes(); $styleAttributes = $styleRegion->Style->attributes();
@ -487,7 +488,7 @@ class Gnumeric extends BaseReader implements IReader
// We still set the number format mask for date/time values, even if readDataOnly is true // We still set the number format mask for date/time values, even if readDataOnly is true
if ((!$this->readDataOnly) || if ((!$this->readDataOnly) ||
(\PhpSpreadsheet\Shared\Date::isDateTimeFormatCode((string) $styleAttributes['Format']))) { (\PhpSpreadsheet\Shared\Date::isDateTimeFormatCode((string) $styleAttributes['Format']))) {
$styleArray = array(); $styleArray = [];
$styleArray['numberformat']['code'] = (string) $styleAttributes['Format']; $styleArray['numberformat']['code'] = (string) $styleAttributes['Format'];
// If readDataOnly is false, we set all formatting information // If readDataOnly is false, we set all formatting information
if (!$this->readDataOnly) { if (!$this->readDataOnly) {
@ -530,15 +531,15 @@ class Gnumeric extends BaseReader implements IReader
$styleArray['alignment']['wrap'] = ($styleAttributes['WrapText'] == '1') ? true : false; $styleArray['alignment']['wrap'] = ($styleAttributes['WrapText'] == '1') ? true : false;
$styleArray['alignment']['shrinkToFit'] = ($styleAttributes['ShrinkToFit'] == '1') ? true : false; $styleArray['alignment']['shrinkToFit'] = ($styleAttributes['ShrinkToFit'] == '1') ? true : false;
$styleArray['alignment']['indent'] = (intval($styleAttributes["Indent"]) > 0) ? $styleAttributes["indent"] : 0; $styleArray['alignment']['indent'] = (intval($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0;
$RGB = self::parseGnumericColour($styleAttributes["Fore"]); $RGB = self::parseGnumericColour($styleAttributes['Fore']);
$styleArray['font']['color']['rgb'] = $RGB; $styleArray['font']['color']['rgb'] = $RGB;
$RGB = self::parseGnumericColour($styleAttributes["Back"]); $RGB = self::parseGnumericColour($styleAttributes['Back']);
$shade = $styleAttributes["Shade"]; $shade = $styleAttributes['Shade'];
if (($RGB != '000000') || ($shade != '0')) { if (($RGB != '000000') || ($shade != '0')) {
$styleArray['fill']['color']['rgb'] = $styleArray['fill']['startcolor']['rgb'] = $RGB; $styleArray['fill']['color']['rgb'] = $styleArray['fill']['startcolor']['rgb'] = $RGB;
$RGB2 = self::parseGnumericColour($styleAttributes["PatternColor"]); $RGB2 = self::parseGnumericColour($styleAttributes['PatternColor']);
$styleArray['fill']['endcolor']['rgb'] = $RGB2; $styleArray['fill']['endcolor']['rgb'] = $RGB2;
switch ($shade) { switch ($shade) {
case '1': case '1':
@ -677,19 +678,19 @@ class Gnumeric extends BaseReader implements IReader
if ((!$this->readDataOnly) && (isset($sheet->Cols))) { if ((!$this->readDataOnly) && (isset($sheet->Cols))) {
// Column Widths // Column Widths
$columnAttributes = $sheet->Cols->attributes(); $columnAttributes = $sheet->Cols->attributes();
$defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4;
$c = 0; $c = 0;
foreach ($sheet->Cols->ColInfo as $columnOverride) { foreach ($sheet->Cols->ColInfo as $columnOverride) {
$columnAttributes = $columnOverride->attributes(); $columnAttributes = $columnOverride->attributes();
$column = $columnAttributes['No']; $column = $columnAttributes['No'];
$columnWidth = $columnAttributes['Unit'] / 5.4; $columnWidth = $columnAttributes['Unit'] / 5.4;
$hidden = ((isset($columnAttributes['Hidden'])) && ($columnAttributes['Hidden'] == '1')) ? true : false; $hidden = ((isset($columnAttributes['Hidden'])) && ($columnAttributes['Hidden'] == '1')) ? true : false;
$columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1; $columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1;
while ($c < $column) { while ($c < $column) {
$spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setWidth($defaultWidth); $spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setWidth($defaultWidth);
++$c; ++$c;
} }
while (($c < ($column+$columnCount)) && ($c <= $maxCol)) { while (($c < ($column + $columnCount)) && ($c <= $maxCol)) {
$spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setWidth($columnWidth); $spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setWidth($columnWidth);
if ($hidden) { if ($hidden) {
$spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setVisible(false); $spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setVisible(false);
@ -719,7 +720,7 @@ class Gnumeric extends BaseReader implements IReader
++$r; ++$r;
$spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); $spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
} }
while (($r < ($row+$rowCount)) && ($r < $maxRow)) { while (($r < ($row + $rowCount)) && ($r < $maxRow)) {
++$r; ++$r;
$spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight); $spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight);
if ($hidden) { if ($hidden) {
@ -742,7 +743,7 @@ class Gnumeric extends BaseReader implements IReader
} }
} }
$worksheetID++; ++$worksheetID;
} }
// Loop through definedNames (global named ranges) // Loop through definedNames (global named ranges)
@ -769,12 +770,12 @@ class Gnumeric extends BaseReader implements IReader
private static function parseBorderAttributes($borderAttributes) private static function parseBorderAttributes($borderAttributes)
{ {
$styleArray = array(); $styleArray = [];
if (isset($borderAttributes["Color"])) { if (isset($borderAttributes['Color'])) {
$styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes["Color"]); $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']);
} }
switch ($borderAttributes["Style"]) { switch ($borderAttributes['Style']) {
case '0': case '0':
$styleArray['style'] = \PhpSpreadsheet\Style\Border::BORDER_NONE; $styleArray['style'] = \PhpSpreadsheet\Style\Border::BORDER_NONE;
break; break;
@ -818,6 +819,7 @@ class Gnumeric extends BaseReader implements IReader
$styleArray['style'] = \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHDOTDOT; $styleArray['style'] = \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHDOTDOT;
break; break;
} }
return $styleArray; return $styleArray;
} }
@ -835,6 +837,7 @@ class Gnumeric extends BaseReader implements IReader
$gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2); $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2);
$gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2); $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2);
$gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2); $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2);
return $gnmR . $gnmG . $gnmB; return $gnmR . $gnmG . $gnmB;
} }
} }

View File

@ -27,7 +27,6 @@ namespace PhpSpreadsheet\Reader;
/** PhpSpreadsheet root directory */ /** PhpSpreadsheet root directory */
class HTML extends BaseReader implements IReader class HTML extends BaseReader implements IReader
{ {
/** /**
* Input encoding * Input encoding
* *
@ -47,64 +46,64 @@ class HTML extends BaseReader implements IReader
* *
* @var array * @var array
*/ */
protected $formats = array( protected $formats = [
'h1' => array( 'h1' => [
'font' => array( 'font' => [
'bold' => true, 'bold' => true,
'size' => 24, 'size' => 24,
), ],
), // Bold, 24pt ], // Bold, 24pt
'h2' => array( 'h2' => [
'font' => array( 'font' => [
'bold' => true, 'bold' => true,
'size' => 18, 'size' => 18,
), ],
), // Bold, 18pt ], // Bold, 18pt
'h3' => array( 'h3' => [
'font' => array( 'font' => [
'bold' => true, 'bold' => true,
'size' => 13.5, 'size' => 13.5,
), ],
), // Bold, 13.5pt ], // Bold, 13.5pt
'h4' => array( 'h4' => [
'font' => array( 'font' => [
'bold' => true, 'bold' => true,
'size' => 12, 'size' => 12,
), ],
), // Bold, 12pt ], // Bold, 12pt
'h5' => array( 'h5' => [
'font' => array( 'font' => [
'bold' => true, 'bold' => true,
'size' => 10, 'size' => 10,
), ],
), // Bold, 10pt ], // Bold, 10pt
'h6' => array( 'h6' => [
'font' => array( 'font' => [
'bold' => true, 'bold' => true,
'size' => 7.5, 'size' => 7.5,
), ],
), // Bold, 7.5pt ], // Bold, 7.5pt
'a' => array( 'a' => [
'font' => array( 'font' => [
'underline' => true, 'underline' => true,
'color' => array( 'color' => [
'argb' => \PhpSpreadsheet\Style\Color::COLOR_BLUE, 'argb' => \PhpSpreadsheet\Style\Color::COLOR_BLUE,
), ],
), ],
), // Blue underlined ], // Blue underlined
'hr' => array( 'hr' => [
'borders' => array( 'borders' => [
'bottom' => array( 'bottom' => [
'style' => \PhpSpreadsheet\Style\Border::BORDER_THIN, 'style' => \PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => array( 'color' => [
\PhpSpreadsheet\Style\Color::COLOR_BLACK, \PhpSpreadsheet\Style\Color::COLOR_BLACK,
), ],
), ],
), ],
), // Bottom border ], // Bottom border
); ];
protected $rowspan = array(); protected $rowspan = [];
/** /**
* Create a new HTML Reader instance * Create a new HTML Reader instance
@ -117,7 +116,7 @@ class HTML extends BaseReader implements IReader
/** /**
* Validate that the current file is an HTML file * Validate that the current file is an HTML file
* *
* @return boolean * @return bool
*/ */
protected function isValidFormat() protected function isValidFormat()
{ {
@ -135,8 +134,8 @@ class HTML extends BaseReader implements IReader
* Loads PhpSpreadsheet from file * Loads PhpSpreadsheet from file
* *
* @param string $pFilename * @param string $pFilename
* @return PhpSpreadsheet
* @throws Exception * @throws Exception
* @return PhpSpreadsheet
*/ */
public function load($pFilename) public function load($pFilename)
{ {
@ -170,9 +169,9 @@ class HTML extends BaseReader implements IReader
} }
// Data Array used for testing only, should write to PhpSpreadsheet object on completion of tests // Data Array used for testing only, should write to PhpSpreadsheet object on completion of tests
protected $dataArray = array(); protected $dataArray = [];
protected $tableLevel = 0; protected $tableLevel = 0;
protected $nestedColumn = array('A'); protected $nestedColumn = ['A'];
protected function setTableStartColumn($column) protected function setTableStartColumn($column)
{ {
@ -230,11 +229,11 @@ class HTML extends BaseReader implements IReader
// TODO // TODO
} }
} elseif ($child instanceof DOMElement) { } elseif ($child instanceof DOMElement) {
// echo '<b>DOM ELEMENT: </b>' , strtoupper($child->nodeName) , '<br />'; // echo '<b>DOM ELEMENT: </b>' , strtoupper($child->nodeName) , '<br />';
$attributeArray = array(); $attributeArray = [];
foreach ($child->attributes as $attribute) { foreach ($child->attributes as $attribute) {
// echo '<b>ATTRIBUTE: </b>' , $attribute->name , ' => ' , $attribute->value , '<br />'; // echo '<b>ATTRIBUTE: </b>' , $attribute->name , ' => ' , $attribute->value , '<br />';
$attributeArray[$attribute->name] = $attribute->value; $attributeArray[$attribute->name] = $attribute->value;
} }
@ -329,7 +328,7 @@ class HTML extends BaseReader implements IReader
} else { } else {
if ($cellContent > '') { if ($cellContent > '') {
$this->flushCell($sheet, $column, $row, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent);
$row++; ++$row;
} }
// echo 'START OF PARAGRAPH: ' , '<br />'; // echo 'START OF PARAGRAPH: ' , '<br />';
$this->processDomElement($child, $sheet, $row, $column, $cellContent); $this->processDomElement($child, $sheet, $row, $column, $cellContent);
@ -340,7 +339,7 @@ class HTML extends BaseReader implements IReader
$sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]);
} }
$row++; ++$row;
$column = 'A'; $column = 'A';
} }
break; break;
@ -414,7 +413,7 @@ class HTML extends BaseReader implements IReader
if (isset($attributeArray['rowspan']) && isset($attributeArray['colspan'])) { if (isset($attributeArray['rowspan']) && isset($attributeArray['colspan'])) {
//create merging rowspan and colspan //create merging rowspan and colspan
$columnTo = $column; $columnTo = $column;
for ($i = 0; $i < $attributeArray['colspan'] - 1; $i++) { for ($i = 0; $i < $attributeArray['colspan'] - 1; ++$i) {
++$columnTo; ++$columnTo;
} }
$range = $column . $row . ':' . $columnTo . ($row + $attributeArray['rowspan'] - 1); $range = $column . $row . ':' . $columnTo . ($row + $attributeArray['rowspan'] - 1);
@ -433,7 +432,7 @@ class HTML extends BaseReader implements IReader
} elseif (isset($attributeArray['colspan'])) { } elseif (isset($attributeArray['colspan'])) {
//create merging colspan //create merging colspan
$columnTo = $column; $columnTo = $column;
for ($i = 0; $i < $attributeArray['colspan'] - 1; $i++) { for ($i = 0; $i < $attributeArray['colspan'] - 1; ++$i) {
++$columnTo; ++$columnTo;
} }
$sheet->mergeCells($column . $row . ':' . $columnTo . $row); $sheet->mergeCells($column . $row . ':' . $columnTo . $row);
@ -460,8 +459,8 @@ class HTML extends BaseReader implements IReader
* *
* @param string $pFilename * @param string $pFilename
* @param \PhpSpreadsheet\Spreadsheet $spreadsheet * @param \PhpSpreadsheet\Spreadsheet $spreadsheet
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet)
{ {
@ -469,7 +468,7 @@ class HTML extends BaseReader implements IReader
$this->openFile($pFilename); $this->openFile($pFilename);
if (!$this->isValidFormat()) { if (!$this->isValidFormat()) {
fclose($this->fileHandle); fclose($this->fileHandle);
throw new Exception($pFilename . " is an Invalid HTML file."); throw new Exception($pFilename . ' is an Invalid HTML file.');
} }
// Close after validating // Close after validating
fclose($this->fileHandle); fclose($this->fileHandle);
@ -481,7 +480,7 @@ class HTML extends BaseReader implements IReader
$spreadsheet->setActiveSheetIndex($this->sheetIndex); $spreadsheet->setActiveSheetIndex($this->sheetIndex);
// Create a new DOM object // Create a new DOM object
$dom = new domDocument; $dom = new domDocument();
// Reload the HTML file into the DOM object // Reload the HTML file into the DOM object
$loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanFile($pFilename), 'HTML-ENTITIES', 'UTF-8')); $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanFile($pFilename), 'HTML-ENTITIES', 'UTF-8'));
if ($loaded === false) { if ($loaded === false) {
@ -535,6 +534,7 @@ class HTML extends BaseReader implements IReader
if (preg_match($pattern, $xml)) { if (preg_match($pattern, $xml)) {
throw new Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); throw new Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks');
} }
return $xml; return $xml;
} }
} }

View File

@ -32,7 +32,7 @@ interface IReadFilter
* @param $column Column address (as a string value like "A", or "IV") * @param $column Column address (as a string value like "A", or "IV")
* @param $row Row number * @param $row Row number
* @param $worksheetName Optional worksheet name * @param $worksheetName Optional worksheet name
* @return boolean * @return bool
*/ */
public function readCell($column, $row, $worksheetName = ''); public function readCell($column, $row, $worksheetName = '');
} }

View File

@ -30,7 +30,7 @@ interface IReader
* Can the current IReader read the file? * Can the current IReader read the file?
* *
* @param string $pFilename * @param string $pFilename
* @return boolean * @return bool
*/ */
public function canRead($pFilename); public function canRead($pFilename);
@ -38,8 +38,8 @@ interface IReader
* Loads PhpSpreadsheet from file * Loads PhpSpreadsheet from file
* *
* @param string $pFilename * @param string $pFilename
* @return PhpSpreadsheet
* @throws Exception * @throws Exception
* @return PhpSpreadsheet
*/ */
public function load($pFilename); public function load($pFilename);
} }

View File

@ -31,28 +31,28 @@ class OOCalc extends BaseReader implements IReader
* *
* @var array * @var array
*/ */
private $styles = array(); private $styles = [];
/** /**
* Create a new OOCalc Reader instance * Create a new OOCalc Reader instance
*/ */
public function __construct() public function __construct()
{ {
$this->readFilter = new DefaultReadFilter(); $this->readFilter = new DefaultReadFilter();
} }
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
* *
* @param string $pFilename * @param string $pFilename
* @return boolean
* @throws Exception * @throws Exception
* @return bool
*/ */
public function canRead($pFilename) public function canRead($pFilename)
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$zipClass = \PhpSpreadsheet\Settings::getZipClass(); $zipClass = \PhpSpreadsheet\Settings::getZipClass();
@ -64,7 +64,7 @@ class OOCalc extends BaseReader implements IReader
$mimeType = 'UNKNOWN'; $mimeType = 'UNKNOWN';
// Load file // Load file
$zip = new $zipClass; $zip = new $zipClass();
if ($zip->open($pFilename) === true) { if ($zip->open($pFilename) === true) {
// check if it is an OOXML archive // check if it is an OOXML archive
$stat = $zip->statName('mimetype'); $stat = $zip->statName('mimetype');
@ -91,13 +91,12 @@ class OOCalc extends BaseReader implements IReader
$zip->close(); $zip->close();
return ($mimeType === 'application/vnd.oasis.opendocument.spreadsheet'); return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet';
} }
return false; return false;
} }
/** /**
* Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object
* *
@ -108,21 +107,21 @@ class OOCalc extends BaseReader implements IReader
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$zipClass = \PhpSpreadsheet\Settings::getZipClass(); $zipClass = \PhpSpreadsheet\Settings::getZipClass();
$zip = new $zipClass; $zip = new $zipClass();
if (!$zip->open($pFilename)) { if (!$zip->open($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! Error opening file."); throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
} }
$worksheetNames = array(); $worksheetNames = [];
$xml = new XMLReader(); $xml = new XMLReader();
$res = $xml->xml( $res = $xml->xml(
$this->securityScanFile('zip://'.realpath($pFilename).'#content.xml'), $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'),
null, null,
\PhpSpreadsheet\Settings::getLibXmlLoaderOptions() \PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
); );
@ -164,21 +163,21 @@ class OOCalc extends BaseReader implements IReader
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$worksheetInfo = array(); $worksheetInfo = [];
$zipClass = \PhpSpreadsheet\Settings::getZipClass(); $zipClass = \PhpSpreadsheet\Settings::getZipClass();
$zip = new $zipClass; $zip = new $zipClass();
if (!$zip->open($pFilename)) { if (!$zip->open($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! Error opening file."); throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
} }
$xml = new XMLReader(); $xml = new XMLReader();
$res = $xml->xml( $res = $xml->xml(
$this->securityScanFile('zip://'.realpath($pFilename).'#content.xml'), $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'),
null, null,
\PhpSpreadsheet\Settings::getLibXmlLoaderOptions() \PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
); );
@ -200,13 +199,13 @@ class OOCalc extends BaseReader implements IReader
if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
$worksheetNames[] = $xml->getAttribute('table:name'); $worksheetNames[] = $xml->getAttribute('table:name');
$tmpInfo = array( $tmpInfo = [
'worksheetName' => $xml->getAttribute('table:name'), 'worksheetName' => $xml->getAttribute('table:name'),
'lastColumnLetter' => 'A', 'lastColumnLetter' => 'A',
'lastColumnIndex' => 0, 'lastColumnIndex' => 0,
'totalRows' => 0, 'totalRows' => 0,
'totalColumns' => 0, 'totalColumns' => 0,
); ];
// Loop through each child node of the table:table element reading // Loop through each child node of the table:table element reading
$currCells = 0; $currCells = 0;
@ -223,7 +222,7 @@ class OOCalc extends BaseReader implements IReader
do { do {
if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
if (!$xml->isEmptyElement) { if (!$xml->isEmptyElement) {
$currCells++; ++$currCells;
$xml->next(); $xml->next();
} else { } else {
$xml->read(); $xml->read();
@ -287,8 +286,8 @@ class OOCalc extends BaseReader implements IReader
* Loads PhpSpreadsheet from file * Loads PhpSpreadsheet from file
* *
* @param string $pFilename * @param string $pFilename
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function load($pFilename) public function load($pFilename)
{ {
@ -305,9 +304,11 @@ class OOCalc extends BaseReader implements IReader
foreach ($styleList as $style) { foreach ($styleList as $style) {
if ($styleAttributeValue == strtolower($style)) { if ($styleAttributeValue == strtolower($style)) {
$styleAttributeValue = $style; $styleAttributeValue = $style;
return true; return true;
} }
} }
return false; return false;
} }
@ -316,14 +317,14 @@ class OOCalc extends BaseReader implements IReader
* *
* @param string $pFilename * @param string $pFilename
* @param \PhpSpreadsheet\Spreadsheet $spreadsheet * @param \PhpSpreadsheet\Spreadsheet $spreadsheet
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet)
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
} }
$timezoneObj = new DateTimeZone('Europe/London'); $timezoneObj = new DateTimeZone('Europe/London');
@ -331,14 +332,14 @@ class OOCalc extends BaseReader implements IReader
$zipClass = \PhpSpreadsheet\Settings::getZipClass(); $zipClass = \PhpSpreadsheet\Settings::getZipClass();
$zip = new $zipClass; $zip = new $zipClass();
if (!$zip->open($pFilename)) { if (!$zip->open($pFilename)) {
throw new Exception("Could not open " . $pFilename . " for reading! Error opening file."); throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
} }
// echo '<h1>Meta Information</h1>'; // echo '<h1>Meta Information</h1>';
$xml = simplexml_load_string( $xml = simplexml_load_string(
$this->securityScan($zip->getFromName("meta.xml")), $this->securityScan($zip->getFromName('meta.xml')),
'SimpleXMLElement', 'SimpleXMLElement',
\PhpSpreadsheet\Settings::getLibXmlLoaderOptions() \PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
); );
@ -350,7 +351,7 @@ class OOCalc extends BaseReader implements IReader
$docProps = $spreadsheet->getProperties(); $docProps = $spreadsheet->getProperties();
$officeProperty = $xml->children($namespacesMeta['office']); $officeProperty = $xml->children($namespacesMeta['office']);
foreach ($officeProperty as $officePropertyData) { foreach ($officeProperty as $officePropertyData) {
$officePropertyDC = array(); $officePropertyDC = [];
if (isset($namespacesMeta['dc'])) { if (isset($namespacesMeta['dc'])) {
$officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
} }
@ -377,7 +378,7 @@ class OOCalc extends BaseReader implements IReader
break; break;
} }
} }
$officePropertyMeta = array(); $officePropertyMeta = [];
if (isset($namespacesMeta['dc'])) { if (isset($namespacesMeta['dc'])) {
$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
} }
@ -425,10 +426,9 @@ class OOCalc extends BaseReader implements IReader
} }
} }
// echo '<h1>Workbook Content</h1>'; // echo '<h1>Workbook Content</h1>';
$xml = simplexml_load_string( $xml = simplexml_load_string(
$this->securityScan($zip->getFromName("content.xml")), $this->securityScan($zip->getFromName('content.xml')),
'SimpleXMLElement', 'SimpleXMLElement',
\PhpSpreadsheet\Settings::getLibXmlLoaderOptions() \PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
); );
@ -467,7 +467,7 @@ class OOCalc extends BaseReader implements IReader
$rowID = 1; $rowID = 1;
foreach ($worksheetData as $key => $rowData) { foreach ($worksheetData as $key => $rowData) {
// echo '<b>'.$key.'</b><br />'; // echo '<b>'.$key.'</b><br />';
switch ($key) { switch ($key) {
case 'table-header-rows': case 'table-header-rows':
foreach ($rowData as $keyRowData => $cellData) { foreach ($rowData as $keyRowData => $cellData) {
@ -509,13 +509,13 @@ class OOCalc extends BaseReader implements IReader
} }
if (isset($cellDataOffice->annotation)) { if (isset($cellDataOffice->annotation)) {
// echo 'Cell has comment<br />'; // echo 'Cell has comment<br />';
$annotationText = $cellDataOffice->annotation->children($namespacesContent['text']); $annotationText = $cellDataOffice->annotation->children($namespacesContent['text']);
$textArray = array(); $textArray = [];
foreach ($annotationText as $t) { foreach ($annotationText as $t) {
if (isset($t->span)) { if (isset($t->span)) {
foreach ($t->span as $text) { foreach ($t->span as $text) {
$textArray[] = (string)$text; $textArray[] = (string) $text;
} }
} else { } else {
$textArray[] = (string) $t; $textArray[] = (string) $t;
@ -523,13 +523,13 @@ class OOCalc extends BaseReader implements IReader
} }
$text = implode("\n", $textArray); $text = implode("\n", $textArray);
// echo $text, '<br />'; // echo $text, '<br />';
$spreadsheet->getActiveSheet()->getComment($columnID.$rowID)->setText($this->parseRichText($text)); $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setText($this->parseRichText($text));
// ->setAuthor( $author ) // ->setAuthor( $author )
} }
if (isset($cellDataText->p)) { if (isset($cellDataText->p)) {
// Consolidate if there are multiple p records (maybe with spans as well) // Consolidate if there are multiple p records (maybe with spans as well)
$dataArray = array(); $dataArray = [];
// Text can have multiple text:p and within those, multiple text:span. // Text can have multiple text:p and within those, multiple text:span.
// text:p newlines, but text:span does not. // text:p newlines, but text:span does not.
// Also, here we assume there is no text data is span fields are specified, since // Also, here we assume there is no text data is span fields are specified, since
@ -537,7 +537,7 @@ class OOCalc extends BaseReader implements IReader
foreach ($cellDataText->p as $pData) { foreach ($cellDataText->p as $pData) {
if (isset($pData->span)) { if (isset($pData->span)) {
// span sections do not newline, so we just create one large string here // span sections do not newline, so we just create one large string here
$spanSection = ""; $spanSection = '';
foreach ($pData->span as $spanData) { foreach ($pData->span as $spanData) {
$spanSection .= $spanData; $spanSection .= $spanData;
} }
@ -597,14 +597,14 @@ class OOCalc extends BaseReader implements IReader
list($year, $month, $day, $hour, $minute, $second) = explode(' ', $dateObj->format('Y m d H i s')); list($year, $month, $day, $hour, $minute, $second) = explode(' ', $dateObj->format('Y m d H i s'));
$dataValue = \PhpSpreadsheet\Shared\Date::formattedPHPToExcel($year, $month, $day, $hour, $minute, $second); $dataValue = \PhpSpreadsheet\Shared\Date::formattedPHPToExcel($year, $month, $day, $hour, $minute, $second);
if ($dataValue != floor($dataValue)) { if ($dataValue != floor($dataValue)) {
$formatting = \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15.' '.\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4; $formatting = \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15 . ' ' . \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4;
} else { } else {
$formatting = \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15; $formatting = \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15;
} }
break; break;
case 'time': case 'time':
$type = \PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC; $type = \PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
$dataValue = \PhpSpreadsheet\Shared\Date::PHPToExcel(strtotime('01-01-1970 '.implode(':', sscanf($cellDataOfficeAttributes['time-value'], 'PT%dH%dM%dS')))); $dataValue = \PhpSpreadsheet\Shared\Date::PHPToExcel(strtotime('01-01-1970 ' . implode(':', sscanf($cellDataOfficeAttributes['time-value'], 'PT%dH%dM%dS'))));
$formatting = \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4; $formatting = \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4;
break; break;
} }
@ -620,7 +620,7 @@ class OOCalc extends BaseReader implements IReader
if ($hasCalculatedValue) { if ($hasCalculatedValue) {
$type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA; $type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA;
// echo 'Formula: ', $cellDataFormula, PHP_EOL; // echo 'Formula: ', $cellDataFormula, PHP_EOL;
$cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=')+1); $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1);
$temp = explode('"', $cellDataFormula); $temp = explode('"', $cellDataFormula);
$tKey = false; $tKey = false;
foreach ($temp as &$value) { foreach ($temp as &$value) {
@ -648,18 +648,18 @@ class OOCalc extends BaseReader implements IReader
if ($type !== \PhpSpreadsheet\Cell\DataType::TYPE_NULL) { if ($type !== \PhpSpreadsheet\Cell\DataType::TYPE_NULL) {
for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) { for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) {
$rID = $rowID + $rowAdjust; $rID = $rowID + $rowAdjust;
$spreadsheet->getActiveSheet()->getCell($columnID.$rID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $dataValue), $type); $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $dataValue), $type);
if ($hasCalculatedValue) { if ($hasCalculatedValue) {
// echo 'Forumla result is '.$dataValue.'<br />'; // echo 'Forumla result is '.$dataValue.'<br />';
$spreadsheet->getActiveSheet()->getCell($columnID.$rID)->setCalculatedValue($dataValue); $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->setCalculatedValue($dataValue);
} }
if ($formatting !== null) { if ($formatting !== null) {
$spreadsheet->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode($formatting); $spreadsheet->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode($formatting);
} else { } else {
$spreadsheet->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL); $spreadsheet->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL);
} }
if ($hyperlink !== null) { if ($hyperlink !== null) {
$spreadsheet->getActiveSheet()->getCell($columnID.$rID)->getHyperlink()->setUrl($hyperlink); $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->getHyperlink()->setUrl($hyperlink);
} }
} }
} }
@ -671,13 +671,13 @@ class OOCalc extends BaseReader implements IReader
if (($type !== \PhpSpreadsheet\Cell\DataType::TYPE_NULL) || (!$this->readDataOnly)) { if (($type !== \PhpSpreadsheet\Cell\DataType::TYPE_NULL) || (!$this->readDataOnly)) {
$columnTo = $columnID; $columnTo = $columnID;
if (isset($cellDataTableAttributes['number-columns-spanned'])) { if (isset($cellDataTableAttributes['number-columns-spanned'])) {
$columnTo = \PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] -2); $columnTo = \PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] - 2);
} }
$rowTo = $rowID; $rowTo = $rowID;
if (isset($cellDataTableAttributes['number-rows-spanned'])) { if (isset($cellDataTableAttributes['number-rows-spanned'])) {
$rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1; $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1;
} }
$cellRange = $columnID.$rowID.':'.$columnTo.$rowTo; $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo;
$spreadsheet->getActiveSheet()->mergeCells($cellRange); $spreadsheet->getActiveSheet()->mergeCells($cellRange);
} }
} }

View File

@ -45,7 +45,7 @@ class SYLK extends BaseReader implements IReader
* *
* @var array * @var array
*/ */
private $formats = array(); private $formats = [];
/** /**
* Format Count * Format Count
@ -65,7 +65,7 @@ class SYLK extends BaseReader implements IReader
/** /**
* Validate that the current file is a SYLK file * Validate that the current file is a SYLK file
* *
* @return boolean * @return bool
*/ */
protected function isValidFormat() protected function isValidFormat()
{ {
@ -95,6 +95,7 @@ class SYLK extends BaseReader implements IReader
public function setInputEncoding($pValue = 'ANSI') public function setInputEncoding($pValue = 'ANSI')
{ {
$this->inputEncoding = $pValue; $this->inputEncoding = $pValue;
return $this; return $this;
} }
@ -120,12 +121,12 @@ class SYLK extends BaseReader implements IReader
$this->openFile($pFilename); $this->openFile($pFilename);
if (!$this->isValidFormat()) { if (!$this->isValidFormat()) {
fclose($this->fileHandle); fclose($this->fileHandle);
throw new Exception($pFilename . " is an Invalid Spreadsheet file."); throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
} }
$fileHandle = $this->fileHandle; $fileHandle = $this->fileHandle;
rewind($fileHandle); rewind($fileHandle);
$worksheetInfo = array(); $worksheetInfo = [];
$worksheetInfo[0]['worksheetName'] = 'Worksheet'; $worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0; $worksheetInfo[0]['lastColumnIndex'] = 0;
@ -133,7 +134,7 @@ class SYLK extends BaseReader implements IReader
$worksheetInfo[0]['totalColumns'] = 0; $worksheetInfo[0]['totalColumns'] = 0;
// Loop through file // Loop through file
$rowData = array(); $rowData = [];
// loop through one row (line) at a time in the file // loop through one row (line) at a time in the file
$rowIndex = 0; $rowIndex = 0;
@ -181,8 +182,8 @@ class SYLK extends BaseReader implements IReader
* Loads PhpSpreadsheet from file * Loads PhpSpreadsheet from file
* *
* @param string $pFilename * @param string $pFilename
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function load($pFilename) public function load($pFilename)
{ {
@ -198,8 +199,8 @@ class SYLK extends BaseReader implements IReader
* *
* @param string $pFilename * @param string $pFilename
* @param \PhpSpreadsheet\Spreadsheet $spreadsheet * @param \PhpSpreadsheet\Spreadsheet $spreadsheet
* @return \PhpSpreadsheet\Spreadsheet
* @throws Exception * @throws Exception
* @return \PhpSpreadsheet\Spreadsheet
*/ */
public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet)
{ {
@ -207,7 +208,7 @@ class SYLK extends BaseReader implements IReader
$this->openFile($pFilename); $this->openFile($pFilename);
if (!$this->isValidFormat()) { if (!$this->isValidFormat()) {
fclose($this->fileHandle); fclose($this->fileHandle);
throw new Exception($pFilename . " is an Invalid Spreadsheet file."); throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
} }
$fileHandle = $this->fileHandle; $fileHandle = $this->fileHandle;
rewind($fileHandle); rewind($fileHandle);
@ -218,11 +219,11 @@ class SYLK extends BaseReader implements IReader
} }
$spreadsheet->setActiveSheetIndex($this->sheetIndex); $spreadsheet->setActiveSheetIndex($this->sheetIndex);
$fromFormats = array('\-', '\ '); $fromFormats = ['\-', '\ '];
$toFormats = array('-', ' '); $toFormats = ['-', ' '];
// Loop through file // Loop through file
$rowData = array(); $rowData = [];
$column = $row = ''; $column = $row = '';
// loop through one row (line) at a time in the file // loop through one row (line) at a time in the file
@ -237,7 +238,7 @@ class SYLK extends BaseReader implements IReader
$dataType = array_shift($rowData); $dataType = array_shift($rowData);
// Read shared styles // Read shared styles
if ($dataType == 'P') { if ($dataType == 'P') {
$formatArray = array(); $formatArray = [];
foreach ($rowData as $rowDatum) { foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) { switch ($rowDatum{0}) {
case 'P': case 'P':
@ -252,7 +253,7 @@ class SYLK extends BaseReader implements IReader
break; break;
case 'S': case 'S':
$styleSettings = substr($rowDatum, 1); $styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) { for ($i = 0; $i < strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) { switch ($styleSettings{$i}) {
case 'I': case 'I':
$formatArray['font']['italic'] = true; $formatArray['font']['italic'] = true;
@ -277,7 +278,7 @@ class SYLK extends BaseReader implements IReader
break; break;
} }
} }
$this->formats['P'.$this->format++] = $formatArray; $this->formats['P' . $this->format++] = $formatArray;
// Read cell value data // Read cell value data
} elseif ($dataType == 'C') { } elseif ($dataType == 'C') {
$hasCalculatedValue = false; $hasCalculatedValue = false;
@ -296,14 +297,14 @@ class SYLK extends BaseReader implements IReader
$cellData = substr($rowDatum, 1); $cellData = substr($rowDatum, 1);
break; break;
case 'E': case 'E':
$cellDataFormula = '='.substr($rowDatum, 1); $cellDataFormula = '=' . substr($rowDatum, 1);
// Convert R1C1 style references to A1 style references (but only when not quoted) // Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"', $cellDataFormula); $temp = explode('"', $cellDataFormula);
$key = false; $key = false;
foreach ($temp as &$value) { foreach ($temp as &$value) {
// Only count/replace in alternate array entries // Only count/replace in alternate array entries
if ($key = !$key) { if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER+PREG_OFFSET_CAPTURE); preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through // through the formula from left to right. Reversing means that we work right to left.through
// the formula // the formula
@ -329,7 +330,7 @@ class SYLK extends BaseReader implements IReader
if ($columnReference{0} == '[') { if ($columnReference{0} == '[') {
$columnReference = $column + trim($columnReference, '[]'); $columnReference = $column + trim($columnReference, '[]');
} }
$A1CellReference = \PhpSpreadsheet\Cell::stringFromColumnIndex($columnReference-1).$rowReference; $A1CellReference = \PhpSpreadsheet\Cell::stringFromColumnIndex($columnReference - 1) . $rowReference;
$value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
} }
@ -342,19 +343,19 @@ class SYLK extends BaseReader implements IReader
break; break;
} }
} }
$columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1);
$cellData = \PhpSpreadsheet\Calculation::unwrapResult($cellData); $cellData = \PhpSpreadsheet\Calculation::unwrapResult($cellData);
// Set cell value // Set cell value
$spreadsheet->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) { if ($hasCalculatedValue) {
$cellData = \PhpSpreadsheet\Calculation::unwrapResult($cellData); $cellData = \PhpSpreadsheet\Calculation::unwrapResult($cellData);
$spreadsheet->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData); $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setCalculatedValue($cellData);
} }
// Read cell formatting // Read cell formatting
} elseif ($dataType == 'F') { } elseif ($dataType == 'F') {
$formatStyle = $columnWidth = $styleSettings = ''; $formatStyle = $columnWidth = $styleSettings = '';
$styleData = array(); $styleData = [];
foreach ($rowData as $rowDatum) { foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) { switch ($rowDatum{0}) {
case 'C': case 'C':
@ -373,7 +374,7 @@ class SYLK extends BaseReader implements IReader
break; break;
case 'S': case 'S':
$styleSettings = substr($rowDatum, 1); $styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) { for ($i = 0; $i < strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) { switch ($styleSettings{$i}) {
case 'I': case 'I':
$styleData['font']['italic'] = true; $styleData['font']['italic'] = true;
@ -399,22 +400,22 @@ class SYLK extends BaseReader implements IReader
} }
} }
if (($formatStyle > '') && ($column > '') && ($row > '')) { if (($formatStyle > '') && ($column > '') && ($row > '')) {
$columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1);
if (isset($this->formats[$formatStyle])) { if (isset($this->formats[$formatStyle])) {
$spreadsheet->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->formats[$formatStyle]); $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->formats[$formatStyle]);
} }
} }
if ((!empty($styleData)) && ($column > '') && ($row > '')) { if ((!empty($styleData)) && ($column > '') && ($row > '')) {
$columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1);
$spreadsheet->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData); $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData);
} }
if ($columnWidth > '') { if ($columnWidth > '') {
if ($startCol == $endCol) { if ($startCol == $endCol) {
$startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol-1); $startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol - 1);
$spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else { } else {
$startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol-1); $startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol - 1);
$endCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($endCol-1); $endCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($endCol - 1);
$spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
do { do {
$spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
@ -463,6 +464,7 @@ class SYLK extends BaseReader implements IReader
public function setSheetIndex($pValue = 0) public function setSheetIndex($pValue = 0)
{ {
$this->sheetIndex = $pValue; $this->sheetIndex = $pValue;
return $this; return $this;
} }
} }

View File

@ -28,10 +28,10 @@ class ReferenceHelper
{ {
/** Constants */ /** Constants */
/** Regular Expressions */ /** Regular Expressions */
const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?<![:a-z\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])'; const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?<![:a-z\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])';
const REFHELPER_REGEXP_CELLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)'; const REFHELPER_REGEXP_CELLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)';
const REFHELPER_REGEXP_ROWRANGE = '((\w*|\'[^!]*\')!)?(\$?\d+):(\$?\d+)'; const REFHELPER_REGEXP_ROWRANGE = '((\w*|\'[^!]*\')!)?(\$?\d+):(\$?\d+)';
const REFHELPER_REGEXP_COLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; const REFHELPER_REGEXP_COLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})';
/** /**
* Instance of this class * Instance of this class
@ -48,7 +48,7 @@ class ReferenceHelper
public static function getInstance() public static function getInstance()
{ {
if (!isset(self::$instance) || (self::$instance === null)) { if (!isset(self::$instance) || (self::$instance === null)) {
self::$instance = new ReferenceHelper(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
@ -67,7 +67,7 @@ class ReferenceHelper
* *
* @param string $a First column to test (e.g. 'AA') * @param string $a First column to test (e.g. 'AA')
* @param string $b Second column to test (e.g. 'Z') * @param string $b Second column to test (e.g. 'Z')
* @return integer * @return int
*/ */
public static function columnSort($a, $b) public static function columnSort($a, $b)
{ {
@ -80,7 +80,7 @@ class ReferenceHelper
* *
* @param string $a First column to test (e.g. 'AA') * @param string $a First column to test (e.g. 'AA')
* @param string $b Second column to test (e.g. 'Z') * @param string $b Second column to test (e.g. 'Z')
* @return integer * @return int
*/ */
public static function columnReverseSort($a, $b) public static function columnReverseSort($a, $b)
{ {
@ -93,7 +93,7 @@ class ReferenceHelper
* *
* @param string $a First cell to test (e.g. 'AA1') * @param string $a First cell to test (e.g. 'AA1')
* @param string $b Second cell to test (e.g. 'Z1') * @param string $b Second cell to test (e.g. 'Z1')
* @return integer * @return int
*/ */
public static function cellSort($a, $b) public static function cellSort($a, $b)
{ {
@ -103,6 +103,7 @@ class ReferenceHelper
if ($ar == $br) { if ($ar == $br) {
return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
} }
return ($ar < $br) ? -1 : 1; return ($ar < $br) ? -1 : 1;
} }
@ -112,7 +113,7 @@ class ReferenceHelper
* *
* @param string $a First cell to test (e.g. 'AA1') * @param string $a First cell to test (e.g. 'AA1')
* @param string $b Second cell to test (e.g. 'Z1') * @param string $b Second cell to test (e.g. 'Z1')
* @return integer * @return int
*/ */
public static function cellReverseSort($a, $b) public static function cellReverseSort($a, $b)
{ {
@ -122,6 +123,7 @@ class ReferenceHelper
if ($ar == $br) { if ($ar == $br) {
return 1 - strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); return 1 - strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
} }
return ($ar < $br) ? 1 : -1; return ($ar < $br) ? 1 : -1;
} }
@ -129,11 +131,11 @@ class ReferenceHelper
* Test whether a cell address falls within a defined range of cells * Test whether a cell address falls within a defined range of cells
* *
* @param string $cellAddress Address of the cell we're testing * @param string $cellAddress Address of the cell we're testing
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @return boolean * @return bool
*/ */
private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)
{ {
@ -149,6 +151,7 @@ class ReferenceHelper
($cellColumnIndex < $beforeColumnIndex)) { ($cellColumnIndex < $beforeColumnIndex)) {
return true; return true;
} }
return false; return false;
} }
@ -157,17 +160,17 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustPageBreaks(Worksheet $pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustPageBreaks(Worksheet $pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
$aBreaks = $pSheet->getBreaks(); $aBreaks = $pSheet->getBreaks();
($pNumCols > 0 || $pNumRows > 0) ? ($pNumCols > 0 || $pNumRows > 0) ?
uksort($aBreaks, array('self','cellReverseSort')) : uksort($aBreaks, ['self', 'cellReverseSort']) :
uksort($aBreaks, array('self','cellSort')); uksort($aBreaks, ['self', 'cellSort']);
foreach ($aBreaks as $key => $value) { foreach ($aBreaks as $key => $value) {
if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) {
@ -191,15 +194,15 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
$aComments = $pSheet->getComments(); $aComments = $pSheet->getComments();
$aNewComments = array(); // the new array of all comments $aNewComments = []; // the new array of all comments
foreach ($aComments as $key => &$value) { foreach ($aComments as $key => &$value) {
// Any comments inside a deleted range will be ignored // Any comments inside a deleted range will be ignored
@ -218,17 +221,17 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
$aHyperlinkCollection = $pSheet->getHyperlinkCollection(); $aHyperlinkCollection = $pSheet->getHyperlinkCollection();
($pNumCols > 0 || $pNumRows > 0) ? ($pNumCols > 0 || $pNumRows > 0) ?
uksort($aHyperlinkCollection, array('self','cellReverseSort')) : uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) :
uksort($aHyperlinkCollection, array('self','cellSort')); uksort($aHyperlinkCollection, ['self', 'cellSort']);
foreach ($aHyperlinkCollection as $key => $value) { foreach ($aHyperlinkCollection as $key => $value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
@ -244,17 +247,17 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
$aDataValidationCollection = $pSheet->getDataValidationCollection(); $aDataValidationCollection = $pSheet->getDataValidationCollection();
($pNumCols > 0 || $pNumRows > 0) ? ($pNumCols > 0 || $pNumRows > 0) ?
uksort($aDataValidationCollection, array('self','cellReverseSort')) : uksort($aDataValidationCollection, ['self', 'cellReverseSort']) :
uksort($aDataValidationCollection, array('self','cellSort')); uksort($aDataValidationCollection, ['self', 'cellSort']);
foreach ($aDataValidationCollection as $key => $value) { foreach ($aDataValidationCollection as $key => $value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
@ -270,15 +273,15 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
$aMergeCells = $pSheet->getMergeCells(); $aMergeCells = $pSheet->getMergeCells();
$aNewMergeCells = array(); // the new array of all merge cells $aNewMergeCells = []; // the new array of all merge cells
foreach ($aMergeCells as $key => &$value) { foreach ($aMergeCells as $key => &$value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
$aNewMergeCells[$newReference] = $newReference; $aNewMergeCells[$newReference] = $newReference;
@ -291,17 +294,17 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
$aProtectedCells = $pSheet->getProtectedCells(); $aProtectedCells = $pSheet->getProtectedCells();
($pNumCols > 0 || $pNumRows > 0) ? ($pNumCols > 0 || $pNumRows > 0) ?
uksort($aProtectedCells, array('self','cellReverseSort')) : uksort($aProtectedCells, ['self', 'cellReverseSort']) :
uksort($aProtectedCells, array('self','cellSort')); uksort($aProtectedCells, ['self', 'cellSort']);
foreach ($aProtectedCells as $key => $value) { foreach ($aProtectedCells as $key => $value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
if ($key != $newReference) { if ($key != $newReference) {
@ -316,10 +319,10 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
@ -341,10 +344,10 @@ class ReferenceHelper
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $beforeRow Number of the row we're inserting/deleting before * @param int $beforeRow Number of the row we're inserting/deleting before
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
{ {
@ -374,8 +377,8 @@ class ReferenceHelper
* Insert a new column or row, updating all possible related data * Insert a new column or row, updating all possible related data
* *
* @param string $pBefore Insert before this cell address (e.g. 'A1') * @param string $pBefore Insert before this cell address (e.g. 'A1')
* @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
* @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $pSheet The worksheet that we're editing
* @throws Exception * @throws Exception
*/ */
@ -385,14 +388,14 @@ class ReferenceHelper
$aCellCollection = $pSheet->getCellCollection(); $aCellCollection = $pSheet->getCellCollection();
// Get coordinates of $pBefore // Get coordinates of $pBefore
$beforeColumn = 'A'; $beforeColumn = 'A';
$beforeRow = 1; $beforeRow = 1;
list($beforeColumn, $beforeRow) = Cell::coordinateFromString($pBefore); list($beforeColumn, $beforeRow) = Cell::coordinateFromString($pBefore);
$beforeColumnIndex = Cell::columnIndexFromString($beforeColumn); $beforeColumnIndex = Cell::columnIndexFromString($beforeColumn);
// Clear cells if we are removing columns or rows // Clear cells if we are removing columns or rows
$highestColumn = $pSheet->getHighestColumn(); $highestColumn = $pSheet->getHighestColumn();
$highestRow = $pSheet->getHighestRow(); $highestRow = $pSheet->getHighestRow();
// 1. Clear column strips if we are removing columns // 1. Clear column strips if we are removing columns
if ($pNumCols < 0 && $beforeColumnIndex - 2 + $pNumCols > 0) { if ($pNumCols < 0 && $beforeColumnIndex - 2 + $pNumCols > 0) {
@ -431,12 +434,12 @@ class ReferenceHelper
$cell = $pSheet->getCell($cellID); $cell = $pSheet->getCell($cellID);
$cellIndex = Cell::columnIndexFromString($cell->getColumn()); $cellIndex = Cell::columnIndexFromString($cell->getColumn());
if ($cellIndex-1 + $pNumCols < 0) { if ($cellIndex - 1 + $pNumCols < 0) {
continue; continue;
} }
// New coordinates // New coordinates
$newCoordinates = Cell::stringFromColumnIndex($cellIndex-1 + $pNumCols) . ($cell->getRow() + $pNumRows); $newCoordinates = Cell::stringFromColumnIndex($cellIndex - 1 + $pNumCols) . ($cell->getRow() + $pNumRows);
// Should the cell be updated? Move value and cellXf index from one cell to another. // Should the cell be updated? Move value and cellXf index from one cell to another.
if (($cellIndex >= $beforeColumnIndex) && ($cell->getRow() >= $beforeRow)) { if (($cellIndex >= $beforeColumnIndex) && ($cell->getRow() >= $beforeRow)) {
@ -466,8 +469,8 @@ class ReferenceHelper
} }
// Duplicate styles for the newly inserted cells // Duplicate styles for the newly inserted cells
$highestColumn = $pSheet->getHighestColumn(); $highestColumn = $pSheet->getHighestColumn();
$highestRow = $pSheet->getHighestRow(); $highestRow = $pSheet->getHighestRow();
if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) { if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) {
for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
@ -480,7 +483,7 @@ class ReferenceHelper
for ($j = $beforeColumnIndex - 1; $j <= $beforeColumnIndex - 2 + $pNumCols; ++$j) { for ($j = $beforeColumnIndex - 1; $j <= $beforeColumnIndex - 2 + $pNumCols; ++$j) {
$pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
if ($conditionalStyles) { if ($conditionalStyles) {
$cloned = array(); $cloned = [];
foreach ($conditionalStyles as $conditionalStyle) { foreach ($conditionalStyles as $conditionalStyle) {
$cloned[] = clone $conditionalStyle; $cloned[] = clone $conditionalStyle;
} }
@ -502,7 +505,7 @@ class ReferenceHelper
for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) { for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) {
$pSheet->getCell(Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); $pSheet->getCell(Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
if ($conditionalStyles) { if ($conditionalStyles) {
$cloned = array(); $cloned = [];
foreach ($conditionalStyles as $conditionalStyle) { foreach ($conditionalStyles as $conditionalStyle) {
$cloned[] = clone $conditionalStyle; $cloned[] = clone $conditionalStyle;
} }
@ -565,23 +568,23 @@ class ReferenceHelper
// Shuffle columns in autofilter range // Shuffle columns in autofilter range
if ($pNumCols > 0) { if ($pNumCols > 0) {
// For insert, we shuffle from end to beginning to avoid overwriting // For insert, we shuffle from end to beginning to avoid overwriting
$startColID = Cell::stringFromColumnIndex($startCol-1); $startColID = Cell::stringFromColumnIndex($startCol - 1);
$toColID = Cell::stringFromColumnIndex($startCol+$pNumCols-1); $toColID = Cell::stringFromColumnIndex($startCol + $pNumCols - 1);
$endColID = Cell::stringFromColumnIndex($rangeEnd[0]); $endColID = Cell::stringFromColumnIndex($rangeEnd[0]);
$startColRef = $startCol; $startColRef = $startCol;
$endColRef = $rangeEnd[0]; $endColRef = $rangeEnd[0];
$toColRef = $rangeEnd[0]+$pNumCols; $toColRef = $rangeEnd[0] + $pNumCols;
do { do {
$autoFilter->shiftColumn(Cell::stringFromColumnIndex($endColRef-1), Cell::stringFromColumnIndex($toColRef-1)); $autoFilter->shiftColumn(Cell::stringFromColumnIndex($endColRef - 1), Cell::stringFromColumnIndex($toColRef - 1));
--$endColRef; --$endColRef;
--$toColRef; --$toColRef;
} while ($startColRef <= $endColRef); } while ($startColRef <= $endColRef);
} else { } else {
// For delete, we shuffle from beginning to end to avoid overwriting // For delete, we shuffle from beginning to end to avoid overwriting
$startColID = Cell::stringFromColumnIndex($startCol-1); $startColID = Cell::stringFromColumnIndex($startCol - 1);
$toColID = Cell::stringFromColumnIndex($startCol+$pNumCols-1); $toColID = Cell::stringFromColumnIndex($startCol + $pNumCols - 1);
$endColID = Cell::stringFromColumnIndex($rangeEnd[0]); $endColID = Cell::stringFromColumnIndex($rangeEnd[0]);
do { do {
$autoFilter->shiftColumn($startColID, $toColID); $autoFilter->shiftColumn($startColID, $toColID);
@ -635,8 +638,8 @@ class ReferenceHelper
* @param int $pNumCols Number of columns to insert * @param int $pNumCols Number of columns to insert
* @param int $pNumRows Number of rows to insert * @param int $pNumRows Number of rows to insert
* @param string $sheetName Worksheet name/title * @param string $sheetName Worksheet name/title
* @return string Updated formula
* @throws Exception * @throws Exception
* @return string Updated formula
*/ */
public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '')
{ {
@ -647,95 +650,95 @@ class ReferenceHelper
// Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
if ($i = !$i) { if ($i = !$i) {
$adjustCount = 0; $adjustCount = 0;
$newCellTokens = $cellTokens = array(); $newCellTokens = $cellTokens = [];
// Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5) // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5)
$matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_ROWRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
if ($matchCount > 0) { if ($matchCount > 0) {
foreach ($matches as $match) { foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2].'!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3].':'.$match[4]; $fromString .= $match[3] . ':' . $match[4];
$modified3 = substr($this->updateCellReference('$A'.$match[3], $pBefore, $pNumCols, $pNumRows), 2); $modified3 = substr($this->updateCellReference('$A' . $match[3], $pBefore, $pNumCols, $pNumRows), 2);
$modified4 = substr($this->updateCellReference('$A'.$match[4], $pBefore, $pNumCols, $pNumRows), 2); $modified4 = substr($this->updateCellReference('$A' . $match[4], $pBefore, $pNumCols, $pNumRows), 2);
if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
$toString = ($match[2] > '') ? $match[2].'!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3.':'.$modified4; $toString .= $modified3 . ':' . $modified4;
// Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
$column = 100000; $column = 100000;
$row = 10000000 + trim($match[3], '$'); $row = 10000000 + trim($match[3], '$');
$cellIndex = $column.$row; $cellIndex = $column . $row;
$newCellTokens[$cellIndex] = preg_quote($toString); $newCellTokens[$cellIndex] = preg_quote($toString);
$cellTokens[$cellIndex] = '/(?<!\d\$\!)'.preg_quote($fromString).'(?!\d)/i'; $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString) . '(?!\d)/i';
++$adjustCount; ++$adjustCount;
} }
} }
} }
} }
// Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E) // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E)
$matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_COLRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
if ($matchCount > 0) { if ($matchCount > 0) {
foreach ($matches as $match) { foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2].'!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3].':'.$match[4]; $fromString .= $match[3] . ':' . $match[4];
$modified3 = substr($this->updateCellReference($match[3].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); $modified3 = substr($this->updateCellReference($match[3] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2);
$modified4 = substr($this->updateCellReference($match[4].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); $modified4 = substr($this->updateCellReference($match[4] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2);
if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
$toString = ($match[2] > '') ? $match[2].'!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3.':'.$modified4; $toString .= $modified3 . ':' . $modified4;
// Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
$column = Cell::columnIndexFromString(trim($match[3], '$')) + 100000; $column = Cell::columnIndexFromString(trim($match[3], '$')) + 100000;
$row = 10000000; $row = 10000000;
$cellIndex = $column.$row; $cellIndex = $column . $row;
$newCellTokens[$cellIndex] = preg_quote($toString); $newCellTokens[$cellIndex] = preg_quote($toString);
$cellTokens[$cellIndex] = '/(?<![A-Z\$\!])'.preg_quote($fromString).'(?![A-Z])/i'; $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString) . '(?![A-Z])/i';
++$adjustCount; ++$adjustCount;
} }
} }
} }
} }
// Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5) // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5)
$matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
if ($matchCount > 0) { if ($matchCount > 0) {
foreach ($matches as $match) { foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2].'!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3].':'.$match[4]; $fromString .= $match[3] . ':' . $match[4];
$modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows);
$modified4 = $this->updateCellReference($match[4], $pBefore, $pNumCols, $pNumRows); $modified4 = $this->updateCellReference($match[4], $pBefore, $pNumCols, $pNumRows);
if ($match[3].$match[4] !== $modified3.$modified4) { if ($match[3] . $match[4] !== $modified3 . $modified4) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
$toString = ($match[2] > '') ? $match[2].'!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3.':'.$modified4; $toString .= $modified3 . ':' . $modified4;
list($column, $row) = Cell::coordinateFromString($match[3]); list($column, $row) = Cell::coordinateFromString($match[3]);
// Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
$column = Cell::columnIndexFromString(trim($column, '$')) + 100000; $column = Cell::columnIndexFromString(trim($column, '$')) + 100000;
$row = trim($row, '$') + 10000000; $row = trim($row, '$') + 10000000;
$cellIndex = $column.$row; $cellIndex = $column . $row;
$newCellTokens[$cellIndex] = preg_quote($toString); $newCellTokens[$cellIndex] = preg_quote($toString);
$cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)'.preg_quote($fromString).'(?!\d)/i'; $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString) . '(?!\d)/i';
++$adjustCount; ++$adjustCount;
} }
} }
} }
} }
// Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5) // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5)
$matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLREF.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
if ($matchCount > 0) { if ($matchCount > 0) {
foreach ($matches as $match) { foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2].'!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3]; $fromString .= $match[3];
$modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows);
if ($match[3] !== $modified3) { if ($match[3] !== $modified3) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
$toString = ($match[2] > '') ? $match[2].'!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3; $toString .= $modified3;
list($column, $row) = Cell::coordinateFromString($match[3]); list($column, $row) = Cell::coordinateFromString($match[3]);
// Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
@ -744,7 +747,7 @@ class ReferenceHelper
$cellIndex = $row . $column; $cellIndex = $row . $column;
$newCellTokens[$cellIndex] = preg_quote($toString); $newCellTokens[$cellIndex] = preg_quote($toString);
$cellTokens[$cellIndex] = '/(?<![A-Z\$\!])'.preg_quote($fromString).'(?!\d)/i'; $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString) . '(?!\d)/i';
++$adjustCount; ++$adjustCount;
} }
} }
@ -775,13 +778,13 @@ class ReferenceHelper
* @param int $pBefore Insert before this one * @param int $pBefore Insert before this one
* @param int $pNumCols Number of columns to increment * @param int $pNumCols Number of columns to increment
* @param int $pNumRows Number of rows to increment * @param int $pNumRows Number of rows to increment
* @return string Updated cell range
* @throws Exception * @throws Exception
* @return string Updated cell range
*/ */
public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0)
{ {
// Is it in another worksheet? Will not have to update anything. // Is it in another worksheet? Will not have to update anything.
if (strpos($pCellRange, "!") !== false) { if (strpos($pCellRange, '!') !== false) {
return $pCellRange; return $pCellRange;
// Is it a range or a single cell? // Is it a range or a single cell?
} elseif (strpos($pCellRange, ':') === false && strpos($pCellRange, ',') === false) { } elseif (strpos($pCellRange, ':') === false && strpos($pCellRange, ',') === false) {
@ -816,7 +819,7 @@ class ReferenceHelper
$formula = $cell->getValue(); $formula = $cell->getValue();
if (strpos($formula, $oldName) !== false) { if (strpos($formula, $oldName) !== false) {
$formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
$formula = str_replace($oldName . "!", $newName . "!", $formula); $formula = str_replace($oldName . '!', $newName . '!', $formula);
$cell->setValueExplicit($formula, Cell\DataType::TYPE_FORMULA); $cell->setValueExplicit($formula, Cell\DataType::TYPE_FORMULA);
} }
} }
@ -831,8 +834,8 @@ class ReferenceHelper
* @param int $pBefore Insert before this one * @param int $pBefore Insert before this one
* @param int $pNumCols Number of columns to increment * @param int $pNumCols Number of columns to increment
* @param int $pNumRows Number of rows to increment * @param int $pNumRows Number of rows to increment
* @return string Updated cell range
* @throws Exception * @throws Exception
* @return string Updated cell range
*/ */
private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0)
{ {
@ -844,10 +847,10 @@ class ReferenceHelper
$jc = count($range[$i]); $jc = count($range[$i]);
for ($j = 0; $j < $jc; ++$j) { for ($j = 0; $j < $jc; ++$j) {
if (ctype_alpha($range[$i][$j])) { if (ctype_alpha($range[$i][$j])) {
$r = Cell::coordinateFromString($this->updateSingleCellReference($range[$i][$j].'1', $pBefore, $pNumCols, $pNumRows)); $r = Cell::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $pBefore, $pNumCols, $pNumRows));
$range[$i][$j] = $r[0]; $range[$i][$j] = $r[0];
} elseif (ctype_digit($range[$i][$j])) { } elseif (ctype_digit($range[$i][$j])) {
$r = Cell::coordinateFromString($this->updateSingleCellReference('A'.$range[$i][$j], $pBefore, $pNumCols, $pNumRows)); $r = Cell::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $pBefore, $pNumCols, $pNumRows));
$range[$i][$j] = $r[1]; $range[$i][$j] = $r[1];
} else { } else {
$range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows); $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows);
@ -858,7 +861,7 @@ class ReferenceHelper
// Recreate range string // Recreate range string
return Cell::buildRange($range); return Cell::buildRange($range);
} else { } else {
throw new Exception("Only cell ranges may be passed to this method."); throw new Exception('Only cell ranges may be passed to this method.');
} }
} }
@ -869,8 +872,8 @@ class ReferenceHelper
* @param int $pBefore Insert before this one * @param int $pBefore Insert before this one
* @param int $pNumCols Number of columns to increment * @param int $pNumCols Number of columns to increment
* @param int $pNumRows Number of rows to increment * @param int $pNumRows Number of rows to increment
* @return string Updated cell reference
* @throws Exception * @throws Exception
* @return string Updated cell reference
*/ */
private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0)
{ {
@ -887,18 +890,18 @@ class ReferenceHelper
// Create new column reference // Create new column reference
if ($updateColumn) { if ($updateColumn) {
$newColumn = Cell::stringFromColumnIndex(Cell::columnIndexFromString($newColumn) - 1 + $pNumCols); $newColumn = Cell::stringFromColumnIndex(Cell::columnIndexFromString($newColumn) - 1 + $pNumCols);
} }
// Create new row reference // Create new row reference
if ($updateRow) { if ($updateRow) {
$newRow = $newRow + $pNumRows; $newRow = $newRow + $pNumRows;
} }
// Return new reference // Return new reference
return $newColumn . $newRow; return $newColumn . $newRow;
} else { } else {
throw new Exception("Only single cell references may be passed to this method."); throw new Exception('Only single cell references may be passed to this method.');
} }
} }
@ -909,6 +912,6 @@ class ReferenceHelper
*/ */
final public function __clone() final public function __clone()
{ {
throw new Exception("Cloning a Singleton is not allowed!"); throw new Exception('Cloning a Singleton is not allowed!');
} }
} }

View File

@ -42,12 +42,12 @@ class RichText implements IComparable
public function __construct(Cell $pCell = null) public function __construct(Cell $pCell = null)
{ {
// Initialise variables // Initialise variables
$this->richTextElements = array(); $this->richTextElements = [];
// Rich-Text string attached to cell? // Rich-Text string attached to cell?
if ($pCell !== null) { if ($pCell !== null) {
// Add cell text and style // Add cell text and style
if ($pCell->getValue() != "") { if ($pCell->getValue() != '') {
$objRun = new RichText\Run($pCell->getValue()); $objRun = new RichText\Run($pCell->getValue());
$objRun->setFont(clone $pCell->getParent()->getStyle($pCell->getCoordinate())->getFont()); $objRun->setFont(clone $pCell->getParent()->getStyle($pCell->getCoordinate())->getFont());
$this->addText($objRun); $this->addText($objRun);
@ -68,6 +68,7 @@ class RichText implements IComparable
public function addText(RichText\ITextElement $pText = null) public function addText(RichText\ITextElement $pText = null)
{ {
$this->richTextElements[] = $pText; $this->richTextElements[] = $pText;
return $this; return $this;
} }
@ -75,13 +76,14 @@ class RichText implements IComparable
* Create text * Create text
* *
* @param string $pText Text * @param string $pText Text
* @return RichText\TextElement
* @throws Exception * @throws Exception
* @return RichText\TextElement
*/ */
public function createText($pText = '') public function createText($pText = '')
{ {
$objText = new RichText\TextElement($pText); $objText = new RichText\TextElement($pText);
$this->addText($objText); $this->addText($objText);
return $objText; return $objText;
} }
@ -89,13 +91,14 @@ class RichText implements IComparable
* Create text run * Create text run
* *
* @param string $pText Text * @param string $pText Text
* @return RichText\Run
* @throws Exception * @throws Exception
* @return RichText\Run
*/ */
public function createTextRun($pText = '') public function createTextRun($pText = '')
{ {
$objText = new RichText\Run($pText); $objText = new RichText\Run($pText);
$this->addText($objText); $this->addText($objText);
return $objText; return $objText;
} }
@ -151,6 +154,7 @@ class RichText implements IComparable
} else { } else {
throw new Exception("Invalid \PhpSpreadsheet\RichText\ITextElement[] array passed."); throw new Exception("Invalid \PhpSpreadsheet\RichText\ITextElement[] array passed.");
} }
return $this; return $this;
} }

View File

@ -63,6 +63,7 @@ class Run extends TextElement implements ITextElement
public function setFont(\PhpSpreadsheet\Style\Font $pFont = null) public function setFont(\PhpSpreadsheet\Style\Font $pFont = null)
{ {
$this->font = $pFont; $this->font = $pFont;
return $this; return $this;
} }

View File

@ -61,6 +61,7 @@ class TextElement implements ITextElement
public function setText($pText = '') public function setText($pText = '')
{ {
$this->text = $pText; $this->text = $pText;
return $this; return $this;
} }

View File

@ -28,28 +28,26 @@ class Settings
{ {
/** constants */ /** constants */
/** Available Zip library classes */ /** Available Zip library classes */
const PCLZIP = '\\PhpSpreadsheet\\Shared\\ZipArchive'; const PCLZIP = '\\PhpSpreadsheet\\Shared\\ZipArchive';
const ZIPARCHIVE = '\\ZipArchive'; const ZIPARCHIVE = '\\ZipArchive';
/** Optional Chart Rendering libraries */ /** Optional Chart Rendering libraries */
const CHART_RENDERER_JPGRAPH = 'JpGraph'; const CHART_RENDERER_JPGRAPH = 'JpGraph';
/** Optional PDF Rendering libraries */ /** Optional PDF Rendering libraries */
const PDF_RENDERER_TCPDF = 'TcPDF'; const PDF_RENDERER_TCPDF = 'TcPDF';
const PDF_RENDERER_DOMPDF = 'DomPDF'; const PDF_RENDERER_DOMPDF = 'DomPDF';
const PDF_RENDERER_MPDF = 'MPDF'; const PDF_RENDERER_MPDF = 'MPDF';
private static $chartRenderers = [
private static $chartRenderers = array(
self::CHART_RENDERER_JPGRAPH, self::CHART_RENDERER_JPGRAPH,
); ];
private static $pdfRenderers = array( private static $pdfRenderers = [
self::PDF_RENDERER_TCPDF, self::PDF_RENDERER_TCPDF,
self::PDF_RENDERER_DOMPDF, self::PDF_RENDERER_DOMPDF,
self::PDF_RENDERER_MPDF, self::PDF_RENDERER_MPDF,
); ];
/** /**
* Name of the class used for Zip file management * Name of the class used for Zip file management
@ -60,7 +58,6 @@ class Settings
*/ */
private static $zipClass = self::ZIPARCHIVE; private static $zipClass = self::ZIPARCHIVE;
/** /**
* Name of the external Library used for rendering charts * Name of the external Library used for rendering charts
* e.g. * e.g.
@ -77,7 +74,6 @@ class Settings
*/ */
private static $chartRendererPath; private static $chartRendererPath;
/** /**
* Name of the external Library used for rendering PDF files * Name of the external Library used for rendering PDF files
* e.g. * e.g.
@ -106,19 +102,20 @@ class Settings
* *
* @param string $zipClass The Zip handler class that PhpSpreadsheet should use for Zip file management * @param string $zipClass The Zip handler class that PhpSpreadsheet should use for Zip file management
* e.g. \PhpSpreadsheet\Settings::PCLZip or \PhpSpreadsheet\Settings::ZipArchive * e.g. \PhpSpreadsheet\Settings::PCLZip or \PhpSpreadsheet\Settings::ZipArchive
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setZipClass($zipClass) public static function setZipClass($zipClass)
{ {
if (($zipClass === self::PCLZIP) || if (($zipClass === self::PCLZIP) ||
($zipClass === self::ZIPARCHIVE)) { ($zipClass === self::ZIPARCHIVE)) {
self::$zipClass = $zipClass; self::$zipClass = $zipClass;
return true; return true;
} }
return false; return false;
} }
/** /**
* Return the name of the Zip handler Class that PhpSpreadsheet is configured to use (PCLZip or ZipArchive) * Return the name of the Zip handler Class that PhpSpreadsheet is configured to use (PCLZip or ZipArchive)
* or Zip file management * or Zip file management
@ -132,7 +129,6 @@ class Settings
return self::$zipClass; return self::$zipClass;
} }
/** /**
* Return the name of the method that is currently configured for cell cacheing * Return the name of the method that is currently configured for cell cacheing
* *
@ -143,7 +139,6 @@ class Settings
return CachedObjectStorageFactory::getCacheStorageMethod(); return CachedObjectStorageFactory::getCacheStorageMethod();
} }
/** /**
* Return the name of the class that is currently being used for cell cacheing * Return the name of the class that is currently being used for cell cacheing
* *
@ -154,32 +149,29 @@ class Settings
return CachedObjectStorageFactory::getCacheStorageClass(); return CachedObjectStorageFactory::getCacheStorageClass();
} }
/** /**
* Set the method that should be used for cell cacheing * Set the method that should be used for cell cacheing
* *
* @param string $method Name of the cacheing method * @param string $method Name of the cacheing method
* @param array $arguments Optional configuration arguments for the cacheing method * @param array $arguments Optional configuration arguments for the cacheing method
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setCacheStorageMethod($method = CachedObjectStorageFactory::cache_in_memory, $arguments = array()) public static function setCacheStorageMethod($method = CachedObjectStorageFactory::cache_in_memory, $arguments = [])
{ {
return CachedObjectStorageFactory::initialize($method, $arguments); return CachedObjectStorageFactory::initialize($method, $arguments);
} }
/** /**
* Set the locale code to use for formula translations and any special formatting * Set the locale code to use for formula translations and any special formatting
* *
* @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk") * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk")
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setLocale($locale = 'en_us') public static function setLocale($locale = 'en_us')
{ {
return Calculation::getInstance()->setLocale($locale); return Calculation::getInstance()->setLocale($locale);
} }
/** /**
* Set details of the external library that PhpSpreadsheet should use for rendering charts * Set details of the external library that PhpSpreadsheet should use for rendering charts
* *
@ -187,24 +179,24 @@ class Settings
* e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH * e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH
* @param string $libraryBaseDir Directory path to the library's base folder * @param string $libraryBaseDir Directory path to the library's base folder
* *
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setChartRenderer($libraryName, $libraryBaseDir) public static function setChartRenderer($libraryName, $libraryBaseDir)
{ {
if (!self::setChartRendererName($libraryName)) { if (!self::setChartRendererName($libraryName)) {
return false; return false;
} }
return self::setChartRendererPath($libraryBaseDir); return self::setChartRendererPath($libraryBaseDir);
} }
/** /**
* Identify to PhpSpreadsheet the external library to use for rendering charts * Identify to PhpSpreadsheet the external library to use for rendering charts
* *
* @param string $libraryName Internal reference name of the library * @param string $libraryName Internal reference name of the library
* e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH * e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH
* *
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setChartRendererName($libraryName) public static function setChartRendererName($libraryName)
{ {
@ -216,12 +208,11 @@ class Settings
return true; return true;
} }
/** /**
* Tell PhpSpreadsheet where to find the external library to use for rendering charts * Tell PhpSpreadsheet where to find the external library to use for rendering charts
* *
* @param string $libraryBaseDir Directory path to the library's base folder * @param string $libraryBaseDir Directory path to the library's base folder
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setChartRendererPath($libraryBaseDir) public static function setChartRendererPath($libraryBaseDir)
{ {
@ -233,11 +224,10 @@ class Settings
return true; return true;
} }
/** /**
* Return the Chart Rendering Library that PhpSpreadsheet is currently configured to use (e.g. jpgraph) * Return the Chart Rendering Library that PhpSpreadsheet is currently configured to use (e.g. jpgraph)
* *
* @return string|NULL Internal reference name of the Chart Rendering Library that PhpSpreadsheet is * @return string|null Internal reference name of the Chart Rendering Library that PhpSpreadsheet is
* currently configured to use * currently configured to use
* e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH * e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH
*/ */
@ -246,11 +236,10 @@ class Settings
return self::$chartRendererName; return self::$chartRendererName;
} }
/** /**
* Return the directory path to the Chart Rendering Library that PhpSpreadsheet is currently configured to use * Return the directory path to the Chart Rendering Library that PhpSpreadsheet is currently configured to use
* *
* @return string|NULL Directory Path to the Chart Rendering Library that PhpSpreadsheet is * @return string|null Directory Path to the Chart Rendering Library that PhpSpreadsheet is
* currently configured to use * currently configured to use
*/ */
public static function getChartRendererPath() public static function getChartRendererPath()
@ -258,7 +247,6 @@ class Settings
return self::$chartRendererPath; return self::$chartRendererPath;
} }
/** /**
* Set details of the external library that PhpSpreadsheet should use for rendering PDF files * Set details of the external library that PhpSpreadsheet should use for rendering PDF files
* *
@ -268,17 +256,17 @@ class Settings
* or \PhpSpreadsheet\Settings::PDF_RENDERER_MPDF * or \PhpSpreadsheet\Settings::PDF_RENDERER_MPDF
* @param string $libraryBaseDir Directory path to the library's base folder * @param string $libraryBaseDir Directory path to the library's base folder
* *
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setPdfRenderer($libraryName, $libraryBaseDir) public static function setPdfRenderer($libraryName, $libraryBaseDir)
{ {
if (!self::setPdfRendererName($libraryName)) { if (!self::setPdfRendererName($libraryName)) {
return false; return false;
} }
return self::setPdfRendererPath($libraryBaseDir); return self::setPdfRendererPath($libraryBaseDir);
} }
/** /**
* Identify to PhpSpreadsheet the external library to use for rendering PDF files * Identify to PhpSpreadsheet the external library to use for rendering PDF files
* *
@ -287,7 +275,7 @@ class Settings
* \PhpSpreadsheet\Settings::PDF_RENDERER_DOMPDF * \PhpSpreadsheet\Settings::PDF_RENDERER_DOMPDF
* or \PhpSpreadsheet\Settings::PDF_RENDERER_MPDF * or \PhpSpreadsheet\Settings::PDF_RENDERER_MPDF
* *
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setPdfRendererName($libraryName) public static function setPdfRendererName($libraryName)
{ {
@ -299,12 +287,11 @@ class Settings
return true; return true;
} }
/** /**
* Tell PhpSpreadsheet where to find the external library to use for rendering PDF files * Tell PhpSpreadsheet where to find the external library to use for rendering PDF files
* *
* @param string $libraryBaseDir Directory path to the library's base folder * @param string $libraryBaseDir Directory path to the library's base folder
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setPdfRendererPath($libraryBaseDir) public static function setPdfRendererPath($libraryBaseDir)
{ {
@ -316,11 +303,10 @@ class Settings
return true; return true;
} }
/** /**
* Return the PDF Rendering Library that PhpSpreadsheet is currently configured to use (e.g. dompdf) * Return the PDF Rendering Library that PhpSpreadsheet is currently configured to use (e.g. dompdf)
* *
* @return string|NULL Internal reference name of the PDF Rendering Library that PhpSpreadsheet is * @return string|null Internal reference name of the PDF Rendering Library that PhpSpreadsheet is
* currently configured to use * currently configured to use
* e.g. \PhpSpreadsheet\Settings::PDF_RENDERER_TCPDF, * e.g. \PhpSpreadsheet\Settings::PDF_RENDERER_TCPDF,
* \PhpSpreadsheet\Settings::PDF_RENDERER_DOMPDF * \PhpSpreadsheet\Settings::PDF_RENDERER_DOMPDF
@ -334,7 +320,7 @@ class Settings
/** /**
* Return the directory path to the PDF Rendering Library that PhpSpreadsheet is currently configured to use * Return the directory path to the PDF Rendering Library that PhpSpreadsheet is currently configured to use
* *
* @return string|NULL Directory Path to the PDF Rendering Library that PhpSpreadsheet is * @return string|null Directory Path to the PDF Rendering Library that PhpSpreadsheet is
* currently configured to use * currently configured to use
*/ */
public static function getPdfRendererPath() public static function getPdfRendererPath()

View File

@ -32,9 +32,9 @@ class CodePage
* Convert Microsoft Code Page Identifier to Code Page Name which iconv * Convert Microsoft Code Page Identifier to Code Page Name which iconv
* and mbstring understands * and mbstring understands
* *
* @param integer $codePage Microsoft Code Page Indentifier * @param int $codePage Microsoft Code Page Indentifier
* @return string Code Page Name
* @throws \PhpSpreadsheet\Exception * @throws \PhpSpreadsheet\Exception
* @return string Code Page Name
*/ */
public static function numberToName($codePage = 1252) public static function numberToName($codePage = 1252)
{ {

View File

@ -85,23 +85,25 @@ class Date
/** /**
* Set the Excel calendar (Windows 1900 or Mac 1904) * Set the Excel calendar (Windows 1900 or Mac 1904)
* *
* @param integer $baseDate Excel base date (1900 or 1904) * @param int $baseDate Excel base date (1900 or 1904)
* @return boolean Success or failure * @return bool Success or failure
*/ */
public static function setExcelCalendar($baseDate) public static function setExcelCalendar($baseDate)
{ {
if (($baseDate == self::CALENDAR_WINDOWS_1900) || if (($baseDate == self::CALENDAR_WINDOWS_1900) ||
($baseDate == self::CALENDAR_MAC_1904)) { ($baseDate == self::CALENDAR_MAC_1904)) {
self::$excelCalendar = $baseDate; self::$excelCalendar = $baseDate;
return true; return true;
} }
return false; return false;
} }
/** /**
* Return the Excel calendar (Windows 1900 or Mac 1904) * Return the Excel calendar (Windows 1900 or Mac 1904)
* *
* @return integer Excel base date (1900 or 1904) * @return int Excel base date (1900 or 1904)
*/ */
public static function getExcelCalendar() public static function getExcelCalendar()
{ {
@ -112,15 +114,17 @@ class Date
* Set the Default timezone to use for dates * Set the Default timezone to use for dates
* *
* @param string|\DateTimeZone $timezone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions * @param string|\DateTimeZone $timezone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions
* @return boolean Success or failure
* @throws \Exception * @throws \Exception
* @return bool Success or failure
*/ */
public static function setDefaultTimezone($timeZone) public static function setDefaultTimezone($timeZone)
{ {
if ($timeZone = self::validateTimeZone($timeZone)) { if ($timeZone = self::validateTimeZone($timeZone)) {
self::$defaultTimeZone = $timeZone; self::$defaultTimeZone = $timeZone;
return true; return true;
} }
return false; return false;
} }
@ -134,6 +138,7 @@ class Date
if (self::$defaultTimeZone === null) { if (self::$defaultTimeZone === null) {
self::$defaultTimeZone = new \DateTimeZone('UTC'); self::$defaultTimeZone = new \DateTimeZone('UTC');
} }
return self::$defaultTimeZone; return self::$defaultTimeZone;
} }
@ -141,8 +146,8 @@ class Date
* Validate a timezone * Validate a timezone
* *
* @param string|\DateTimeZone $timezone The timezone to validate, either as a timezone string or object * @param string|\DateTimeZone $timezone The timezone to validate, either as a timezone string or object
* @return \DateTimeZone The timezone as a timezone object
* @throws \Exception * @throws \Exception
* @return \DateTimeZone The timezone as a timezone object
*/ */
protected static function validateTimeZone($timeZone) protected static function validateTimeZone($timeZone)
{ {
@ -157,12 +162,12 @@ class Date
/** /**
* Convert a MS serialized datetime value from Excel to a PHP Date/Time object * Convert a MS serialized datetime value from Excel to a PHP Date/Time object
* *
* @param integer|float $dateValue MS Excel serialized date/time value * @param int|float $dateValue MS Excel serialized date/time value
* @param \DateTimeZone|string|null $timezone The timezone to assume for the Excel timestamp, * @param \DateTimeZone|string|null $timezone The timezone to assume for the Excel timestamp,
* if you don't want to treat it as a UTC value * if you don't want to treat it as a UTC value
* Use the default (UST) unless you absolutely need a conversion * Use the default (UST) unless you absolutely need a conversion
* @return \DateTime PHP date/time object
* @throws \Exception * @throws \Exception
* @return \DateTime PHP date/time object
*/ */
public static function excelToDateTimeObject($excelTimestamp = 0, $timeZone = null) public static function excelToDateTimeObject($excelTimestamp = 0, $timeZone = null)
{ {
@ -188,6 +193,7 @@ class Date
$seconds = round($partDay * 60); $seconds = round($partDay * 60);
$interval = '+' . $days . ' days'; $interval = '+' . $days . ' days';
return $baseDate->modify($interval) return $baseDate->modify($interval)
->setTime($hours, $minutes, $seconds); ->setTime($hours, $minutes, $seconds);
} }
@ -195,12 +201,12 @@ class Date
/** /**
* Convert a MS serialized datetime value from Excel to a unix timestamp * Convert a MS serialized datetime value from Excel to a unix timestamp
* *
* @param integer|float $dateValue MS Excel serialized date/time value * @param int|float $dateValue MS Excel serialized date/time value
* @param \DateTimeZone|string|null $timezone The timezone to assume for the Excel timestamp, * @param \DateTimeZone|string|null $timezone The timezone to assume for the Excel timestamp,
* if you don't want to treat it as a UTC value * if you don't want to treat it as a UTC value
* Use the default (UST) unless you absolutely need a conversion * Use the default (UST) unless you absolutely need a conversion
* @return integer Unix timetamp for this date/time
* @throws \Exception * @throws \Exception
* @return int Unix timetamp for this date/time
*/ */
public static function excelToTimestamp($excelTimestamp = 0, $timeZone = null) public static function excelToTimestamp($excelTimestamp = 0, $timeZone = null)
{ {
@ -212,7 +218,7 @@ class Date
* Convert a date from PHP to an MS Excel serialized date/time value * Convert a date from PHP to an MS Excel serialized date/time value
* *
* @param mixed $dateValue PHP serialized date/time or date object * @param mixed $dateValue PHP serialized date/time or date object
* @return float|boolean Excel date/time value * @return float|bool Excel date/time value
* or boolean FALSE on failure * or boolean FALSE on failure
*/ */
public static function PHPToExcel($dateValue = 0) public static function PHPToExcel($dateValue = 0)
@ -257,19 +263,20 @@ class Date
if (!is_numeric($dateValue)) { if (!is_numeric($dateValue)) {
return false; return false;
} }
return self::DateTimeToExcel(new \DateTime('@' . $dateValue)); return self::DateTimeToExcel(new \DateTime('@' . $dateValue));
} }
/** /**
* formattedPHPToExcel * formattedPHPToExcel
* *
* @param integer $year * @param int $year
* @param integer $month * @param int $month
* @param integer $day * @param int $day
* @param integer $hours * @param int $hours
* @param integer $minutes * @param int $minutes
* @param integer $seconds * @param int $seconds
* @return integer Excel date/time value * @return int Excel date/time value
*/ */
public static function formattedPHPToExcel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0) public static function formattedPHPToExcel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0)
{ {
@ -306,12 +313,11 @@ class Date
return (float) $excelDate + $excelTime; return (float) $excelDate + $excelTime;
} }
/** /**
* Is a given cell a date/time? * Is a given cell a date/time?
* *
* @param \PhpSpreadsheet\Cell $pCell * @param \PhpSpreadsheet\Cell $pCell
* @return boolean * @return bool
*/ */
public static function isDateTime(\PhpSpreadsheet\Cell $pCell) public static function isDateTime(\PhpSpreadsheet\Cell $pCell)
{ {
@ -322,26 +328,24 @@ class Date
); );
} }
/** /**
* Is a given number format a date/time? * Is a given number format a date/time?
* *
* @param \PhpSpreadsheet\Style\NumberFormat $pFormat * @param \PhpSpreadsheet\Style\NumberFormat $pFormat
* @return boolean * @return bool
*/ */
public static function isDateTimeFormat(\PhpSpreadsheet\Style\NumberFormat $pFormat) public static function isDateTimeFormat(\PhpSpreadsheet\Style\NumberFormat $pFormat)
{ {
return self::isDateTimeFormatCode($pFormat->getFormatCode()); return self::isDateTimeFormatCode($pFormat->getFormatCode());
} }
private static $possibleDateFormatCharacters = 'eymdHs'; private static $possibleDateFormatCharacters = 'eymdHs';
/** /**
* Is a given number format code a date/time? * Is a given number format code a date/time?
* *
* @param string $pFormatCode * @param string $pFormatCode
* @return boolean * @return bool
*/ */
public static function isDateTimeFormatCode($pFormatCode = '') public static function isDateTimeFormatCode($pFormatCode = '')
{ {
@ -387,7 +391,7 @@ class Date
return false; return false;
} }
// Try checking for any of the date formatting characters that don't appear within square braces // Try checking for any of the date formatting characters that don't appear within square braces
if (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i', $pFormatCode)) { if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $pFormatCode)) {
// We might also have a format mask containing quoted strings... // We might also have a format mask containing quoted strings...
// we don't want to test for any of our characters within the quoted blocks // we don't want to test for any of our characters within the quoted blocks
if (strpos($pFormatCode, '"') !== false) { if (strpos($pFormatCode, '"') !== false) {
@ -395,12 +399,14 @@ class Date
foreach (explode('"', $pFormatCode) as $subVal) { foreach (explode('"', $pFormatCode) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks) // Only test in alternate array entries (the non-quoted blocks)
if (($segMatcher = !$segMatcher) && if (($segMatcher = !$segMatcher) &&
(preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i', $subVal))) { (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $subVal))) {
return true; return true;
} }
} }
return false; return false;
} }
return true; return true;
} }
@ -408,12 +414,11 @@ class Date
return false; return false;
} }
/** /**
* Convert a date/time string to Excel time * Convert a date/time string to Excel time
* *
* @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10' * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10'
* @return float|FALSE Excel date/time serial value * @return float|false Excel date/time serial value
*/ */
public static function stringToExcel($dateValue = '') public static function stringToExcel($dateValue = '')
{ {
@ -437,6 +442,7 @@ class Date
} }
$dateValueNew += $timeValue; $dateValueNew += $timeValue;
} }
return $dateValueNew; return $dateValueNew;
} }
@ -444,7 +450,7 @@ class Date
* Converts a month name (either a long or a short name) to a month number * Converts a month name (either a long or a short name) to a month number
* *
* @param string $month Month name or abbreviation * @param string $month Month name or abbreviation
* @return integer|string Month number (1 - 12), or the original string argument if it isn't a valid month name * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
*/ */
public static function monthStringToNumber($month) public static function monthStringToNumber($month)
{ {
@ -455,6 +461,7 @@ class Date
} }
++$monthIndex; ++$monthIndex;
} }
return $month; return $month;
} }
@ -462,7 +469,7 @@ class Date
* Strips an ordinal froma numeric value * Strips an ordinal froma numeric value
* *
* @param string $day Day number with an ordinal * @param string $day Day number with an ordinal
* @return integer|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric * @return int|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric
*/ */
public static function dayStringToNumber($day) public static function dayStringToNumber($day)
{ {
@ -470,6 +477,7 @@ class Date
if (is_numeric($strippedDayValue)) { if (is_numeric($strippedDayValue)) {
return (integer) $strippedDayValue; return (integer) $strippedDayValue;
} }
return $day; return $day;
} }
} }

View File

@ -141,7 +141,7 @@ class Drawing
*/ */
public static function degreesToAngle($pValue = 0) public static function degreesToAngle($pValue = 0)
{ {
return (int)round($pValue * 60000); return (int) round($pValue * 60000);
} }
/** /**
@ -169,27 +169,27 @@ class Drawing
public static function imagecreatefrombmp($p_sFile) public static function imagecreatefrombmp($p_sFile)
{ {
// Load the image into a string // Load the image into a string
$file = fopen($p_sFile, "rb"); $file = fopen($p_sFile, 'rb');
$read = fread($file, 10); $read = fread($file, 10);
while (!feof($file) && ($read<>"")) { while (!feof($file) && ($read != '')) {
$read .= fread($file, 1024); $read .= fread($file, 1024);
} }
$temp = unpack("H*", $read); $temp = unpack('H*', $read);
$hex = $temp[1]; $hex = $temp[1];
$header = substr($hex, 0, 108); $header = substr($hex, 0, 108);
// Process the header // Process the header
// Structure: http://www.fastgraph.com/help/bmp_header_format.html // Structure: http://www.fastgraph.com/help/bmp_header_format.html
if (substr($header, 0, 4)=="424d") { if (substr($header, 0, 4) == '424d') {
// Cut it in parts of 2 bytes // Cut it in parts of 2 bytes
$header_parts = str_split($header, 2); $header_parts = str_split($header, 2);
// Get the width 4 bytes // Get the width 4 bytes
$width = hexdec($header_parts[19].$header_parts[18]); $width = hexdec($header_parts[19] . $header_parts[18]);
// Get the height 4 bytes // Get the height 4 bytes
$height = hexdec($header_parts[23].$header_parts[22]); $height = hexdec($header_parts[23] . $header_parts[22]);
// Unset the header params // Unset the header params
unset($header_parts); unset($header_parts);
@ -208,11 +208,11 @@ class Drawing
// Calculate if padding at the end-line is needed // Calculate if padding at the end-line is needed
// Divided by two to keep overview. // Divided by two to keep overview.
// 1 byte = 2 HEX-chars // 1 byte = 2 HEX-chars
$body_size = (strlen($body)/2); $body_size = (strlen($body) / 2);
$header_size = ($width*$height); $header_size = ($width * $height);
// Use end-line padding? Only when needed // Use end-line padding? Only when needed
$usePadding = ($body_size>($header_size*3)+4); $usePadding = ($body_size > ($header_size * 3) + 4);
// Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
// Calculate the next DWORD-position in the body // Calculate the next DWORD-position in the body
@ -222,14 +222,14 @@ class Drawing
// If padding needed, ignore image-padding // If padding needed, ignore image-padding
// Shift i to the ending of the current 32-bit-block // Shift i to the ending of the current 32-bit-block
if ($usePadding) { if ($usePadding) {
$i += $width%4; $i += $width % 4;
} }
// Reset horizontal position // Reset horizontal position
$x = 0; $x = 0;
// Raise the height-position (bottom-up) // Raise the height-position (bottom-up)
$y++; ++$y;
// Reached the image-height? Break the for-loop // Reached the image-height? Break the for-loop
if ($y > $height) { if ($y > $height) {
@ -239,17 +239,17 @@ class Drawing
// Calculation of the RGB-pixel (defined as BGR in image-data) // Calculation of the RGB-pixel (defined as BGR in image-data)
// Define $i_pos as absolute position in the body // Define $i_pos as absolute position in the body
$i_pos = $i * 2; $i_pos = $i * 2;
$r = hexdec($body[$i_pos+4].$body[$i_pos+5]); $r = hexdec($body[$i_pos + 4] . $body[$i_pos + 5]);
$g = hexdec($body[$i_pos+2].$body[$i_pos+3]); $g = hexdec($body[$i_pos + 2] . $body[$i_pos + 3]);
$b = hexdec($body[$i_pos].$body[$i_pos+1]); $b = hexdec($body[$i_pos] . $body[$i_pos + 1]);
// Calculate and draw the pixel // Calculate and draw the pixel
$color = imagecolorallocate($image, $r, $g, $b); $color = imagecolorallocate($image, $r, $g, $b);
imagesetpixel($image, $x, $height-$y, $color); imagesetpixel($image, $x, $height - $y, $color);
// Raise the horizontal position // Raise the horizontal position
$x++; ++$x;
} }
// Unset the body / free the memory // Unset the body / free the memory

View File

@ -38,7 +38,7 @@ class SpgrContainer
* *
* @var array * @var array
*/ */
private $children = array(); private $children = [];
/** /**
* Set parent Shape Group Container * Set parent Shape Group Container
@ -86,10 +86,10 @@ class SpgrContainer
*/ */
public function getAllSpContainers() public function getAllSpContainers()
{ {
$allSpContainers = array(); $allSpContainers = [];
foreach ($this->children as $child) { foreach ($this->children as $child) {
if ($child instanceof SpgrContainer) { if ($child instanceof self) {
$allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers()); $allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers());
} else { } else {
$allSpContainers[] = $child; $allSpContainers[] = $child;

View File

@ -36,7 +36,7 @@ class SpContainer
/** /**
* Is this a group shape? * Is this a group shape?
* *
* @var boolean * @var bool
*/ */
private $spgr = false; private $spgr = false;
@ -57,7 +57,7 @@ class SpContainer
/** /**
* Shape index (usually group shape has index 0, and the rest: 1,2,3...) * Shape index (usually group shape has index 0, and the rest: 1,2,3...)
* *
* @var boolean * @var bool
*/ */
private $spId; private $spId;
@ -133,7 +133,7 @@ class SpContainer
/** /**
* Set whether this is a group shape * Set whether this is a group shape
* *
* @param boolean $value * @param bool $value
*/ */
public function setSpgr($value = false) public function setSpgr($value = false)
{ {
@ -143,7 +143,7 @@ class SpContainer
/** /**
* Get whether this is a group shape * Get whether this is a group shape
* *
* @return boolean * @return bool
*/ */
public function getSpgr() public function getSpgr()
{ {
@ -232,6 +232,7 @@ class SpContainer
if (isset($this->OPT[$property])) { if (isset($this->OPT[$property])) {
return $this->OPT[$property]; return $this->OPT[$property];
} }
return null; return null;
} }

View File

@ -59,14 +59,14 @@ class DggContainer
* *
* @var array * @var array
*/ */
private $OPT = array(); private $OPT = [];
/** /**
* Array of identifier clusters containg information about the maximum shape identifiers * Array of identifier clusters containg information about the maximum shape identifiers
* *
* @var array * @var array
*/ */
private $IDCLs = array(); private $IDCLs = [];
/** /**
* Get maximum shape index of all shapes in all drawings (plus one) * Get maximum shape index of all shapes in all drawings (plus one)
@ -170,6 +170,7 @@ class DggContainer
if (isset($this->OPT[$property])) { if (isset($this->OPT[$property])) {
return $this->OPT[$property]; return $this->OPT[$property];
} }
return null; return null;
} }

View File

@ -31,7 +31,7 @@ class BstoreContainer
* *
* @var array * @var array
*/ */
private $BSECollection = array(); private $BSECollection = [];
/** /**
* Add a BLIP Store Entry * Add a BLIP Store Entry

View File

@ -26,15 +26,15 @@ namespace PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
*/ */
class BSE class BSE
{ {
const BLIPTYPE_ERROR = 0x00; const BLIPTYPE_ERROR = 0x00;
const BLIPTYPE_UNKNOWN = 0x01; const BLIPTYPE_UNKNOWN = 0x01;
const BLIPTYPE_EMF = 0x02; const BLIPTYPE_EMF = 0x02;
const BLIPTYPE_WMF = 0x03; const BLIPTYPE_WMF = 0x03;
const BLIPTYPE_PICT = 0x04; const BLIPTYPE_PICT = 0x04;
const BLIPTYPE_JPEG = 0x05; const BLIPTYPE_JPEG = 0x05;
const BLIPTYPE_PNG = 0x06; const BLIPTYPE_PNG = 0x06;
const BLIPTYPE_DIB = 0x07; const BLIPTYPE_DIB = 0x07;
const BLIPTYPE_TIFF = 0x11; const BLIPTYPE_TIFF = 0x11;
const BLIPTYPE_CMYKJPEG = 0x12; const BLIPTYPE_CMYKJPEG = 0x12;
/** /**

View File

@ -33,8 +33,8 @@ class Excel5
* *
* @param \PhpSpreadsheet\Worksheet $sheet The sheet * @param \PhpSpreadsheet\Worksheet $sheet The sheet
* @param string $col The column * @param string $col The column
* @return integer The width in pixels * @return int The width in pixels
*/ */
public static function sizeCol($sheet, $col = 'A') public static function sizeCol($sheet, $col = 'A')
{ {
// default font of the workbook // default font of the workbook
@ -74,8 +74,8 @@ class Excel5
* use the default value. If the row is hidden we use a value of zero. * use the default value. If the row is hidden we use a value of zero.
* *
* @param \PhpSpreadsheet\Worksheet $sheet The sheet * @param \PhpSpreadsheet\Worksheet $sheet The sheet
* @param integer $row The row index (1-based) * @param int $row The row index (1-based)
* @return integer The width in pixels * @return int The width in pixels
*/ */
public static function sizeRow($sheet, $row = 1) public static function sizeRow($sheet, $row = 1)
{ {
@ -117,10 +117,10 @@ class Excel5
* *
* @param \PhpSpreadsheet\Worksheet $sheet * @param \PhpSpreadsheet\Worksheet $sheet
* @param string $startColumn * @param string $startColumn
* @param integer $startOffsetX Offset within start cell measured in 1/1024 of the cell width * @param int $startOffsetX Offset within start cell measured in 1/1024 of the cell width
* @param string $endColumn * @param string $endColumn
* @param integer $endOffsetX Offset within end cell measured in 1/1024 of the cell width * @param int $endOffsetX Offset within end cell measured in 1/1024 of the cell width
* @return integer Horizontal measured in pixels * @return int Horizontal measured in pixels
*/ */
public static function getDistanceX(\PhpSpreadsheet\Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0) public static function getDistanceX(\PhpSpreadsheet\Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0)
{ {
@ -147,11 +147,11 @@ class Excel5
* The distanceY is found as sum of all the spanning rows minus two offsets * The distanceY is found as sum of all the spanning rows minus two offsets
* *
* @param \PhpSpreadsheet\Worksheet $sheet * @param \PhpSpreadsheet\Worksheet $sheet
* @param integer $startRow (1-based) * @param int $startRow (1-based)
* @param integer $startOffsetY Offset within start cell measured in 1/256 of the cell height * @param int $startOffsetY Offset within start cell measured in 1/256 of the cell height
* @param integer $endRow (1-based) * @param int $endRow (1-based)
* @param integer $endOffsetY Offset within end cell measured in 1/256 of the cell height * @param int $endOffsetY Offset within end cell measured in 1/256 of the cell height
* @return integer Vertical distance measured in pixels * @return int Vertical distance measured in pixels
*/ */
public static function getDistanceY(\PhpSpreadsheet\Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0) public static function getDistanceY(\PhpSpreadsheet\Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0)
{ {
@ -217,10 +217,10 @@ class Excel5
* *
* @param \PhpSpreadsheet\Worksheet $sheet * @param \PhpSpreadsheet\Worksheet $sheet
* @param string $coordinates E.g. 'A1' * @param string $coordinates E.g. 'A1'
* @param integer $offsetX Horizontal offset in pixels * @param int $offsetX Horizontal offset in pixels
* @param integer $offsetY Vertical offset in pixels * @param int $offsetY Vertical offset in pixels
* @param integer $width Width in pixels * @param int $width Width in pixels
* @param integer $height Height in pixels * @param int $height Height in pixels
* @return array * @return array
*/ */
public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height) public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height)
@ -233,8 +233,8 @@ class Excel5
$y1 = $offsetY; $y1 = $offsetY;
// Initialise end cell to the same as the start cell // Initialise end cell to the same as the start cell
$col_end = $col_start; // Col containing lower right corner of object $col_end = $col_start; // Col containing lower right corner of object
$row_end = $row_start; // Row containing bottom right corner of object $row_end = $row_start; // Row containing bottom right corner of object
// Zero the specified offset if greater than the cell dimensions // Zero the specified offset if greater than the cell dimensions
if ($x1 >= self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start))) { if ($x1 >= self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start))) {
@ -244,8 +244,8 @@ class Excel5
$y1 = 0; $y1 = 0;
} }
$width = $width + $x1 -1; $width = $width + $x1 - 1;
$height = $height + $y1 -1; $height = $height + $y1 - 1;
// Subtract the underlying cell widths to find the end cell of the image // Subtract the underlying cell widths to find the end cell of the image
while ($width >= self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end))) { while ($width >= self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end))) {
@ -264,33 +264,33 @@ class Excel5
if (self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) == 0) { if (self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) == 0) {
return; return;
} }
if (self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) == 0) { if (self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) == 0) {
return; return;
} }
if (self::sizeRow($sheet, $row_start + 1) == 0) { if (self::sizeRow($sheet, $row_start + 1) == 0) {
return; return;
} }
if (self::sizeRow($sheet, $row_end + 1) == 0) { if (self::sizeRow($sheet, $row_end + 1) == 0) {
return; return;
} }
// Convert the pixel values to the percentage value expected by Excel // Convert the pixel values to the percentage value expected by Excel
$x1 = $x1 / self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) * 1024; $x1 = $x1 / self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) * 1024;
$y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256; $y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256;
$x2 = ($width + 1) / self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object $x2 = ($width + 1) / self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
$y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object $y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object
$startCoordinates = \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start) . ($row_start + 1); $startCoordinates = \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start) . ($row_start + 1);
$endCoordinates = \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end) . ($row_end + 1); $endCoordinates = \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end) . ($row_end + 1);
$twoAnchor = array( $twoAnchor = [
'startCoordinates' => $startCoordinates, 'startCoordinates' => $startCoordinates,
'startOffsetX' => $x1, 'startOffsetX' => $x1,
'startOffsetY' => $y1, 'startOffsetY' => $y1,
'endCoordinates' => $endCoordinates, 'endCoordinates' => $endCoordinates,
'endOffsetX' => $x2, 'endOffsetX' => $x2,
'endOffsetY' => $y2, 'endOffsetY' => $y2,
); ];
return $twoAnchor; return $twoAnchor;
} }

View File

@ -36,35 +36,32 @@ class File
*/ */
protected static $useUploadTempDirectory = false; protected static $useUploadTempDirectory = false;
/** /**
* Set the flag indicating whether the File Upload Temp directory should be used for temporary files * Set the flag indicating whether the File Upload Temp directory should be used for temporary files
* *
* @param boolean $useUploadTempDir Use File Upload Temporary directory (true or false) * @param bool $useUploadTempDir Use File Upload Temporary directory (true or false)
*/ */
public static function setUseUploadTempDirectory($useUploadTempDir = false) public static function setUseUploadTempDirectory($useUploadTempDir = false)
{ {
self::$useUploadTempDirectory = (boolean) $useUploadTempDir; self::$useUploadTempDirectory = (boolean) $useUploadTempDir;
} }
/** /**
* Get the flag indicating whether the File Upload Temp directory should be used for temporary files * Get the flag indicating whether the File Upload Temp directory should be used for temporary files
* *
* @return boolean Use File Upload Temporary directory (true or false) * @return bool Use File Upload Temporary directory (true or false)
*/ */
public static function getUseUploadTempDirectory() public static function getUseUploadTempDirectory()
{ {
return self::$useUploadTempDirectory; return self::$useUploadTempDirectory;
} }
/** /**
* Verify if a file exists * Verify if a file exists
* *
* @param string $pFilename Filename * @param string $pFilename Filename
* @return bool * @return bool
*/ */
public static function fileExists($pFilename) public static function fileExists($pFilename)
{ {
// Sick construction, but it seems that // Sick construction, but it seems that
@ -72,7 +69,7 @@ class File
// doing the original file_exists on ZIP archives... // doing the original file_exists on ZIP archives...
if (strtolower(substr($pFilename, 0, 3)) == 'zip') { if (strtolower(substr($pFilename, 0, 3)) == 'zip') {
// Open ZIP file and verify if the file exists // Open ZIP file and verify if the file exists
$zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6);
$archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1);
$zipClass = \PhpSpreadsheet\Settings::getZipClass(); $zipClass = \PhpSpreadsheet\Settings::getZipClass();
@ -80,6 +77,7 @@ class File
if ($zip->open($zipFile) === true) { if ($zip->open($zipFile) === true) {
$returnValue = ($zip->getFromName($archiveFile) !== false); $returnValue = ($zip->getFromName($archiveFile) !== false);
$zip->close(); $zip->close();
return $returnValue; return $returnValue;
} else { } else {
return false; return false;
@ -168,6 +166,7 @@ class File
$temp = tempnam(__FILE__, ''); $temp = tempnam(__FILE__, '');
if (file_exists($temp)) { if (file_exists($temp)) {
unlink($temp); unlink($temp);
return realpath(dirname($temp)); return realpath(dirname($temp));
} }

Some files were not shown because too many files have changed in this diff Show More