diff --git a/.php_cs b/.php_cs new file mode 100644 index 00000000..ed5a0ebb --- /dev/null +++ b/.php_cs @@ -0,0 +1,108 @@ +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); diff --git a/.travis.yml b/.travis.yml index 15e7a210..589c53c6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,6 +27,8 @@ before_script: script: ## PHP_CodeSniffer - ./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 - ./vendor/bin/phpunit --coverage-clover coverage-clover.xml diff --git a/composer.json b/composer.json index f2a69af4..ca41778b 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,8 @@ "require-dev": { "squizlabs/php_codesniffer": "2.*", "phpunit/phpunit": "4.6.*", - "mikey179/vfsStream": "1.5.*" + "mikey179/vfsStream": "1.5.*", + "friendsofphp/php-cs-fixer": "^1.11" }, "suggest": { "ext-zip": "*", diff --git a/src/Autoloader.php b/src/Autoloader.php index 4380522d..3ed00569 100644 --- a/src/Autoloader.php +++ b/src/Autoloader.php @@ -3,7 +3,6 @@ namespace PhpSpreadsheet; /** - * * Autoloader for PhpSpreadsheet classes * * Copyright (c) 2006 - 2016 PhpSpreadsheet @@ -31,7 +30,6 @@ class Autoloader { /** * Register the Autoloader with SPL - * */ public static function register() { @@ -40,10 +38,9 @@ class Autoloader spl_autoload_register('__autoload'); } // 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 * @@ -65,6 +62,6 @@ class Autoloader // Can't load return false; } - require($classFilePath); + require $classFilePath; } } diff --git a/src/Bootstrap.php b/src/Bootstrap.php index bacf33b7..53e704c3 100644 --- a/src/Bootstrap.php +++ b/src/Bootstrap.php @@ -1,7 +1,6 @@ cachePrefix.$pCoord.'.cache'); + $success = apc_fetch($this->cachePrefix . $pCoord . '.cache'); if ($success === false) { // Entry no longer exists in APC, so clear it from the cache array 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 false; } /** * Get cell at a specific coordinate * - * @access public * @param string $pCoord Coordinate of the cell * @throws \PhpSpreadsheet\Exception * @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) { // Entry no longer exists in APC, so clear it from the cache array 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 { // 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 * - * @access public * @param string $pCoord Coordinate address of the cell to delete * @throws \PhpSpreadsheet\Exception */ public function deleteCacheData($pCoord) { // 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 parent::deleteCacheData($pCoord); @@ -188,7 +183,6 @@ class APC extends CacheBase implements ICache /** * Clone the cell collection * - * @access public * @param \PhpSpreadsheet\Worksheet $parent The new worksheet that we're copying to * @throws \PhpSpreadsheet\Exception */ @@ -218,8 +212,6 @@ class APC extends CacheBase implements ICache /** * Clear the cell collection and disconnect from our parent - * - * @return void */ public function unsetWorksheetCells() { @@ -231,7 +223,7 @@ class APC extends CacheBase implements ICache // Flush the APC cache $this->__destruct(); - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; @@ -271,7 +263,7 @@ class APC extends CacheBase implements ICache * Identify whether the caching method is currently available * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable() { diff --git a/src/PhpSpreadsheet/CachedObjectStorage/CacheBase.php b/src/PhpSpreadsheet/CachedObjectStorage/CacheBase.php index bfe76dc8..787eac29 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/CacheBase.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/CacheBase.php @@ -50,7 +50,7 @@ abstract class CacheBase /** * Flag indicating whether the currently active Cell requires saving * - * @var boolean + * @var bool */ protected $currentCellIsDirty = true; @@ -60,7 +60,7 @@ abstract class CacheBase * * @var array of mixed */ - protected $cellCache = array(); + protected $cellCache = []; /** * 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? * * @param string $pCoord Coordinate address of the cell to check - * @return boolean + * @return bool */ public function isDataSet($pCoord) { @@ -105,7 +105,7 @@ abstract class CacheBase * * @param string $fromAddress Current 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) { @@ -125,8 +125,8 @@ abstract class CacheBase * Add or Update a cell in cache * * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function updateCacheData(\PhpSpreadsheet\Cell $cell) { @@ -170,7 +170,7 @@ abstract class CacheBase */ public function getSortedCellList() { - $sortKeys = array(); + $sortKeys = []; foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $column, $row); $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord; @@ -188,12 +188,12 @@ abstract class CacheBase public function getHighestRowAndColumn() { // Lookup highest column and highest row - $col = array('A' => '1A'); - $row = array(1); + $col = ['A' => '1A']; + $row = [1]; foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); $row[$r] = $r; - $col[$c] = strlen($c).$c; + $col[$c] = strlen($c) . $c; } if (!empty($row)) { // Determine highest column and row @@ -201,10 +201,10 @@ abstract class CacheBase $highestColumn = substr(max($col), 1); } - return array( - 'row' => $highestRow, - 'column' => $highestColumn - ); + return [ + 'row' => $highestRow, + 'column' => $highestColumn, + ]; } /** @@ -225,17 +225,19 @@ abstract class CacheBase public function getCurrentColumn() { sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row); + return $column; } /** * Return the row address of the currently active cell object * - * @return integer + * @return int */ public function getCurrentRow() { sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row); + return (integer) $row; } @@ -250,10 +252,11 @@ abstract class CacheBase { if ($row == null) { $colRow = $this->getHighestRowAndColumn(); + return $colRow['column']; } - $columnList = array(1); + $columnList = [1]; foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); if ($r != $row) { @@ -261,6 +264,7 @@ abstract class CacheBase } $columnList[] = \PhpSpreadsheet\Cell::columnIndexFromString($c); } + return \PhpSpreadsheet\Cell::stringFromColumnIndex(max($columnList) - 1); } @@ -275,10 +279,11 @@ abstract class CacheBase { if ($column == null) { $colRow = $this->getHighestRowAndColumn(); + return $colRow['row']; } - $rowList = array(0); + $rowList = [0]; foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); if ($c != $column) { @@ -302,6 +307,7 @@ abstract class CacheBase } else { $baseUnique = mt_rand(); } + return uniqid($baseUnique, true); } @@ -325,7 +331,6 @@ abstract class CacheBase * Remove a row, deleting all cells in that row * * @param string $row Row number to remove - * @return void */ public function removeRow($row) { @@ -341,7 +346,6 @@ abstract class CacheBase * Remove a column, deleting all cells in that column * * @param string $column Column ID to remove - * @return void */ public function removeColumn($column) { @@ -357,7 +361,7 @@ abstract class CacheBase * Identify whether the caching method is currently available * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable() { diff --git a/src/PhpSpreadsheet/CachedObjectStorage/DiscISAM.php b/src/PhpSpreadsheet/CachedObjectStorage/DiscISAM.php index 9414faea..826e6637 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/DiscISAM.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/DiscISAM.php @@ -51,7 +51,6 @@ class DiscISAM extends CacheBase implements ICache * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object * - * @return void * @throws \PhpSpreadsheet\Exception */ protected function storeData() @@ -61,10 +60,10 @@ class DiscISAM extends CacheBase implements ICache fseek($this->fileHandle, 0, SEEK_END); - $this->cellCache[$this->currentObjectID] = array( + $this->cellCache[$this->currentObjectID] = [ 'ptr' => ftell($this->fileHandle), - 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)) - ); + 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)), + ]; $this->currentCellIsDirty = false; } $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 \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) { @@ -146,7 +145,7 @@ class DiscISAM extends CacheBase implements ICache parent::copyCellCollection($parent); // Get a new id for the new file name $baseUnique = $this->getUniqueID(); - $newFileName = $this->cacheDirectory.'/PhpSpreadsheet.'.$baseUnique.'.cache'; + $newFileName = $this->cacheDirectory . '/PhpSpreadsheet.' . $baseUnique . '.cache'; // Copy the existing cell cache file copy($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 - * */ public function unsetWorksheetCells() { @@ -164,7 +162,7 @@ class DiscISAM extends CacheBase implements ICache $this->currentObject->detach(); $this->currentObject = $this->currentObjectID = null; } - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; @@ -181,14 +179,14 @@ class DiscISAM extends CacheBase implements ICache */ 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'] : \PhpSpreadsheet\Shared\File::sysGetTempDir(); parent::__construct($parent); if (is_null($this->fileHandle)) { $baseUnique = $this->getUniqueID(); - $this->fileName = $this->cacheDirectory.'/PhpSpreadsheet.'.$baseUnique.'.cache'; + $this->fileName = $this->cacheDirectory . '/PhpSpreadsheet.' . $baseUnique . '.cache'; $this->fileHandle = fopen($this->fileName, 'a+'); } } diff --git a/src/PhpSpreadsheet/CachedObjectStorage/ICache.php b/src/PhpSpreadsheet/CachedObjectStorage/ICache.php index 17a198f7..da9c4495 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/ICache.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/ICache.php @@ -31,8 +31,8 @@ interface ICache * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell); @@ -40,8 +40,8 @@ interface ICache * Add or Update a cell in cache * * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function updateCacheData(\PhpSpreadsheet\Cell $cell); @@ -49,8 +49,8 @@ interface ICache * Fetch a cell from cache identified by coordinate address * * @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 + * @return \PhpSpreadsheet\Cell Cell that was found, or null if not found */ public function getCacheData($pCoord); @@ -66,7 +66,7 @@ interface ICache * Is a value set in the current \PhpSpreadsheet\CachedObjectStorage\ICache for an indexed cell? * * @param string $pCoord Coordinate address of the cell to check - * @return boolean + * @return bool */ public function isDataSet($pCoord); @@ -95,7 +95,7 @@ interface ICache * Identify whether the caching method is currently available * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable(); } diff --git a/src/PhpSpreadsheet/CachedObjectStorage/Igbinary.php b/src/PhpSpreadsheet/CachedObjectStorage/Igbinary.php index b95c2649..1bb8944c 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/Igbinary.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/Igbinary.php @@ -30,7 +30,6 @@ class Igbinary extends CacheBase implements ICache * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object * - * @return void * @throws \PhpSpreadsheet\Exception */ protected function storeData() @@ -44,14 +43,13 @@ class Igbinary extends CacheBase implements ICache $this->currentObjectID = $this->currentObject = null; } // function _storeData() - /** * Add or Update a cell in cache identified by coordinate address * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) { @@ -66,7 +64,6 @@ class Igbinary extends CacheBase implements ICache return $cell; } - /** * Get cell at a specific coordinate * @@ -97,7 +94,6 @@ class Igbinary extends CacheBase implements ICache return $this->currentObject; } // function getCacheData() - /** * Get a list of all cell addresses currently held in cache * @@ -112,11 +108,8 @@ class Igbinary extends CacheBase implements ICache return parent::getCellList(); } - /** * Clear the cell collection and disconnect from our parent - * - * @return void */ public function unsetWorksheetCells() { @@ -124,18 +117,17 @@ class Igbinary extends CacheBase implements ICache $this->currentObject->detach(); $this->currentObject = $this->currentObjectID = null; } - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; } // function unsetWorksheetCells() - /** * Identify whether the caching method is currently available * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable() { diff --git a/src/PhpSpreadsheet/CachedObjectStorage/Memcache.php b/src/PhpSpreadsheet/CachedObjectStorage/Memcache.php index 260ff24c..959c2801 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/Memcache.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/Memcache.php @@ -36,7 +36,7 @@ class Memcache extends CacheBase implements ICache /** * Cache timeout * - * @var integer + * @var int */ private $cacheTime = 600; @@ -47,7 +47,6 @@ class Memcache extends CacheBase implements ICache */ private $memcache = null; - /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object @@ -71,14 +70,13 @@ class Memcache extends CacheBase implements ICache $this->currentObjectID = $this->currentObject = null; } - /** * Add or Update a cell in cache identified by coordinate address * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) { @@ -94,13 +92,12 @@ class Memcache extends CacheBase implements ICache return $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 - * @return boolean * @throws \PhpSpreadsheet\Exception + * @return bool */ public function isDataSet($pCoord) { @@ -110,18 +107,19 @@ class Memcache extends CacheBase implements ICache return true; } // 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) { // Entry no longer exists in Memcache, so clear it from the cache array 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 false; } - /** * Get cell at a specific coordinate * @@ -203,7 +201,7 @@ class Memcache extends CacheBase implements ICache $cacheList = $this->getCellList(); foreach ($cacheList as $cellID) { if ($cellID != $this->currentObjectID) { - $obj = $this->memcache->get($this->cachePrefix.$cellID.'.cache'); + $obj = $this->memcache->get($this->cachePrefix . $cellID . '.cache'); if ($obj === false) { // Entry no longer exists in Memcache, so clear it from the cache array parent::deleteCacheData($cellID); @@ -220,8 +218,6 @@ class Memcache extends CacheBase implements ICache /** * Clear the cell collection and disconnect from our parent - * - * @return void */ public function unsetWorksheetCells() { @@ -233,7 +229,7 @@ class Memcache extends CacheBase implements ICache // Flush the Memcache cache $this->__destruct(); - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; @@ -257,8 +253,8 @@ class Memcache extends CacheBase implements ICache $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.'; // Set a new Memcache object and connect to the Memcache server - $this->memcache = new Memcache(); - if (!$this->memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) { + $this->memcache = new self(); + 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}"); } $this->cacheTime = $cacheTime; @@ -271,7 +267,7 @@ class Memcache extends CacheBase implements ICache * Memcache error handler * * @param string $host Memcache server - * @param integer $port Memcache port + * @param int $port Memcache port * @throws \PhpSpreadsheet\Exception */ public function failureCallback($host, $port) @@ -286,7 +282,7 @@ class Memcache extends CacheBase implements ICache { $cacheList = $this->getCellList(); 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 * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable() { diff --git a/src/PhpSpreadsheet/CachedObjectStorage/Memory.php b/src/PhpSpreadsheet/CachedObjectStorage/Memory.php index ba567e71..0f3a8a7e 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/Memory.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/Memory.php @@ -28,8 +28,6 @@ class Memory extends CacheBase implements ICache { /** * Dummy method callable from CacheBase, but unused by Memory cache - * - * @return void */ protected function storeData() { @@ -40,8 +38,8 @@ class Memory extends CacheBase implements ICache * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) { @@ -53,7 +51,6 @@ class Memory extends CacheBase implements ICache return $cell; } - /** * Get cell at a specific coordinate * @@ -77,7 +74,6 @@ class Memory extends CacheBase implements ICache return $this->cellCache[$pCoord]; } - /** * Clone the cell collection * @@ -87,7 +83,7 @@ class Memory extends CacheBase implements ICache { parent::copyCellCollection($parent); - $newCollection = array(); + $newCollection = []; foreach ($this->cellCache as $k => &$cell) { $newCollection[$k] = clone $cell; $newCollection[$k]->attach($this); @@ -98,7 +94,6 @@ class Memory extends CacheBase implements ICache /** * Clear the cell collection and disconnect from our parent - * */ public function unsetWorksheetCells() { @@ -109,7 +104,7 @@ class Memory extends CacheBase implements ICache } unset($cell); - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; diff --git a/src/PhpSpreadsheet/CachedObjectStorage/MemoryGZip.php b/src/PhpSpreadsheet/CachedObjectStorage/MemoryGZip.php index 6e2be11a..9dc30f19 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/MemoryGZip.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/MemoryGZip.php @@ -30,7 +30,6 @@ class MemoryGZip extends CacheBase implements ICache * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object * - * @return void * @throws \PhpSpreadsheet\Exception */ protected function storeData() @@ -44,14 +43,13 @@ class MemoryGZip extends CacheBase implements ICache $this->currentObjectID = $this->currentObject = null; } - /** * Add or Update a cell in cache identified by coordinate address * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) { @@ -66,7 +64,6 @@ class MemoryGZip extends CacheBase implements ICache return $cell; } - /** * Get cell at a specific coordinate * @@ -97,7 +94,6 @@ class MemoryGZip extends CacheBase implements ICache return $this->currentObject; } - /** * Get a list of all cell addresses currently held in cache * @@ -112,11 +108,8 @@ class MemoryGZip extends CacheBase implements ICache return parent::getCellList(); } - /** * Clear the cell collection and disconnect from our parent - * - * @return void */ public function unsetWorksheetCells() { @@ -124,7 +117,7 @@ class MemoryGZip extends CacheBase implements ICache $this->currentObject->detach(); $this->currentObject = $this->currentObjectID = null; } - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; diff --git a/src/PhpSpreadsheet/CachedObjectStorage/MemorySerialized.php b/src/PhpSpreadsheet/CachedObjectStorage/MemorySerialized.php index 41ecad5b..4114bb3d 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/MemorySerialized.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/MemorySerialized.php @@ -30,7 +30,6 @@ class MemorySerialized extends CacheBase implements ICache * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object * - * @return void * @throws \PhpSpreadsheet\Exception */ protected function storeData() @@ -49,8 +48,8 @@ class MemorySerialized extends CacheBase implements ICache * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\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 - * - * @return void */ public function unsetWorksheetCells() { @@ -120,7 +117,7 @@ class MemorySerialized extends CacheBase implements ICache $this->currentObject->detach(); $this->currentObject = $this->currentObjectID = null; } - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; diff --git a/src/PhpSpreadsheet/CachedObjectStorage/PHPTemp.php b/src/PhpSpreadsheet/CachedObjectStorage/PHPTemp.php index f235656e..185a35ad 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/PHPTemp.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/PHPTemp.php @@ -36,7 +36,7 @@ class PHPTemp extends CacheBase implements ICache /** * Memory limit to use before reverting to file cache * - * @var integer + * @var int */ private $memoryCacheSize = null; @@ -53,23 +53,22 @@ class PHPTemp extends CacheBase implements ICache fseek($this->fileHandle, 0, SEEK_END); - $this->cellCache[$this->currentObjectID] = array( + $this->cellCache[$this->currentObjectID] = [ 'ptr' => ftell($this->fileHandle), - 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)) - ); + 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)), + ]; $this->currentCellIsDirty = false; } $this->currentObjectID = $this->currentObject = null; } - /** * Add or Update a cell in cache identified by coordinate address * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) { @@ -84,7 +83,6 @@ class PHPTemp extends CacheBase implements ICache return $cell; } - /** * 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 - * - * @return void */ public function unsetWorksheetCells() { @@ -159,7 +155,7 @@ class PHPTemp extends CacheBase implements ICache $this->currentObject->detach(); $this->currentObject = $this->currentObjectID = null; } - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; diff --git a/src/PhpSpreadsheet/CachedObjectStorage/SQLite.php b/src/PhpSpreadsheet/CachedObjectStorage/SQLite.php index da5b57e5..33a5d78f 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/SQLite.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/SQLite.php @@ -51,7 +51,7 @@ class SQLite extends CacheBase implements ICache if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { $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())); } $this->currentCellIsDirty = false; @@ -64,8 +64,8 @@ class SQLite extends CacheBase implements ICache * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell */ public function addCacheData($pCoord, \PhpSpreadsheet\Cell $cell) { @@ -94,7 +94,7 @@ class SQLite extends CacheBase implements ICache } $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); if ($cellResultSet === false) { 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? * * @param string $pCoord Coordinate address of the cell to check - * @return boolean * @throws \PhpSpreadsheet\Exception + * @return bool */ public function isDataSet($pCoord) { @@ -129,7 +129,7 @@ class SQLite extends CacheBase implements ICache } // 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); if ($cellResultSet === false) { 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 false; } + return true; } @@ -154,7 +155,7 @@ class SQLite extends CacheBase implements ICache } // 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)) { 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 $toAddress Destination address of the cell to move * @throws \PhpSpreadsheet\Exception - * @return boolean + * @return bool */ public function moveCell($fromAddress, $toAddress) { @@ -176,13 +177,13 @@ class SQLite extends CacheBase implements ICache $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); if ($result === false) { 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); if ($result === false) { 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 * - * @return string[] * @throws \PhpSpreadsheet\Exception + * @return string[] */ public function getCellList() { @@ -203,13 +204,13 @@ class SQLite extends CacheBase implements ICache $this->storeData(); } - $query = "SELECT id FROM kvp_".$this->TableName; + $query = 'SELECT id FROM kvp_' . $this->TableName; $cellIdsResult = $this->DBHandle->unbufferedQuery($query, SQLITE_ASSOC); if ($cellIdsResult === false) { throw new \PhpSpreadsheet\Exception(sqlite_error_string($this->DBHandle->lastError())); } - $cellKeys = array(); + $cellKeys = []; foreach ($cellIdsResult as $row) { $cellKeys[] = $row['id']; } @@ -230,8 +231,8 @@ class SQLite extends CacheBase implements ICache // Get a new id for the new table name $tableName = str_replace('.', '_', $this->getUniqueID()); - if (!$this->DBHandle->queryExec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) - AS SELECT * FROM kvp_'.$this->TableName) + if (!$this->DBHandle->queryExec('CREATE TABLE kvp_' . $tableName . ' (id VARCHAR(12) PRIMARY KEY, value BLOB) + AS SELECT * FROM kvp_' . $this->TableName) ) { 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 - * - * @return void */ public function unsetWorksheetCells() { @@ -275,7 +274,7 @@ class SQLite extends CacheBase implements ICache if ($this->DBHandle === false) { 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())); } } @@ -287,7 +286,7 @@ class SQLite extends CacheBase implements ICache public function __destruct() { if (!is_null($this->DBHandle)) { - $this->DBHandle->queryExec('DROP TABLE kvp_'.$this->TableName); + $this->DBHandle->queryExec('DROP TABLE kvp_' . $this->TableName); } $this->DBHandle = null; } @@ -296,7 +295,7 @@ class SQLite extends CacheBase implements ICache * Identify whether the caching method is currently available * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable() { diff --git a/src/PhpSpreadsheet/CachedObjectStorage/SQLite3.php b/src/PhpSpreadsheet/CachedObjectStorage/SQLite3.php index 0e625f69..6acb1f4a 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/SQLite3.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/SQLite3.php @@ -95,8 +95,8 @@ class SQLite3 extends CacheBase implements ICache * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\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 * @throws \PhpSpreadsheet\Exception - * @return \PhpSpreadsheet\Cell Cell that was found, or null if not found * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\Cell Cell that was found, or null if not found */ public function getCacheData($pCoord) { @@ -152,8 +152,8 @@ class SQLite3 extends CacheBase implements ICache * Is a value set for an indexed cell? * * @param string $pCoord Coordinate address of the cell to check - * @return boolean * @throws \PhpSpreadsheet\Exception + * @return bool */ 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 $toAddress Destination address of the cell to move - * @return boolean * @throws \PhpSpreadsheet\Exception + * @return bool */ 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 * - * @return string[] * @throws \PhpSpreadsheet\Exception + * @return string[] */ public function getCellList() { @@ -237,13 +237,13 @@ class SQLite3 extends CacheBase implements ICache $this->storeData(); } - $query = "SELECT id FROM kvp_".$this->TableName; + $query = 'SELECT id FROM kvp_' . $this->TableName; $cellIdsResult = $this->DBHandle->query($query); if ($cellIdsResult === false) { throw new \PhpSpreadsheet\Exception($this->DBHandle->lastErrorMsg()); } - $cellKeys = array(); + $cellKeys = []; while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) { $cellKeys[] = $row['id']; } @@ -264,8 +264,8 @@ class SQLite3 extends CacheBase implements ICache // Get a new id for the new table name $tableName = str_replace('.', '_', $this->getUniqueID()); - if (!$this->DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) - AS SELECT * FROM kvp_'.$this->TableName) + if (!$this->DBHandle->exec('CREATE TABLE kvp_' . $tableName . ' (id VARCHAR(12) PRIMARY KEY, value BLOB) + AS SELECT * FROM kvp_' . $this->TableName) ) { 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 - * - * @return void */ public function unsetWorksheetCells() { @@ -309,15 +307,15 @@ class SQLite3 extends CacheBase implements ICache if ($this->DBHandle === false) { 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()); } } - $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->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->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->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'); } /** @@ -326,7 +324,7 @@ class SQLite3 extends CacheBase implements ICache public function __destruct() { 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 = null; @@ -336,7 +334,7 @@ class SQLite3 extends CacheBase implements ICache * Identify whether the caching method is currently available * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable() { diff --git a/src/PhpSpreadsheet/CachedObjectStorage/Wincache.php b/src/PhpSpreadsheet/CachedObjectStorage/Wincache.php index bd337445..de9e2f94 100644 --- a/src/PhpSpreadsheet/CachedObjectStorage/Wincache.php +++ b/src/PhpSpreadsheet/CachedObjectStorage/Wincache.php @@ -36,16 +36,14 @@ class Wincache extends CacheBase implements ICache /** * Cache timeout * - * @var integer + * @var int */ private $cacheTime = 600; - /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object * - * @return void * @throws \PhpSpreadsheet\Exception */ protected function storeData() @@ -54,15 +52,15 @@ class Wincache extends CacheBase implements ICache $this->currentObject->detach(); $obj = serialize($this->currentObject); - if (wincache_ucache_exists($this->cachePrefix.$this->currentObjectID.'.cache')) { - if (!wincache_ucache_set($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) { + if (wincache_ucache_exists($this->cachePrefix . $this->currentObjectID . '.cache')) { + if (!wincache_ucache_set($this->cachePrefix . $this->currentObjectID . '.cache', $obj, $this->cacheTime)) { $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 { - 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(); - 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; @@ -76,8 +74,8 @@ class Wincache extends CacheBase implements ICache * * @param string $pCoord Coordinate address of the cell to update * @param \PhpSpreadsheet\Cell $cell Cell to update - * @return \PhpSpreadsheet\Cell * @throws \PhpSpreadsheet\Exception + * @return \PhpSpreadsheet\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? * * @param string $pCoord Coordinate address of the cell to check - * @return boolean * @throws \PhpSpreadsheet\Exception + * @return bool */ public function isDataSet($pCoord) { @@ -108,18 +106,19 @@ class Wincache extends CacheBase implements ICache return true; } // 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) { // Entry no longer exists in Wincache, so clear it from the cache array 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 false; } - /** * Get cell at a specific coordinate * @@ -138,11 +137,11 @@ class Wincache extends CacheBase implements ICache $obj = null; if (parent::isDataSet($pCoord)) { $success = false; - $obj = wincache_ucache_get($this->cachePrefix.$pCoord.'.cache', $success); + $obj = wincache_ucache_get($this->cachePrefix . $pCoord . '.cache', $success); if ($success === false) { // Entry no longer exists in WinCache, so clear it from the cache array 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 { // Return null if requested entry doesn't exist in cache @@ -159,7 +158,6 @@ class Wincache extends CacheBase implements ICache return $this->currentObject; } - /** * 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) { // 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 parent::deleteCacheData($pCoord); @@ -205,26 +203,23 @@ class Wincache extends CacheBase implements ICache foreach ($cacheList as $cellID) { if ($cellID != $this->currentObjectID) { $success = false; - $obj = wincache_ucache_get($this->cachePrefix.$cellID.'.cache', $success); + $obj = wincache_ucache_get($this->cachePrefix . $cellID . '.cache', $success); if ($success === false) { // Entry no longer exists in WinCache, so clear it from the cache array 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(); - 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; } - /** * Clear the cell collection and disconnect from our parent - * - * @return void */ public function unsetWorksheetCells() { @@ -236,7 +231,7 @@ class Wincache extends CacheBase implements ICache // Flush the WinCache cache $this->__destruct(); - $this->cellCache = array(); + $this->cellCache = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; @@ -250,11 +245,11 @@ class Wincache extends CacheBase implements ICache */ 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)) { $baseUnique = $this->getUniqueID(); - $this->cachePrefix = substr(md5($baseUnique), 0, 8).'.'; + $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.'; $this->cacheTime = $cacheTime; parent::__construct($parent); @@ -268,7 +263,7 @@ class Wincache extends CacheBase implements ICache { $cacheList = $this->getCellList(); 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 * Some methods are dependent on the availability of certain extensions being enabled in the PHP build * - * @return boolean + * @return bool */ public static function cacheMethodIsAvailable() { diff --git a/src/PhpSpreadsheet/CachedObjectStorageFactory.php b/src/PhpSpreadsheet/CachedObjectStorageFactory.php index a12a42d2..c92228a4 100644 --- a/src/PhpSpreadsheet/CachedObjectStorageFactory.php +++ b/src/PhpSpreadsheet/CachedObjectStorageFactory.php @@ -26,17 +26,17 @@ namespace PhpSpreadsheet; */ class CachedObjectStorageFactory { - const CACHE_IN_MEMORY = 'Memory'; - const CACHE_IN_MEMORY_GZIP = 'MemoryGZip'; - const CACHE_IN_MEMORY_SERIALIZED = 'MemorySerialized'; - const CACHE_IGBINARY = 'Igbinary'; - const CACHE_TO_DISCISAM = 'DiscISAM'; - const CACHE_TO_APC = 'APC'; - const CACHE_TO_MEMCACHE = 'Memcache'; - const CACHE_TO_PHPTEMP = 'PHPTemp'; - const CACHE_TO_WINCACHE = 'Wincache'; - const CACHE_TO_SQLITE = 'SQLite'; - const CACHE_TO_SQLITE3 = 'SQLite3'; + const CACHE_IN_MEMORY = 'Memory'; + const CACHE_IN_MEMORY_GZIP = 'MemoryGZip'; + const CACHE_IN_MEMORY_SERIALIZED = 'MemorySerialized'; + const CACHE_IGBINARY = 'Igbinary'; + const CACHE_TO_DISCISAM = 'DiscISAM'; + const CACHE_TO_APC = 'APC'; + const CACHE_TO_MEMCACHE = 'Memcache'; + const CACHE_TO_PHPTEMP = 'PHPTemp'; + const CACHE_TO_WINCACHE = 'Wincache'; + const CACHE_TO_SQLITE = 'SQLite'; + const CACHE_TO_SQLITE3 = 'SQLite3'; /** * Name of the method used for cell cacheing @@ -109,7 +109,6 @@ class CachedObjectStorageFactory */ private static $storageMethodParameters = []; - /** * Return the current cache storage method * @@ -147,13 +146,14 @@ class CachedObjectStorageFactory **/ public static function getCacheStorageMethods() { - $activeMethods = array(); + $activeMethods = []; foreach (self::$storageMethods as $storageMethod) { $cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $storageMethod; - if (call_user_func(array($cacheStorageClass, 'cacheMethodIsAvailable'))) { + if (call_user_func([$cacheStorageClass, 'cacheMethodIsAvailable'])) { $activeMethods[] = $storageMethod; } } + return $activeMethods; } @@ -163,7 +163,7 @@ class CachedObjectStorageFactory * @param string $method Name of the method to use for cell cacheing * @param mixed[] $arguments Additional arguments to pass to the cell caching class * when instantiating - * @return boolean + * @return bool **/ public static function initialize($method = self::CACHE_IN_MEMORY, $arguments = []) { @@ -171,7 +171,7 @@ class CachedObjectStorageFactory return false; } - $cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\'.$method; + $cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $method; if (!call_user_func([$cacheStorageClass, 'cacheMethodIsAvailable'])) { return false; } @@ -187,6 +187,7 @@ class CachedObjectStorageFactory self::$cacheStorageClass = '\\PhpSpreadsheet\\CachedObjectStorage\\' . $method; self::$cacheStorageMethod = $method; } + return true; } @@ -218,12 +219,11 @@ class CachedObjectStorageFactory /** * Clear the cache storage - * **/ public static function finalize() { self::$cacheStorageMethod = null; self::$cacheStorageClass = null; - self::$storageMethodParameters = array(); + self::$storageMethodParameters = []; } } diff --git a/src/PhpSpreadsheet/CalcEngine/CyclicReferenceStack.php b/src/PhpSpreadsheet/CalcEngine/CyclicReferenceStack.php index eb8c68bd..36977c38 100644 --- a/src/PhpSpreadsheet/CalcEngine/CyclicReferenceStack.php +++ b/src/PhpSpreadsheet/CalcEngine/CyclicReferenceStack.php @@ -31,12 +31,12 @@ class CyclicReferenceStack * * @var mixed[] */ - private $stack = array(); + private $stack = []; /** * Return the number of entries on the stack * - * @return integer + * @return int */ public function count() { @@ -78,7 +78,7 @@ class CyclicReferenceStack */ public function clear() { - $this->stack = array(); + $this->stack = []; } /** diff --git a/src/PhpSpreadsheet/CalcEngine/Logger.php b/src/PhpSpreadsheet/CalcEngine/Logger.php index 0ece55f1..a5c1ed5f 100644 --- a/src/PhpSpreadsheet/CalcEngine/Logger.php +++ b/src/PhpSpreadsheet/CalcEngine/Logger.php @@ -31,7 +31,7 @@ class Logger * If true, then a debug log will be generated * If false, then a debug log will not be generated * - * @var boolean + * @var bool */ private $writeDebugLog = false; @@ -41,7 +41,7 @@ class Logger * If false, then a debug log will not be echoed * A debug log can only be echoed if it is generated * - * @var boolean + * @var bool */ private $echoDebugLog = false; @@ -50,7 +50,7 @@ class Logger * * @var string[] */ - private $debugLog = array(); + private $debugLog = []; /** * The calculation engine cell reference stack @@ -72,7 +72,7 @@ class Logger /** * Enable/Disable Calculation engine logging * - * @param boolean $pValue + * @param bool $pValue */ public function setWriteDebugLog($pValue = false) { @@ -82,7 +82,7 @@ class Logger /** * Return whether calculation engine logging is enabled or disabled * - * @return boolean + * @return bool */ public function getWriteDebugLog() { @@ -92,7 +92,7 @@ class Logger /** * Enable/Disable echoing of debug log information * - * @param boolean $pValue + * @param bool $pValue */ public function setEchoDebugLog($pValue = false) { @@ -102,7 +102,7 @@ class Logger /** * Return whether echoing of debug log information is enabled or disabled * - * @return boolean + * @return bool */ public function getEchoDebugLog() { @@ -135,7 +135,7 @@ class Logger */ public function clearLog() { - $this->debugLog = array(); + $this->debugLog = []; } /** diff --git a/src/PhpSpreadsheet/Calculation.php b/src/PhpSpreadsheet/Calculation.php index 4b3f661d..e4d1b32d 100644 --- a/src/PhpSpreadsheet/Calculation.php +++ b/src/PhpSpreadsheet/Calculation.php @@ -44,22 +44,21 @@ if (!defined('CALCULATION_REGEXP_CELLREF')) { class Calculation { /** Constants */ - /** Regular Expressions */ +/** Regular Expressions */ // Numeric operand - const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?'; + const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?'; // String operand - const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"'; + const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"'; // Opening bracket - const CALCULATION_REGEXP_OPENBRACE = '\('; + const CALCULATION_REGEXP_OPENBRACE = '\('; // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it) - const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\('; + const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\('; // Cell reference (cell or range of cells, with or without a sheet reference) - const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF; + const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF; // Named Range of cells - const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE; + const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE; // Error - const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; - + const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; /** constants */ const RETURN_ARRAY_AS_ERROR = 'error'; @@ -68,20 +67,16 @@ class Calculation private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; - /** * Instance of this class * - * @access private * @var \PhpSpreadsheet\Calculation */ private static $instance; - /** * Instance of the spreadsheet this Calculation Engine is using * - * @access private * @var PhpSpreadsheet */ private $spreadsheet; @@ -89,7 +84,6 @@ class Calculation /** * List of instances of the calculation engine that we've instantiated for individual spreadsheets * - * @access private * @var \PhpSpreadsheet\Calculation[] */ private static $spreadsheetSets; @@ -97,54 +91,46 @@ class Calculation /** * Calculation cache * - * @access private * @var array */ - private $calculationCache = array (); - + private $calculationCache = []; /** * Calculation cache enabled * - * @access private - * @var boolean + * @var bool */ private $calculationCacheEnabled = true; - /** * List of operators that can be used within formulae * The true/false value indicates whether it is a binary operator or a unary operator * - * @access private * @var array */ - private static $operators = array( + private static $operators = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '%' => false, '~' => false, '>' => true, '<' => true, '=' => true, '>=' => true, - '<=' => true, '<>' => true, '|' => true, ':' => true - ); + '<=' => true, '<>' => true, '|' => true, ':' => true, + ]; /** * List of binary operators (those that expect two operands) * - * @access private * @var array */ - private static $binaryOperators = array( + private static $binaryOperators = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, - '|' => true, ':' => true - ); + '|' => true, ':' => true, + ]; /** * The debug log generated by the calculation engine * - * @access private * @var CalcEngine\Logger - * */ private $debugLog; @@ -153,39 +139,32 @@ class Calculation * If true, then a user error will be triggered * If false, then an exception will be thrown * - * @access public - * @var boolean - * + * @var bool */ public $suppressFormulaErrors = false; /** * Error message for any error that was raised/thrown by the calculation engine * - * @access public * @var string - * */ public $formulaError = null; /** * An array of the nested cell references accessed by the calculation engine, used for the debug log * - * @access private * @var array of string - * */ private $cyclicReferenceStack; - private $cellStack = array(); + private $cellStack = []; /** * Current iteration counter for cyclic formulae * If the value is 0 (or less) then cyclic formulae will throw an exception, * otherwise they will iterate to the limit defined here before returning a result * - * @var integer - * + * @var int */ private $cyclicFormulaCounter = 1; @@ -194,8 +173,7 @@ class Calculation /** * Number of iterations for cyclic formulae * - * @var integer - * + * @var int */ public $cyclicFormulaCount = 1; @@ -203,16 +181,13 @@ class Calculation * Epsilon Precision used for comparisons in calculations * * @var float - * */ - private $delta = 0.1e-12; - + private $delta = 0.1e-12; /** * The current locale setting * * @var string - * */ private static $localeLanguage = 'en_us'; // US English (default locale) @@ -221,1844 +196,1839 @@ class Calculation * Note that this is read for the locale subdirectory only when requested * * @var string[] - * */ - private static $validLocaleLanguages = array( - 'en' // English (default language) - ); + private static $validLocaleLanguages = [ + 'en', // English (default language) + ]; /** * Locale-specific argument separator for function arguments * * @var string - * */ private static $localeArgumentSeparator = ','; - private static $localeFunctions = array(); + private static $localeFunctions = []; /** * Locale-specific translations for Excel constants (True, False and Null) * * @var string[] - * */ - public static $localeBoolean = array( - 'TRUE' => 'TRUE', + public static $localeBoolean = [ + 'TRUE' => 'TRUE', 'FALSE' => 'FALSE', - 'NULL' => 'NULL' - ); + 'NULL' => 'NULL', + ]; /** * Excel constant string translations to their PHP equivalents * Constant conversion from text name/value to actual (datatyped) value * * @var string[] - * */ - private static $excelConstants = array( - 'TRUE' => true, + private static $excelConstants = [ + 'TRUE' => true, 'FALSE' => false, - 'NULL' => null - ); + 'NULL' => null, + ]; // PhpSpreadsheet functions - private static $phpSpreadsheetFunctions = array( - 'ABS' => array( + private static $phpSpreadsheetFunctions = [ + 'ABS' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'abs', - 'argumentCount' => '1' - ), - 'ACCRINT' => array( + 'argumentCount' => '1', + ], + 'ACCRINT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::ACCRINT', - 'argumentCount' => '4-7' - ), - 'ACCRINTM' => array( + 'argumentCount' => '4-7', + ], + 'ACCRINTM' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::ACCRINTM', - 'argumentCount' => '3-5' - ), - 'ACOS' => array( + 'argumentCount' => '3-5', + ], + 'ACOS' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'acos', - 'argumentCount' => '1' - ), - 'ACOSH' => array( + 'argumentCount' => '1', + ], + 'ACOSH' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'acosh', - 'argumentCount' => '1' - ), - 'ADDRESS' => array( + 'argumentCount' => '1', + ], + 'ADDRESS' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::cellAddress', - 'argumentCount' => '2-5' - ), - 'AMORDEGRC' => array( + 'argumentCount' => '2-5', + ], + 'AMORDEGRC' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::AMORDEGRC', - 'argumentCount' => '6,7' - ), - 'AMORLINC' => array( + 'argumentCount' => '6,7', + ], + 'AMORLINC' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::AMORLINC', - 'argumentCount' => '6,7' - ), - 'AND' => array( + 'argumentCount' => '6,7', + ], + 'AND' => [ 'category' => Calculation\Categories::CATEGORY_LOGICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Logical::logicalAnd', - 'argumentCount' => '1+' - ), - 'AREAS' => array( + 'argumentCount' => '1+', + ], + 'AREAS' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1' - ), - 'ASC' => array( + 'argumentCount' => '1', + ], + 'ASC' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1' - ), - 'ASIN' => array( + 'argumentCount' => '1', + ], + 'ASIN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'asin', - 'argumentCount' => '1' - ), - 'ASINH' => array( + 'argumentCount' => '1', + ], + 'ASINH' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'asinh', - 'argumentCount' => '1' - ), - 'ATAN' => array( + 'argumentCount' => '1', + ], + 'ATAN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'atan', - 'argumentCount' => '1' - ), - 'ATAN2' => array( + 'argumentCount' => '1', + ], + 'ATAN2' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::ATAN2', - 'argumentCount' => '2' - ), - 'ATANH' => array( + 'argumentCount' => '2', + ], + 'ATANH' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'atanh', - 'argumentCount' => '1' - ), - 'AVEDEV' => array( + 'argumentCount' => '1', + ], + 'AVEDEV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::AVEDEV', - 'argumentCount' => '1+' - ), - 'AVERAGE' => array( + 'argumentCount' => '1+', + ], + 'AVERAGE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::AVERAGE', - 'argumentCount' => '1+' - ), - 'AVERAGEA' => array( + 'argumentCount' => '1+', + ], + 'AVERAGEA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::AVERAGEA', - 'argumentCount' => '1+' - ), - 'AVERAGEIF' => array( + 'argumentCount' => '1+', + ], + 'AVERAGEIF' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::AVERAGEIF', - 'argumentCount' => '2,3' - ), - 'AVERAGEIFS' => array( + 'argumentCount' => '2,3', + ], + 'AVERAGEIFS' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '3+' - ), - 'BAHTTEXT' => array( + 'argumentCount' => '3+', + ], + 'BAHTTEXT' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1' - ), - 'BESSELI' => array( + 'argumentCount' => '1', + ], + 'BESSELI' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::BESSELI', - 'argumentCount' => '2' - ), - 'BESSELJ' => array( + 'argumentCount' => '2', + ], + 'BESSELJ' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::BESSELJ', - 'argumentCount' => '2' - ), - 'BESSELK' => array( + 'argumentCount' => '2', + ], + 'BESSELK' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::BESSELK', - 'argumentCount' => '2' - ), - 'BESSELY' => array( + 'argumentCount' => '2', + ], + 'BESSELY' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::BESSELY', - 'argumentCount' => '2' - ), - 'BETADIST' => array( + 'argumentCount' => '2', + ], + 'BETADIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::BETADIST', - 'argumentCount' => '3-5' - ), - 'BETAINV' => array( + 'argumentCount' => '3-5', + ], + 'BETAINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::BETAINV', - 'argumentCount' => '3-5' - ), - 'BIN2DEC' => array( + 'argumentCount' => '3-5', + ], + 'BIN2DEC' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::BINTODEC', - 'argumentCount' => '1' - ), - 'BIN2HEX' => array( + 'argumentCount' => '1', + ], + 'BIN2HEX' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::BINTOHEX', - 'argumentCount' => '1,2' - ), - 'BIN2OCT' => array( + 'argumentCount' => '1,2', + ], + 'BIN2OCT' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::BINTOOCT', - 'argumentCount' => '1,2' - ), - 'BINOMDIST' => array( + 'argumentCount' => '1,2', + ], + 'BINOMDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::BINOMDIST', - 'argumentCount' => '4' - ), - 'CEILING' => array( + 'argumentCount' => '4', + ], + 'CEILING' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::CEILING', - 'argumentCount' => '2' - ), - 'CELL' => array( + 'argumentCount' => '2', + ], + 'CELL' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1,2' - ), - 'CHAR' => array( + 'argumentCount' => '1,2', + ], + 'CHAR' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::CHARACTER', - 'argumentCount' => '1' - ), - 'CHIDIST' => array( + 'argumentCount' => '1', + ], + 'CHIDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::CHIDIST', - 'argumentCount' => '2' - ), - 'CHIINV' => array( + 'argumentCount' => '2', + ], + 'CHIINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::CHIINV', - 'argumentCount' => '2' - ), - 'CHITEST' => array( + 'argumentCount' => '2', + ], + 'CHITEST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2' - ), - 'CHOOSE' => array( + 'argumentCount' => '2', + ], + 'CHOOSE' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::CHOOSE', - 'argumentCount' => '2+' - ), - 'CLEAN' => array( + 'argumentCount' => '2+', + ], + 'CLEAN' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::TRIMNONPRINTABLE', - 'argumentCount' => '1' - ), - 'CODE' => array( + 'argumentCount' => '1', + ], + 'CODE' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::ASCIICODE', - 'argumentCount' => '1' - ), - 'COLUMN' => array( + 'argumentCount' => '1', + ], + 'COLUMN' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::COLUMN', 'argumentCount' => '-1', - 'passByReference' => array(true) - ), - 'COLUMNS' => array( + 'passByReference' => [true], + ], + 'COLUMNS' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::COLUMNS', - 'argumentCount' => '1' - ), - 'COMBIN' => array( + 'argumentCount' => '1', + ], + 'COMBIN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::COMBIN', - 'argumentCount' => '2' - ), - 'COMPLEX' => array( + 'argumentCount' => '2', + ], + 'COMPLEX' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::COMPLEX', - 'argumentCount' => '2,3' - ), - 'CONCATENATE' => array( + 'argumentCount' => '2,3', + ], + 'CONCATENATE' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::CONCATENATE', - 'argumentCount' => '1+' - ), - 'CONFIDENCE' => array( + 'argumentCount' => '1+', + ], + 'CONFIDENCE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::CONFIDENCE', - 'argumentCount' => '3' - ), - 'CONVERT' => array( + 'argumentCount' => '3', + ], + 'CONVERT' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::CONVERTUOM', - 'argumentCount' => '3' - ), - 'CORREL' => array( + 'argumentCount' => '3', + ], + 'CORREL' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::CORREL', - 'argumentCount' => '2' - ), - 'COS' => array( + 'argumentCount' => '2', + ], + 'COS' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'cos', - 'argumentCount' => '1' - ), - 'COSH' => array( + 'argumentCount' => '1', + ], + 'COSH' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'cosh', - 'argumentCount' => '1' - ), - 'COUNT' => array( + 'argumentCount' => '1', + ], + 'COUNT' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::COUNT', - 'argumentCount' => '1+' - ), - 'COUNTA' => array( + 'argumentCount' => '1+', + ], + 'COUNTA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::COUNTA', - 'argumentCount' => '1+' - ), - 'COUNTBLANK' => array( + 'argumentCount' => '1+', + ], + 'COUNTBLANK' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::COUNTBLANK', - 'argumentCount' => '1' - ), - 'COUNTIF' => array( + 'argumentCount' => '1', + ], + 'COUNTIF' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::COUNTIF', - 'argumentCount' => '2' - ), - 'COUNTIFS' => array( + 'argumentCount' => '2', + ], + 'COUNTIFS' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2' - ), - 'COUPDAYBS' => array( + 'argumentCount' => '2', + ], + 'COUPDAYBS' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::COUPDAYBS', - 'argumentCount' => '3,4' - ), - 'COUPDAYS' => array( + 'argumentCount' => '3,4', + ], + 'COUPDAYS' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::COUPDAYS', - 'argumentCount' => '3,4' - ), - 'COUPDAYSNC' => array( + 'argumentCount' => '3,4', + ], + 'COUPDAYSNC' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::COUPDAYSNC', - 'argumentCount' => '3,4' - ), - 'COUPNCD' => array( + 'argumentCount' => '3,4', + ], + 'COUPNCD' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::COUPNCD', - 'argumentCount' => '3,4' - ), - 'COUPNUM' => array( + 'argumentCount' => '3,4', + ], + 'COUPNUM' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::COUPNUM', - 'argumentCount' => '3,4' - ), - 'COUPPCD' => array( + 'argumentCount' => '3,4', + ], + 'COUPPCD' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::COUPPCD', - 'argumentCount' => '3,4' - ), - 'COVAR' => array( + 'argumentCount' => '3,4', + ], + 'COVAR' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::COVAR', - 'argumentCount' => '2' - ), - 'CRITBINOM' => array( + 'argumentCount' => '2', + ], + 'CRITBINOM' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::CRITBINOM', - 'argumentCount' => '3' - ), - 'CUBEKPIMEMBER' => array( + 'argumentCount' => '3', + ], + 'CUBEKPIMEMBER' => [ 'category' => Calculation\Categories::CATEGORY_CUBE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '?' - ), - 'CUBEMEMBER' => array( + 'argumentCount' => '?', + ], + 'CUBEMEMBER' => [ 'category' => Calculation\Categories::CATEGORY_CUBE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '?' - ), - 'CUBEMEMBERPROPERTY' => array( + 'argumentCount' => '?', + ], + 'CUBEMEMBERPROPERTY' => [ 'category' => Calculation\Categories::CATEGORY_CUBE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '?' - ), - 'CUBERANKEDMEMBER' => array( + 'argumentCount' => '?', + ], + 'CUBERANKEDMEMBER' => [ 'category' => Calculation\Categories::CATEGORY_CUBE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '?' - ), - 'CUBESET' => array( + 'argumentCount' => '?', + ], + 'CUBESET' => [ 'category' => Calculation\Categories::CATEGORY_CUBE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '?' - ), - 'CUBESETCOUNT' => array( + 'argumentCount' => '?', + ], + 'CUBESETCOUNT' => [ 'category' => Calculation\Categories::CATEGORY_CUBE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '?' - ), - 'CUBEVALUE' => array( + 'argumentCount' => '?', + ], + 'CUBEVALUE' => [ 'category' => Calculation\Categories::CATEGORY_CUBE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '?' - ), - 'CUMIPMT' => array( + 'argumentCount' => '?', + ], + 'CUMIPMT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::CUMIPMT', - 'argumentCount' => '6' - ), - 'CUMPRINC' => array( + 'argumentCount' => '6', + ], + 'CUMPRINC' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::CUMPRINC', - 'argumentCount' => '6' - ), - 'DATE' => array( + 'argumentCount' => '6', + ], + 'DATE' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DATE', - 'argumentCount' => '3' - ), - 'DATEDIF' => array( + 'argumentCount' => '3', + ], + 'DATEDIF' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DATEDIF', - 'argumentCount' => '2,3' - ), - 'DATEVALUE' => array( + 'argumentCount' => '2,3', + ], + 'DATEVALUE' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DATEVALUE', - 'argumentCount' => '1' - ), - 'DAVERAGE' => array( + 'argumentCount' => '1', + ], + 'DAVERAGE' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DAVERAGE', - 'argumentCount' => '3' - ), - 'DAY' => array( + 'argumentCount' => '3', + ], + 'DAY' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DAYOFMONTH', - 'argumentCount' => '1' - ), - 'DAYS360' => array( + 'argumentCount' => '1', + ], + 'DAYS360' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DAYS360', - 'argumentCount' => '2,3' - ), - 'DB' => array( + 'argumentCount' => '2,3', + ], + 'DB' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::DB', - 'argumentCount' => '4,5' - ), - 'DCOUNT' => array( + 'argumentCount' => '4,5', + ], + 'DCOUNT' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DCOUNT', - 'argumentCount' => '3' - ), - 'DCOUNTA' => array( + 'argumentCount' => '3', + ], + 'DCOUNTA' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DCOUNTA', - 'argumentCount' => '3' - ), - 'DDB' => array( + 'argumentCount' => '3', + ], + 'DDB' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::DDB', - 'argumentCount' => '4,5' - ), - 'DEC2BIN' => array( + 'argumentCount' => '4,5', + ], + 'DEC2BIN' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::DECTOBIN', - 'argumentCount' => '1,2' - ), - 'DEC2HEX' => array( + 'argumentCount' => '1,2', + ], + 'DEC2HEX' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::DECTOHEX', - 'argumentCount' => '1,2' - ), - 'DEC2OCT' => array( + 'argumentCount' => '1,2', + ], + 'DEC2OCT' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::DECTOOCT', - 'argumentCount' => '1,2' - ), - 'DEGREES' => array( + 'argumentCount' => '1,2', + ], + 'DEGREES' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'rad2deg', - 'argumentCount' => '1' - ), - 'DELTA' => array( + 'argumentCount' => '1', + ], + 'DELTA' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::DELTA', - 'argumentCount' => '1,2' - ), - 'DEVSQ' => array( + 'argumentCount' => '1,2', + ], + 'DEVSQ' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::DEVSQ', - 'argumentCount' => '1+' - ), - 'DGET' => array( + 'argumentCount' => '1+', + ], + 'DGET' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DGET', - 'argumentCount' => '3' - ), - 'DISC' => array( + 'argumentCount' => '3', + ], + 'DISC' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::DISC', - 'argumentCount' => '4,5' - ), - 'DMAX' => array( + 'argumentCount' => '4,5', + ], + 'DMAX' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DMAX', - 'argumentCount' => '3' - ), - 'DMIN' => array( + 'argumentCount' => '3', + ], + 'DMIN' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DMIN', - 'argumentCount' => '3' - ), - 'DOLLAR' => array( + 'argumentCount' => '3', + ], + 'DOLLAR' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::DOLLAR', - 'argumentCount' => '1,2' - ), - 'DOLLARDE' => array( + 'argumentCount' => '1,2', + ], + 'DOLLARDE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::DOLLARDE', - 'argumentCount' => '2' - ), - 'DOLLARFR' => array( + 'argumentCount' => '2', + ], + 'DOLLARFR' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::DOLLARFR', - 'argumentCount' => '2' - ), - 'DPRODUCT' => array( + 'argumentCount' => '2', + ], + 'DPRODUCT' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DPRODUCT', - 'argumentCount' => '3' - ), - 'DSTDEV' => array( + 'argumentCount' => '3', + ], + 'DSTDEV' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DSTDEV', - 'argumentCount' => '3' - ), - 'DSTDEVP' => array( + 'argumentCount' => '3', + ], + 'DSTDEVP' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DSTDEVP', - 'argumentCount' => '3' - ), - 'DSUM' => array( + 'argumentCount' => '3', + ], + 'DSUM' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DSUM', - 'argumentCount' => '3' - ), - 'DURATION' => array( + 'argumentCount' => '3', + ], + 'DURATION' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '5,6' - ), - 'DVAR' => array( + 'argumentCount' => '5,6', + ], + 'DVAR' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DVAR', - 'argumentCount' => '3' - ), - 'DVARP' => array( + 'argumentCount' => '3', + ], + 'DVARP' => [ 'category' => Calculation\Categories::CATEGORY_DATABASE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Database::DVARP', - 'argumentCount' => '3' - ), - 'EDATE' => array( + 'argumentCount' => '3', + ], + 'EDATE' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::EDATE', - 'argumentCount' => '2' - ), - 'EFFECT' => array( + 'argumentCount' => '2', + ], + 'EFFECT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::EFFECT', - 'argumentCount' => '2' - ), - 'EOMONTH' => array( + 'argumentCount' => '2', + ], + 'EOMONTH' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::EOMONTH', - 'argumentCount' => '2' - ), - 'ERF' => array( + 'argumentCount' => '2', + ], + 'ERF' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::ERF', - 'argumentCount' => '1,2' - ), - 'ERFC' => array( + 'argumentCount' => '1,2', + ], + 'ERFC' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::ERFC', - 'argumentCount' => '1' - ), - 'ERROR.TYPE' => array( + 'argumentCount' => '1', + ], + 'ERROR.TYPE' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::errorType', - 'argumentCount' => '1' - ), - 'EVEN' => array( + 'argumentCount' => '1', + ], + 'EVEN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::EVEN', - 'argumentCount' => '1' - ), - 'EXACT' => array( + 'argumentCount' => '1', + ], + 'EXACT' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2' - ), - 'EXP' => array( + 'argumentCount' => '2', + ], + 'EXP' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'exp', - 'argumentCount' => '1' - ), - 'EXPONDIST' => array( + 'argumentCount' => '1', + ], + 'EXPONDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::EXPONDIST', - 'argumentCount' => '3' - ), - 'FACT' => array( + 'argumentCount' => '3', + ], + 'FACT' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::FACT', - 'argumentCount' => '1' - ), - 'FACTDOUBLE' => array( + 'argumentCount' => '1', + ], + 'FACTDOUBLE' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::FACTDOUBLE', - 'argumentCount' => '1' - ), - 'FALSE' => array( + 'argumentCount' => '1', + ], + 'FALSE' => [ 'category' => Calculation\Categories::CATEGORY_LOGICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Logical::FALSE', - 'argumentCount' => '0' - ), - 'FDIST' => array( + 'argumentCount' => '0', + ], + 'FDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '3' - ), - 'FIND' => array( + 'argumentCount' => '3', + ], + 'FIND' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::SEARCHSENSITIVE', - 'argumentCount' => '2,3' - ), - 'FINDB' => array( + 'argumentCount' => '2,3', + ], + 'FINDB' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::SEARCHSENSITIVE', - 'argumentCount' => '2,3' - ), - 'FINV' => array( + 'argumentCount' => '2,3', + ], + 'FINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '3' - ), - 'FISHER' => array( + 'argumentCount' => '3', + ], + 'FISHER' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::FISHER', - 'argumentCount' => '1' - ), - 'FISHERINV' => array( + 'argumentCount' => '1', + ], + 'FISHERINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::FISHERINV', - 'argumentCount' => '1' - ), - 'FIXED' => array( + 'argumentCount' => '1', + ], + 'FIXED' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::FIXEDFORMAT', - 'argumentCount' => '1-3' - ), - 'FLOOR' => array( + 'argumentCount' => '1-3', + ], + 'FLOOR' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::FLOOR', - 'argumentCount' => '2' - ), - 'FORECAST' => array( + 'argumentCount' => '2', + ], + 'FORECAST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::FORECAST', - 'argumentCount' => '3' - ), - 'FREQUENCY' => array( + 'argumentCount' => '3', + ], + 'FREQUENCY' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2' - ), - 'FTEST' => array( + 'argumentCount' => '2', + ], + 'FTEST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2' - ), - 'FV' => array( + 'argumentCount' => '2', + ], + 'FV' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::FV', - 'argumentCount' => '3-5' - ), - 'FVSCHEDULE' => array( + 'argumentCount' => '3-5', + ], + 'FVSCHEDULE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::FVSCHEDULE', - 'argumentCount' => '2' - ), - 'GAMMADIST' => array( + 'argumentCount' => '2', + ], + 'GAMMADIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::GAMMADIST', - 'argumentCount' => '4' - ), - 'GAMMAINV' => array( + 'argumentCount' => '4', + ], + 'GAMMAINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::GAMMAINV', - 'argumentCount' => '3' - ), - 'GAMMALN' => array( + 'argumentCount' => '3', + ], + 'GAMMALN' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::GAMMALN', - 'argumentCount' => '1' - ), - 'GCD' => array( + 'argumentCount' => '1', + ], + 'GCD' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::GCD', - 'argumentCount' => '1+' - ), - 'GEOMEAN' => array( + 'argumentCount' => '1+', + ], + 'GEOMEAN' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::GEOMEAN', - 'argumentCount' => '1+' - ), - 'GESTEP' => array( + 'argumentCount' => '1+', + ], + 'GESTEP' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::GESTEP', - 'argumentCount' => '1,2' - ), - 'GETPIVOTDATA' => array( + 'argumentCount' => '1,2', + ], + 'GETPIVOTDATA' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2+' - ), - 'GROWTH' => array( + 'argumentCount' => '2+', + ], + 'GROWTH' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::GROWTH', - 'argumentCount' => '1-4' - ), - 'HARMEAN' => array( + 'argumentCount' => '1-4', + ], + 'HARMEAN' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::HARMEAN', - 'argumentCount' => '1+' - ), - 'HEX2BIN' => array( + 'argumentCount' => '1+', + ], + 'HEX2BIN' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::HEXTOBIN', - 'argumentCount' => '1,2' - ), - 'HEX2DEC' => array( + 'argumentCount' => '1,2', + ], + 'HEX2DEC' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::HEXTODEC', - 'argumentCount' => '1' - ), - 'HEX2OCT' => array( + 'argumentCount' => '1', + ], + 'HEX2OCT' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::HEXTOOCT', - 'argumentCount' => '1,2' - ), - 'HLOOKUP' => array( + 'argumentCount' => '1,2', + ], + 'HLOOKUP' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::HLOOKUP', - 'argumentCount' => '3,4' - ), - 'HOUR' => array( + 'argumentCount' => '3,4', + ], + 'HOUR' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::HOUROFDAY', - 'argumentCount' => '1' - ), - 'HYPERLINK' => array( + 'argumentCount' => '1', + ], + 'HYPERLINK' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::HYPERLINK', 'argumentCount' => '1,2', - 'passCellReference' => true - ), - 'HYPGEOMDIST' => array( + 'passCellReference' => true, + ], + 'HYPGEOMDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::HYPGEOMDIST', - 'argumentCount' => '4' - ), - 'IF' => array( + 'argumentCount' => '4', + ], + 'IF' => [ 'category' => Calculation\Categories::CATEGORY_LOGICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Logical::statementIf', - 'argumentCount' => '1-3' - ), - 'IFERROR' => array( + 'argumentCount' => '1-3', + ], + 'IFERROR' => [ 'category' => Calculation\Categories::CATEGORY_LOGICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Logical::IFERROR', - 'argumentCount' => '2' - ), - 'IMABS' => array( + 'argumentCount' => '2', + ], + 'IMABS' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMABS', - 'argumentCount' => '1' - ), - 'IMAGINARY' => array( + 'argumentCount' => '1', + ], + 'IMAGINARY' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMAGINARY', - 'argumentCount' => '1' - ), - 'IMARGUMENT' => array( + 'argumentCount' => '1', + ], + 'IMARGUMENT' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMARGUMENT', - 'argumentCount' => '1' - ), - 'IMCONJUGATE' => array( + 'argumentCount' => '1', + ], + 'IMCONJUGATE' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMCONJUGATE', - 'argumentCount' => '1' - ), - 'IMCOS' => array( + 'argumentCount' => '1', + ], + 'IMCOS' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMCOS', - 'argumentCount' => '1' - ), - 'IMDIV' => array( + 'argumentCount' => '1', + ], + 'IMDIV' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMDIV', - 'argumentCount' => '2' - ), - 'IMEXP' => array( + 'argumentCount' => '2', + ], + 'IMEXP' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMEXP', - 'argumentCount' => '1' - ), - 'IMLN' => array( + 'argumentCount' => '1', + ], + 'IMLN' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMLN', - 'argumentCount' => '1' - ), - 'IMLOG10' => array( + 'argumentCount' => '1', + ], + 'IMLOG10' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMLOG10', - 'argumentCount' => '1' - ), - 'IMLOG2' => array( + 'argumentCount' => '1', + ], + 'IMLOG2' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMLOG2', - 'argumentCount' => '1' - ), - 'IMPOWER' => array( + 'argumentCount' => '1', + ], + 'IMPOWER' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMPOWER', - 'argumentCount' => '2' - ), - 'IMPRODUCT' => array( + 'argumentCount' => '2', + ], + 'IMPRODUCT' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMPRODUCT', - 'argumentCount' => '1+' - ), - 'IMREAL' => array( + 'argumentCount' => '1+', + ], + 'IMREAL' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMREAL', - 'argumentCount' => '1' - ), - 'IMSIN' => array( + 'argumentCount' => '1', + ], + 'IMSIN' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMSIN', - 'argumentCount' => '1' - ), - 'IMSQRT' => array( + 'argumentCount' => '1', + ], + 'IMSQRT' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMSQRT', - 'argumentCount' => '1' - ), - 'IMSUB' => array( + 'argumentCount' => '1', + ], + 'IMSUB' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMSUB', - 'argumentCount' => '2' - ), - 'IMSUM' => array( + 'argumentCount' => '2', + ], + 'IMSUM' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::IMSUM', - 'argumentCount' => '1+' - ), - 'INDEX' => array( + 'argumentCount' => '1+', + ], + 'INDEX' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::INDEX', - 'argumentCount' => '1-4' - ), - 'INDIRECT' => array( + 'argumentCount' => '1-4', + ], + 'INDIRECT' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::INDIRECT', 'argumentCount' => '1,2', - 'passCellReference' => true - ), - 'INFO' => array( + 'passCellReference' => true, + ], + 'INFO' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1' - ), - 'INT' => array( + 'argumentCount' => '1', + ], + 'INT' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::INT', - 'argumentCount' => '1' - ), - 'INTERCEPT' => array( + 'argumentCount' => '1', + ], + 'INTERCEPT' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::INTERCEPT', - 'argumentCount' => '2' - ), - 'INTRATE' => array( + 'argumentCount' => '2', + ], + 'INTRATE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::INTRATE', - 'argumentCount' => '4,5' - ), - 'IPMT' => array( + 'argumentCount' => '4,5', + ], + 'IPMT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::IPMT', - 'argumentCount' => '4-6' - ), - 'IRR' => array( + 'argumentCount' => '4-6', + ], + 'IRR' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::IRR', - 'argumentCount' => '1,2' - ), - 'ISBLANK' => array( + 'argumentCount' => '1,2', + ], + 'ISBLANK' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isBlank', - 'argumentCount' => '1' - ), - 'ISERR' => array( + 'argumentCount' => '1', + ], + 'ISERR' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::IS_ERR', - 'argumentCount' => '1' - ), - 'ISERROR' => array( + 'argumentCount' => '1', + ], + 'ISERROR' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::IS_ERROR', - 'argumentCount' => '1' - ), - 'ISEVEN' => array( + 'argumentCount' => '1', + ], + 'ISEVEN' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isEven', - 'argumentCount' => '1' - ), - 'ISLOGICAL' => array( + 'argumentCount' => '1', + ], + 'ISLOGICAL' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isLogical', - 'argumentCount' => '1' - ), - 'ISNA' => array( + 'argumentCount' => '1', + ], + 'ISNA' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isNa', - 'argumentCount' => '1' - ), - 'ISNONTEXT' => array( + 'argumentCount' => '1', + ], + 'ISNONTEXT' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isNonText', - 'argumentCount' => '1' - ), - 'ISNUMBER' => array( + 'argumentCount' => '1', + ], + 'ISNUMBER' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isNumber', - 'argumentCount' => '1' - ), - 'ISODD' => array( + 'argumentCount' => '1', + ], + 'ISODD' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isOdd', - 'argumentCount' => '1' - ), - 'ISPMT' => array( + 'argumentCount' => '1', + ], + 'ISPMT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::ISPMT', - 'argumentCount' => '4' - ), - 'ISREF' => array( + 'argumentCount' => '4', + ], + 'ISREF' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1' - ), - 'ISTEXT' => array( + 'argumentCount' => '1', + ], + 'ISTEXT' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::isText', - 'argumentCount' => '1' - ), - 'JIS' => array( + 'argumentCount' => '1', + ], + 'JIS' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1' - ), - 'KURT' => array( + 'argumentCount' => '1', + ], + 'KURT' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::KURT', - 'argumentCount' => '1+' - ), - 'LARGE' => array( + 'argumentCount' => '1+', + ], + 'LARGE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::LARGE', - 'argumentCount' => '2' - ), - 'LCM' => array( + 'argumentCount' => '2', + ], + 'LCM' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::LCM', - 'argumentCount' => '1+' - ), - 'LEFT' => array( + 'argumentCount' => '1+', + ], + 'LEFT' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::LEFT', - 'argumentCount' => '1,2' - ), - 'LEFTB' => array( + 'argumentCount' => '1,2', + ], + 'LEFTB' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::LEFT', - 'argumentCount' => '1,2' - ), - 'LEN' => array( + 'argumentCount' => '1,2', + ], + 'LEN' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::STRINGLENGTH', - 'argumentCount' => '1' - ), - 'LENB' => array( + 'argumentCount' => '1', + ], + 'LENB' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::STRINGLENGTH', - 'argumentCount' => '1' - ), - 'LINEST' => array( + 'argumentCount' => '1', + ], + 'LINEST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::LINEST', - 'argumentCount' => '1-4' - ), - 'LN' => array( + 'argumentCount' => '1-4', + ], + 'LN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'log', - 'argumentCount' => '1' - ), - 'LOG' => array( + 'argumentCount' => '1', + ], + 'LOG' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::logBase', - 'argumentCount' => '1,2' - ), - 'LOG10' => array( + 'argumentCount' => '1,2', + ], + 'LOG10' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'log10', - 'argumentCount' => '1' - ), - 'LOGEST' => array( + 'argumentCount' => '1', + ], + 'LOGEST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::LOGEST', - 'argumentCount' => '1-4' - ), - 'LOGINV' => array( + 'argumentCount' => '1-4', + ], + 'LOGINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::LOGINV', - 'argumentCount' => '3' - ), - 'LOGNORMDIST' => array( + 'argumentCount' => '3', + ], + 'LOGNORMDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::LOGNORMDIST', - 'argumentCount' => '3' - ), - 'LOOKUP' => array( + 'argumentCount' => '3', + ], + 'LOOKUP' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::LOOKUP', - 'argumentCount' => '2,3' - ), - 'LOWER' => array( + 'argumentCount' => '2,3', + ], + 'LOWER' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::LOWERCASE', - 'argumentCount' => '1' - ), - 'MATCH' => array( + 'argumentCount' => '1', + ], + 'MATCH' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::MATCH', - 'argumentCount' => '2,3' - ), - 'MAX' => array( + 'argumentCount' => '2,3', + ], + 'MAX' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MAX', - 'argumentCount' => '1+' - ), - 'MAXA' => array( + 'argumentCount' => '1+', + ], + 'MAXA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MAXA', - 'argumentCount' => '1+' - ), - 'MAXIF' => array( + 'argumentCount' => '1+', + ], + 'MAXIF' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MAXIF', - 'argumentCount' => '2+' - ), - 'MDETERM' => array( + 'argumentCount' => '2+', + ], + 'MDETERM' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::MDETERM', - 'argumentCount' => '1' - ), - 'MDURATION' => array( + 'argumentCount' => '1', + ], + 'MDURATION' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '5,6' - ), - 'MEDIAN' => array( + 'argumentCount' => '5,6', + ], + 'MEDIAN' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MEDIAN', - 'argumentCount' => '1+' - ), - 'MEDIANIF' => array( + 'argumentCount' => '1+', + ], + 'MEDIANIF' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2+' - ), - 'MID' => array( + 'argumentCount' => '2+', + ], + 'MID' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::MID', - 'argumentCount' => '3' - ), - 'MIDB' => array( + 'argumentCount' => '3', + ], + 'MIDB' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::MID', - 'argumentCount' => '3' - ), - 'MIN' => array( + 'argumentCount' => '3', + ], + 'MIN' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MIN', - 'argumentCount' => '1+' - ), - 'MINA' => array( + 'argumentCount' => '1+', + ], + 'MINA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MINA', - 'argumentCount' => '1+' - ), - 'MINIF' => array( + 'argumentCount' => '1+', + ], + 'MINIF' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MINIF', - 'argumentCount' => '2+' - ), - 'MINUTE' => array( + 'argumentCount' => '2+', + ], + 'MINUTE' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::MINUTEOFHOUR', - 'argumentCount' => '1' - ), - 'MINVERSE' => array( + 'argumentCount' => '1', + ], + 'MINVERSE' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::MINVERSE', - 'argumentCount' => '1' - ), - 'MIRR' => array( + 'argumentCount' => '1', + ], + 'MIRR' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::MIRR', - 'argumentCount' => '3' - ), - 'MMULT' => array( + 'argumentCount' => '3', + ], + 'MMULT' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::MMULT', - 'argumentCount' => '2' - ), - 'MOD' => array( + 'argumentCount' => '2', + ], + 'MOD' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::MOD', - 'argumentCount' => '2' - ), - 'MODE' => array( + 'argumentCount' => '2', + ], + 'MODE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::MODE', - 'argumentCount' => '1+' - ), - 'MONTH' => array( + 'argumentCount' => '1+', + ], + 'MONTH' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::MONTHOFYEAR', - 'argumentCount' => '1' - ), - 'MROUND' => array( + 'argumentCount' => '1', + ], + 'MROUND' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::MROUND', - 'argumentCount' => '2' - ), - 'MULTINOMIAL' => array( + 'argumentCount' => '2', + ], + 'MULTINOMIAL' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::MULTINOMIAL', - 'argumentCount' => '1+' - ), - 'N' => array( + 'argumentCount' => '1+', + ], + 'N' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::N', - 'argumentCount' => '1' - ), - 'NA' => array( + 'argumentCount' => '1', + ], + 'NA' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::NA', - 'argumentCount' => '0' - ), - 'NEGBINOMDIST' => array( + 'argumentCount' => '0', + ], + 'NEGBINOMDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::NEGBINOMDIST', - 'argumentCount' => '3' - ), - 'NETWORKDAYS' => array( + 'argumentCount' => '3', + ], + 'NETWORKDAYS' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::NETWORKDAYS', - 'argumentCount' => '2+' - ), - 'NOMINAL' => array( + 'argumentCount' => '2+', + ], + 'NOMINAL' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::NOMINAL', - 'argumentCount' => '2' - ), - 'NORMDIST' => array( + 'argumentCount' => '2', + ], + 'NORMDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::NORMDIST', - 'argumentCount' => '4' - ), - 'NORMINV' => array( + 'argumentCount' => '4', + ], + 'NORMINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::NORMINV', - 'argumentCount' => '3' - ), - 'NORMSDIST' => array( + 'argumentCount' => '3', + ], + 'NORMSDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::NORMSDIST', - 'argumentCount' => '1' - ), - 'NORMSINV' => array( + 'argumentCount' => '1', + ], + 'NORMSINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::NORMSINV', - 'argumentCount' => '1' - ), - 'NOT' => array( + 'argumentCount' => '1', + ], + 'NOT' => [ 'category' => Calculation\Categories::CATEGORY_LOGICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Logical::NOT', - 'argumentCount' => '1' - ), - 'NOW' => array( + 'argumentCount' => '1', + ], + 'NOW' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DATETIMENOW', - 'argumentCount' => '0' - ), - 'NPER' => array( + 'argumentCount' => '0', + ], + 'NPER' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::NPER', - 'argumentCount' => '3-5' - ), - 'NPV' => array( + 'argumentCount' => '3-5', + ], + 'NPV' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::NPV', - 'argumentCount' => '2+' - ), - 'OCT2BIN' => array( + 'argumentCount' => '2+', + ], + 'OCT2BIN' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::OCTTOBIN', - 'argumentCount' => '1,2' - ), - 'OCT2DEC' => array( + 'argumentCount' => '1,2', + ], + 'OCT2DEC' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::OCTTODEC', - 'argumentCount' => '1' - ), - 'OCT2HEX' => array( + 'argumentCount' => '1', + ], + 'OCT2HEX' => [ 'category' => Calculation\Categories::CATEGORY_ENGINEERING, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Engineering::OCTTOHEX', - 'argumentCount' => '1,2' - ), - 'ODD' => array( + 'argumentCount' => '1,2', + ], + 'ODD' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::ODD', - 'argumentCount' => '1' - ), - 'ODDFPRICE' => array( + 'argumentCount' => '1', + ], + 'ODDFPRICE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '8,9' - ), - 'ODDFYIELD' => array( + 'argumentCount' => '8,9', + ], + 'ODDFYIELD' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '8,9' - ), - 'ODDLPRICE' => array( + 'argumentCount' => '8,9', + ], + 'ODDLPRICE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '7,8' - ), - 'ODDLYIELD' => array( + 'argumentCount' => '7,8', + ], + 'ODDLYIELD' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '7,8' - ), - 'OFFSET' => array( + 'argumentCount' => '7,8', + ], + 'OFFSET' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::OFFSET', 'argumentCount' => '3-5', 'passCellReference' => true, - 'passByReference' => array(true) - ), - 'OR' => array( + 'passByReference' => [true], + ], + 'OR' => [ 'category' => Calculation\Categories::CATEGORY_LOGICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Logical::logicalOr', - 'argumentCount' => '1+' - ), - 'PEARSON' => array( + 'argumentCount' => '1+', + ], + 'PEARSON' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::CORREL', - 'argumentCount' => '2' - ), - 'PERCENTILE' => array( + 'argumentCount' => '2', + ], + 'PERCENTILE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::PERCENTILE', - 'argumentCount' => '2' - ), - 'PERCENTRANK' => array( + 'argumentCount' => '2', + ], + 'PERCENTRANK' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::PERCENTRANK', - 'argumentCount' => '2,3' - ), - 'PERMUT' => array( + 'argumentCount' => '2,3', + ], + 'PERMUT' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::PERMUT', - 'argumentCount' => '2' - ), - 'PHONETIC' => array( + 'argumentCount' => '2', + ], + 'PHONETIC' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1' - ), - 'PI' => array( + 'argumentCount' => '1', + ], + 'PI' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'pi', - 'argumentCount' => '0' - ), - 'PMT' => array( + 'argumentCount' => '0', + ], + 'PMT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::PMT', - 'argumentCount' => '3-5' - ), - 'POISSON' => array( + 'argumentCount' => '3-5', + ], + 'POISSON' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::POISSON', - 'argumentCount' => '3' - ), - 'POWER' => array( + 'argumentCount' => '3', + ], + 'POWER' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::POWER', - 'argumentCount' => '2' - ), - 'PPMT' => array( + 'argumentCount' => '2', + ], + 'PPMT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::PPMT', - 'argumentCount' => '4-6' - ), - 'PRICE' => array( + 'argumentCount' => '4-6', + ], + 'PRICE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::PRICE', - 'argumentCount' => '6,7' - ), - 'PRICEDISC' => array( + 'argumentCount' => '6,7', + ], + 'PRICEDISC' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::PRICEDISC', - 'argumentCount' => '4,5' - ), - 'PRICEMAT' => array( + 'argumentCount' => '4,5', + ], + 'PRICEMAT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::PRICEMAT', - 'argumentCount' => '5,6' - ), - 'PROB' => array( + 'argumentCount' => '5,6', + ], + 'PROB' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '3,4' - ), - 'PRODUCT' => array( + 'argumentCount' => '3,4', + ], + 'PRODUCT' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::PRODUCT', - 'argumentCount' => '1+' - ), - 'PROPER' => array( + 'argumentCount' => '1+', + ], + 'PROPER' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::PROPERCASE', - 'argumentCount' => '1' - ), - 'PV' => array( + 'argumentCount' => '1', + ], + 'PV' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::PV', - 'argumentCount' => '3-5' - ), - 'QUARTILE' => array( + 'argumentCount' => '3-5', + ], + 'QUARTILE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::QUARTILE', - 'argumentCount' => '2' - ), - 'QUOTIENT' => array( + 'argumentCount' => '2', + ], + 'QUOTIENT' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::QUOTIENT', - 'argumentCount' => '2' - ), - 'RADIANS' => array( + 'argumentCount' => '2', + ], + 'RADIANS' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'deg2rad', - 'argumentCount' => '1' - ), - 'RAND' => array( + 'argumentCount' => '1', + ], + 'RAND' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::RAND', - 'argumentCount' => '0' - ), - 'RANDBETWEEN' => array( + 'argumentCount' => '0', + ], + 'RANDBETWEEN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::RAND', - 'argumentCount' => '2' - ), - 'RANK' => array( + 'argumentCount' => '2', + ], + 'RANK' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::RANK', - 'argumentCount' => '2,3' - ), - 'RATE' => array( + 'argumentCount' => '2,3', + ], + 'RATE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::RATE', - 'argumentCount' => '3-6' - ), - 'RECEIVED' => array( + 'argumentCount' => '3-6', + ], + 'RECEIVED' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::RECEIVED', - 'argumentCount' => '4-5' - ), - 'REPLACE' => array( + 'argumentCount' => '4-5', + ], + 'REPLACE' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::REPLACE', - 'argumentCount' => '4' - ), - 'REPLACEB' => array( + 'argumentCount' => '4', + ], + 'REPLACEB' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::REPLACE', - 'argumentCount' => '4' - ), - 'REPT' => array( + 'argumentCount' => '4', + ], + 'REPT' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => 'str_repeat', - 'argumentCount' => '2' - ), - 'RIGHT' => array( + 'argumentCount' => '2', + ], + 'RIGHT' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::RIGHT', - 'argumentCount' => '1,2' - ), - 'RIGHTB' => array( + 'argumentCount' => '1,2', + ], + 'RIGHTB' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::RIGHT', - 'argumentCount' => '1,2' - ), - 'ROMAN' => array( + 'argumentCount' => '1,2', + ], + 'ROMAN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::ROMAN', - 'argumentCount' => '1,2' - ), - 'ROUND' => array( + 'argumentCount' => '1,2', + ], + 'ROUND' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'round', - 'argumentCount' => '2' - ), - 'ROUNDDOWN' => array( + 'argumentCount' => '2', + ], + 'ROUNDDOWN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::ROUNDDOWN', - 'argumentCount' => '2' - ), - 'ROUNDUP' => array( + 'argumentCount' => '2', + ], + 'ROUNDUP' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::ROUNDUP', - 'argumentCount' => '2' - ), - 'ROW' => array( + 'argumentCount' => '2', + ], + 'ROW' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::ROW', 'argumentCount' => '-1', - 'passByReference' => array(true) - ), - 'ROWS' => array( + 'passByReference' => [true], + ], + 'ROWS' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::ROWS', - 'argumentCount' => '1' - ), - 'RSQ' => array( + 'argumentCount' => '1', + ], + 'RSQ' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::RSQ', - 'argumentCount' => '2' - ), - 'RTD' => array( + 'argumentCount' => '2', + ], + 'RTD' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '1+' - ), - 'SEARCH' => array( + 'argumentCount' => '1+', + ], + 'SEARCH' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::SEARCHINSENSITIVE', - 'argumentCount' => '2,3' - ), - 'SEARCHB' => array( + 'argumentCount' => '2,3', + ], + 'SEARCHB' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::SEARCHINSENSITIVE', - 'argumentCount' => '2,3' - ), - 'SECOND' => array( + 'argumentCount' => '2,3', + ], + 'SECOND' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::SECONDOFMINUTE', - 'argumentCount' => '1' - ), - 'SERIESSUM' => array( + 'argumentCount' => '1', + ], + 'SERIESSUM' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SERIESSUM', - 'argumentCount' => '4' - ), - 'SIGN' => array( + 'argumentCount' => '4', + ], + 'SIGN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SIGN', - 'argumentCount' => '1' - ), - 'SIN' => array( + 'argumentCount' => '1', + ], + 'SIN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'sin', - 'argumentCount' => '1' - ), - 'SINH' => array( + 'argumentCount' => '1', + ], + 'SINH' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'sinh', - 'argumentCount' => '1' - ), - 'SKEW' => array( + 'argumentCount' => '1', + ], + 'SKEW' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::SKEW', - 'argumentCount' => '1+' - ), - 'SLN' => array( + 'argumentCount' => '1+', + ], + 'SLN' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::SLN', - 'argumentCount' => '3' - ), - 'SLOPE' => array( + 'argumentCount' => '3', + ], + 'SLOPE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::SLOPE', - 'argumentCount' => '2' - ), - 'SMALL' => array( + 'argumentCount' => '2', + ], + 'SMALL' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::SMALL', - 'argumentCount' => '2' - ), - 'SQRT' => array( + 'argumentCount' => '2', + ], + 'SQRT' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'sqrt', - 'argumentCount' => '1' - ), - 'SQRTPI' => array( + 'argumentCount' => '1', + ], + 'SQRTPI' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SQRTPI', - 'argumentCount' => '1' - ), - 'STANDARDIZE' => array( + 'argumentCount' => '1', + ], + 'STANDARDIZE' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::STANDARDIZE', - 'argumentCount' => '3' - ), - 'STDEV' => array( + 'argumentCount' => '3', + ], + 'STDEV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::STDEV', - 'argumentCount' => '1+' - ), - 'STDEVA' => array( + 'argumentCount' => '1+', + ], + 'STDEVA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::STDEVA', - 'argumentCount' => '1+' - ), - 'STDEVP' => array( + 'argumentCount' => '1+', + ], + 'STDEVP' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::STDEVP', - 'argumentCount' => '1+' - ), - 'STDEVPA' => array( + 'argumentCount' => '1+', + ], + 'STDEVPA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::STDEVPA', - 'argumentCount' => '1+' - ), - 'STEYX' => array( + 'argumentCount' => '1+', + ], + 'STEYX' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::STEYX', - 'argumentCount' => '2' - ), - 'SUBSTITUTE' => array( + 'argumentCount' => '2', + ], + 'SUBSTITUTE' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::SUBSTITUTE', - 'argumentCount' => '3,4' - ), - 'SUBTOTAL' => array( + 'argumentCount' => '3,4', + ], + 'SUBTOTAL' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUBTOTAL', - 'argumentCount' => '2+' - ), - 'SUM' => array( + 'argumentCount' => '2+', + ], + 'SUM' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUM', - 'argumentCount' => '1+' - ), - 'SUMIF' => array( + 'argumentCount' => '1+', + ], + 'SUMIF' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUMIF', - 'argumentCount' => '2,3' - ), - 'SUMIFS' => array( + 'argumentCount' => '2,3', + ], + 'SUMIFS' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUMIFS', - 'argumentCount' => '3+' - ), - 'SUMPRODUCT' => array( + 'argumentCount' => '3+', + ], + 'SUMPRODUCT' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUMPRODUCT', - 'argumentCount' => '1+' - ), - 'SUMSQ' => array( + 'argumentCount' => '1+', + ], + 'SUMSQ' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUMSQ', - 'argumentCount' => '1+' - ), - 'SUMX2MY2' => array( + 'argumentCount' => '1+', + ], + 'SUMX2MY2' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUMX2MY2', - 'argumentCount' => '2' - ), - 'SUMX2PY2' => array( + 'argumentCount' => '2', + ], + 'SUMX2PY2' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUMX2PY2', - 'argumentCount' => '2' - ), - 'SUMXMY2' => array( + 'argumentCount' => '2', + ], + 'SUMXMY2' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::SUMXMY2', - 'argumentCount' => '2' - ), - 'SYD' => array( + 'argumentCount' => '2', + ], + 'SYD' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::SYD', - 'argumentCount' => '4' - ), - 'T' => array( + 'argumentCount' => '4', + ], + 'T' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::RETURNSTRING', - 'argumentCount' => '1' - ), - 'TAN' => array( + 'argumentCount' => '1', + ], + 'TAN' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'tan', - 'argumentCount' => '1' - ), - 'TANH' => array( + 'argumentCount' => '1', + ], + 'TANH' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'tanh', - 'argumentCount' => '1' - ), - 'TBILLEQ' => array( + 'argumentCount' => '1', + ], + 'TBILLEQ' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::TBILLEQ', - 'argumentCount' => '3' - ), - 'TBILLPRICE' => array( + 'argumentCount' => '3', + ], + 'TBILLPRICE' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::TBILLPRICE', - 'argumentCount' => '3' - ), - 'TBILLYIELD' => array( + 'argumentCount' => '3', + ], + 'TBILLYIELD' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::TBILLYIELD', - 'argumentCount' => '3' - ), - 'TDIST' => array( + 'argumentCount' => '3', + ], + 'TDIST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::TDIST', - 'argumentCount' => '3' - ), - 'TEXT' => array( + 'argumentCount' => '3', + ], + 'TEXT' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::TEXTFORMAT', - 'argumentCount' => '2' - ), - 'TIME' => array( + 'argumentCount' => '2', + ], + 'TIME' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::TIME', - 'argumentCount' => '3' - ), - 'TIMEVALUE' => array( + 'argumentCount' => '3', + ], + 'TIMEVALUE' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::TIMEVALUE', - 'argumentCount' => '1' - ), - 'TINV' => array( + 'argumentCount' => '1', + ], + 'TINV' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::TINV', - 'argumentCount' => '2' - ), - 'TODAY' => array( + 'argumentCount' => '2', + ], + 'TODAY' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DATENOW', - 'argumentCount' => '0' - ), - 'TRANSPOSE' => array( + 'argumentCount' => '0', + ], + 'TRANSPOSE' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::TRANSPOSE', - 'argumentCount' => '1' - ), - 'TREND' => array( + 'argumentCount' => '1', + ], + 'TREND' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::TREND', - 'argumentCount' => '1-4' - ), - 'TRIM' => array( + 'argumentCount' => '1-4', + ], + 'TRIM' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::TRIMSPACES', - 'argumentCount' => '1' - ), - 'TRIMMEAN' => array( + 'argumentCount' => '1', + ], + 'TRIMMEAN' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::TRIMMEAN', - 'argumentCount' => '2' - ), - 'TRUE' => array( + 'argumentCount' => '2', + ], + 'TRUE' => [ 'category' => Calculation\Categories::CATEGORY_LOGICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Logical::TRUE', - 'argumentCount' => '0' - ), - 'TRUNC' => array( + 'argumentCount' => '0', + ], + 'TRUNC' => [ 'category' => Calculation\Categories::CATEGORY_MATH_AND_TRIG, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\MathTrig::TRUNC', - 'argumentCount' => '1,2' - ), - 'TTEST' => array( + 'argumentCount' => '1,2', + ], + 'TTEST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '4' - ), - 'TYPE' => array( + 'argumentCount' => '4', + ], + 'TYPE' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::TYPE', - 'argumentCount' => '1' - ), - 'UPPER' => array( + 'argumentCount' => '1', + ], + 'UPPER' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::UPPERCASE', - 'argumentCount' => '1' - ), - 'USDOLLAR' => array( + 'argumentCount' => '1', + ], + 'USDOLLAR' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '2' - ), - 'VALUE' => array( + 'argumentCount' => '2', + ], + 'VALUE' => [ 'category' => Calculation\Categories::CATEGORY_TEXT_AND_DATA, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\TextData::VALUE', - 'argumentCount' => '1' - ), - 'VAR' => array( + 'argumentCount' => '1', + ], + 'VAR' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::VARFunc', - 'argumentCount' => '1+' - ), - 'VARA' => array( + 'argumentCount' => '1+', + ], + 'VARA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::VARA', - 'argumentCount' => '1+' - ), - 'VARP' => array( + 'argumentCount' => '1+', + ], + 'VARP' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::VARP', - 'argumentCount' => '1+' - ), - 'VARPA' => array( + 'argumentCount' => '1+', + ], + 'VARPA' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::VARPA', - 'argumentCount' => '1+' - ), - 'VDB' => array( + 'argumentCount' => '1+', + ], + 'VDB' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '5-7' - ), - 'VERSION' => array( + 'argumentCount' => '5-7', + ], + 'VERSION' => [ 'category' => Calculation\Categories::CATEGORY_INFORMATION, 'functionCall' => 'Calculation\Categories::VERSION', - 'argumentCount' => '0' - ), - 'VLOOKUP' => array( + 'argumentCount' => '0', + ], + 'VLOOKUP' => [ 'category' => Calculation\Categories::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\LookupRef::VLOOKUP', - 'argumentCount' => '3,4' - ), - 'WEEKDAY' => array( + 'argumentCount' => '3,4', + ], + 'WEEKDAY' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::DAYOFWEEK', - 'argumentCount' => '1,2' - ), - 'WEEKNUM' => array( + 'argumentCount' => '1,2', + ], + 'WEEKNUM' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::WEEKOFYEAR', - 'argumentCount' => '1,2' - ), - 'WEIBULL' => array( + 'argumentCount' => '1,2', + ], + 'WEIBULL' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::WEIBULL', - 'argumentCount' => '4' - ), - 'WORKDAY' => array( + 'argumentCount' => '4', + ], + 'WORKDAY' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::WORKDAY', - 'argumentCount' => '2+' - ), - 'XIRR' => array( + 'argumentCount' => '2+', + ], + 'XIRR' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::XIRR', - 'argumentCount' => '2,3' - ), - 'XNPV' => array( + 'argumentCount' => '2,3', + ], + 'XNPV' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::XNPV', - 'argumentCount' => '3' - ), - 'YEAR' => array( + 'argumentCount' => '3', + ], + 'YEAR' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::YEAR', - 'argumentCount' => '1' - ), - 'YEARFRAC' => array( + 'argumentCount' => '1', + ], + 'YEARFRAC' => [ 'category' => Calculation\Categories::CATEGORY_DATE_AND_TIME, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\DateTime::YEARFRAC', - 'argumentCount' => '2,3' - ), - 'YIELD' => array( + 'argumentCount' => '2,3', + ], + 'YIELD' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => 'Calculation\Categories::DUMMY', - 'argumentCount' => '6,7' - ), - 'YIELDDISC' => array( + 'argumentCount' => '6,7', + ], + 'YIELDDISC' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::YIELDDISC', - 'argumentCount' => '4,5' - ), - 'YIELDMAT' => array( + 'argumentCount' => '4,5', + ], + 'YIELDMAT' => [ 'category' => Calculation\Categories::CATEGORY_FINANCIAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Financial::YIELDMAT', - 'argumentCount' => '5,6' - ), - 'ZTEST' => array( + 'argumentCount' => '5,6', + ], + 'ZTEST' => [ 'category' => Calculation\Categories::CATEGORY_STATISTICAL, 'functionCall' => '\\PhpSpreadsheet\\Calculation\\Statistical::ZTEST', - 'argumentCount' => '2-3' - ) - ); + 'argumentCount' => '2-3', + ], + ]; // Internal functions used for special control purposes - private static $controlFunctions = array( - 'MKMATRIX' => array( + private static $controlFunctions = [ + 'MKMATRIX' => [ 'argumentCount' => '*', - 'functionCall' => 'self::mkMatrix' - ) - ); - + 'functionCall' => 'self::mkMatrix', + ], + ]; public function __construct(Spreadsheet $spreadsheet = null) { @@ -2069,12 +2039,11 @@ class Calculation $this->_debugLog = new CalcEngine\Logger($this->cyclicReferenceStack); } - private static function loadLocales() { - $localeFileDirectory = PHPSPREADSHEET_ROOT.'PhpSpreadsheet/locale/'; - foreach (glob($localeFileDirectory.'/*', GLOB_ONLYDIR) as $filename) { - $filename = substr($filename, strlen($localeFileDirectory)+1); + $localeFileDirectory = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet/locale/'; + foreach (glob($localeFileDirectory . '/*', GLOB_ONLYDIR) as $filename) { + $filename = substr($filename, strlen($localeFileDirectory) + 1); if ($filename != 'en') { self::$validLocaleLanguages[] = $filename; } @@ -2084,7 +2053,6 @@ class Calculation /** * Get an instance of this class * - * @access public * @param Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, * or NULL to create a standalone claculation engine * @return Calculation @@ -2108,7 +2076,6 @@ class Calculation /** * Unset an instance of this class * - * @access public * @param Spreadsheet $spreadsheet Injected spreadsheet identifying the instance to unset */ public function __destruct() @@ -2119,20 +2086,15 @@ class Calculation /** * Flush the calculation cache for any existing instance of this class * but only if a \PhpSpreadsheet\Calculation instance exists - * - * @access public - * @return null */ public function flushInstance() { $this->clearCalculationCache(); } - /** * Get the debuglog for this claculation engine instance * - * @access public * @return CalcEngine\Logger */ public function getDebugLog() @@ -2143,7 +2105,6 @@ class Calculation /** * __clone implementation. Cloning should not be allowed in a Singleton! * - * @access public * @throws Calculation\Exception */ final public function __clone() @@ -2151,11 +2112,9 @@ class Calculation throw new Calculation\Exception('Cloning the calculation engine is not allowed!'); } - /** * Return the locale-specific translation of TRUE * - * @access public * @return string locale-specific translation of TRUE */ public static function getTRUE() @@ -2166,7 +2125,6 @@ class Calculation /** * Return the locale-specific translation of FALSE * - * @access public * @return string locale-specific translation of FALSE */ public static function getFALSE() @@ -2177,9 +2135,8 @@ class Calculation /** * Set the Array Return Type (Array or Value of first element in the array) * - * @access public * @param string $returnType Array return type - * @return boolean Success or failure + * @return bool Success or failure */ public static function setArrayReturnType($returnType) { @@ -2187,16 +2144,16 @@ class Calculation ($returnType == self::RETURN_ARRAY_AS_ERROR) || ($returnType == self::RETURN_ARRAY_AS_ARRAY)) { self::$returnArrayAsType = $returnType; + return true; } + return false; } - /** * Return the Array Return Type (Array or Value of first element in the array) * - * @access public * @return string $returnType Array return type */ public static function getArrayReturnType() @@ -2204,12 +2161,10 @@ class Calculation return self::$returnArrayAsType; } - /** * Is calculation caching enabled? * - * @access public - * @return boolean + * @return bool */ public function getCalculationCacheEnabled() { @@ -2219,8 +2174,7 @@ class Calculation /** * Enable/disable calculation cache * - * @access public - * @param boolean $pValue + * @param bool $pValue */ public function setCalculationCacheEnabled($pValue = true) { @@ -2228,7 +2182,6 @@ class Calculation $this->clearCalculationCache(); } - /** * Enable calculation cache */ @@ -2237,7 +2190,6 @@ class Calculation $this->setCalculationCacheEnabled(true); } - /** * Disable calculation cache */ @@ -2246,13 +2198,12 @@ class Calculation $this->setCalculationCacheEnabled(false); } - /** * Clear calculation cache */ public function clearCalculationCache() { - $this->calculationCache = array(); + $this->calculationCache = []; } /** @@ -2281,7 +2232,6 @@ class Calculation } } - /** * Get the currently defined locale code * @@ -2292,12 +2242,11 @@ class Calculation return self::$localeLanguage; } - /** * Set the locale code * * @param string $locale The locale to use for formula translation - * @return boolean + * @return bool */ public function setLocale($locale = 'en_us') { @@ -2313,16 +2262,16 @@ class Calculation // Test whether we have any language data for this language (any locale) if (in_array($language, self::$validLocaleLanguages)) { // initialise language/locale settings - self::$localeFunctions = array(); + self::$localeFunctions = []; self::$localeArgumentSeparator = ','; - self::$localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'); + self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL']; // Default is English, if user isn't requesting english, then read the necessary data from the locale files if ($locale != 'en_us') { // Search for a file with a list of function names for locale - $functionNamesFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $locale).DIRECTORY_SEPARATOR.'functions'; + $functionNamesFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet' . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'functions'; if (!file_exists($functionNamesFile)) { // If there isn't a locale specific function file, look for a language specific function file - $functionNamesFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions'; + $functionNamesFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet' . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . 'functions'; if (!file_exists($functionNamesFile)) { return false; } @@ -2348,9 +2297,9 @@ class Calculation self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } - $configFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $locale).DIRECTORY_SEPARATOR.'config'; + $configFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet' . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'config'; if (!file_exists($configFile)) { - $configFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config'; + $configFile = PHPSPREADSHEET_ROOT . 'PhpSpreadsheet' . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . 'config'; } if (file_exists($configFile)) { $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); @@ -2372,13 +2321,13 @@ class Calculation self::$functionReplaceFromExcel = self::$functionReplaceToExcel = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null; self::$localeLanguage = $locale; + return true; } + return false; } - - public static function translateSeparator($fromSeparator, $toSeparator, $formula, &$inBraces) { $strlen = mb_strlen($formula); @@ -2393,10 +2342,11 @@ class Calculation break; case $fromSeparator: if (!$inBraces) { - $formula = mb_substr($formula, 0, $i).$toSeparator.mb_substr($formula, $i+1); + $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1); } } } + return $formula; } @@ -2432,63 +2382,61 @@ class Calculation } private static $functionReplaceFromExcel = null; - private static $functionReplaceToLocale = null; + private static $functionReplaceToLocale = null; public function _translateFormulaToLocale($formula) { if (self::$functionReplaceFromExcel === null) { - self::$functionReplaceFromExcel = array(); + self::$functionReplaceFromExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { - self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui'; + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName) . '([\s]*\()/Ui'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { - self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean) . '([^\w\.])/Ui'; } } if (self::$functionReplaceToLocale === null) { - self::$functionReplaceToLocale = array(); + self::$functionReplaceToLocale = []; foreach (array_values(self::$localeFunctions) as $localeFunctionName) { - self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2'; + self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2'; } foreach (array_values(self::$localeBoolean) as $localeBoolean) { - self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2'; + self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2'; } } return self::translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator); } - private static $functionReplaceFromLocale = null; - private static $functionReplaceToExcel = null; + private static $functionReplaceToExcel = null; public function _translateFormulaToEnglish($formula) { if (self::$functionReplaceFromLocale === null) { - self::$functionReplaceFromLocale = array(); + self::$functionReplaceFromLocale = []; foreach (array_values(self::$localeFunctions) as $localeFunctionName) { - self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui'; + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName) . '([\s]*\()/Ui'; } foreach (array_values(self::$localeBoolean) as $excelBoolean) { - self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean) . '([^\w\.])/Ui'; } } if (self::$functionReplaceToExcel === null) { - self::$functionReplaceToExcel = array(); + self::$functionReplaceToExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { - self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2'; + self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { - self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2'; + self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2'; } } return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ','); } - public static function localeFunc($function) { if (self::$localeLanguage !== 'en_us') { @@ -2501,12 +2449,10 @@ class Calculation } } } + return $function; } - - - /** * Wrap string values in quotes * @@ -2517,12 +2463,12 @@ class Calculation { if (is_string($value)) { // Error values cannot be "wrapped" - if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) { + if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) { // Return Excel errors "as is" return $value; } // Return strings wrapped in quotes - return '"'.$value.'"'; + return '"' . $value . '"'; // Convert numeric errors to NaN error } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { return Calculation\Functions::NAN(); @@ -2531,7 +2477,6 @@ class Calculation return $value; } - /** * Remove quotes used as a wrapper to identify string values * @@ -2548,20 +2493,17 @@ class Calculation } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { return Calculation\Functions::NAN(); } + return $value; } - - - /** * Calculate cell value (using formula from a cell ID) * Retained for backward compatibility * - * @access public * @param Cell $pCell Cell to calculate - * @return mixed * @throws Calculation\Exception + * @return mixed */ public function calculate(Cell $pCell = null) { @@ -2572,15 +2514,13 @@ class Calculation } } - /** * Calculate the value of a cell formula * - * @access public * @param Cell $pCell Cell to calculate - * @param Boolean $resetLog Flag indicating whether the debug log should be reset or not - * @return mixed + * @param bool $resetLog Flag indicating whether the debug log should be reset or not * @throws Calculation\Exception + * @return mixed */ public function calculateCellValue(Cell $pCell = null, $resetLog = true) { @@ -2600,10 +2540,10 @@ class Calculation } // Execute the calculation for the cell formula - $this->cellStack[] = array( + $this->cellStack[] = [ 'sheet' => $pCell->getWorksheet()->getTitle(), 'cell' => $pCell->getCoordinate(), - ); + ]; try { $result = self::unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell)); $cellAddress = array_pop($this->cellStack); @@ -2640,22 +2580,21 @@ class Calculation } self::$returnArrayAsType = $returnArrayAsType; - if ($result === null) { return 0; } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { return Calculation\Functions::NAN(); } + return $result; } - /** * Validate and parse a formula string * * @param string $formula Formula to parse - * @return array * @throws Calculation\Exception + * @return array */ public function parseFormula($formula) { @@ -2663,26 +2602,25 @@ class Calculation // We return an empty array if not $formula = trim($formula); if ((!isset($formula{0})) || ($formula{0} != '=')) { - return array(); + return []; } $formula = ltrim(substr($formula, 1)); if (!isset($formula{0})) { - return array(); + return []; } // Parse the formula and return the token stack return $this->_parseFormula($formula); } - /** * Calculate the value of a formula * * @param string $formula Formula to parse * @param string $cellID Address of the cell to calculate * @param Cell $pCell Cell to calculate - * @return mixed * @throws Calculation\Exception + * @return mixed */ public function calculateFormula($formula, $cellID = null, Cell $pCell = null) { @@ -2716,7 +2654,6 @@ class Calculation return $result; } - public function getValueFromCache($cellReference, &$cellValue) { // Is calculation cacheing enabled? @@ -2726,8 +2663,10 @@ class Calculation $this->_debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache'); // Return the cached result $cellValue = $this->calculationCache[$cellReference]; + return true; } + return false; } @@ -2744,8 +2683,8 @@ class Calculation * @param string $formula The formula to parse and calculate * @param string $cellID The ID (e.g. A3) of the cell that we are calculating * @param Cell $pCell Cell to calculate - * @return mixed * @throws Calculation\Exception + * @return mixed */ public function _calculateFormulaValue($formula, $cellID = null, Cell $pCell = null) { @@ -2773,11 +2712,13 @@ class Calculation if (($wsTitle{0} !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { $this->cyclicFormulaCell = ''; + return $this->raiseFormulaError('Cyclic Reference in Formula'); } elseif ($this->cyclicFormulaCell === $wsCellReference) { ++$this->cyclicFormulaCounter; if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { $this->cyclicFormulaCell = ''; + return $cellValue; } } elseif ($this->cyclicFormulaCell == '') { @@ -2802,13 +2743,12 @@ class Calculation return $cellValue; } - /** * Ensure that paired matrix operands are both matrices and of the same size * * @param mixed &$operand1 First matrix operand * @param mixed &$operand2 Second matrix operand - * @param integer $resize Flag indicating whether the matrices should be resized to match + * @param int $resize Flag indicating whether the matrices should be resized to match * and (if so), whether the smaller dimension should grow or the * larger should shrink. * 0 = no resize @@ -2842,9 +2782,9 @@ class Calculation // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } - return array( $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); - } + return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns]; + } /** * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0 @@ -2859,25 +2799,25 @@ class Calculation foreach ($matrix as $rowKey => $rowValue) { $matrixColumns = max(count($rowValue), $matrixColumns); if (!is_array($rowValue)) { - $matrix[$rowKey] = array($rowValue); + $matrix[$rowKey] = [$rowValue]; } else { $matrix[$rowKey] = array_values($rowValue); } } $matrix = array_values($matrix); - return array($matrixRows, $matrixColumns); - } + return [$matrixRows, $matrixColumns]; + } /** * Ensure that paired matrix operands are both matrices of the same size * * @param mixed &$matrix1 First matrix operand * @param mixed &$matrix2 Second matrix operand - * @param integer $matrix1Rows Row size of first matrix operand - * @param integer $matrix1Columns Column size of first matrix operand - * @param integer $matrix2Rows Row size of second matrix operand - * @param integer $matrix2Columns Column size of second matrix operand + * @param int $matrix1Rows Row size of first matrix operand + * @param int $matrix1Columns Column size of first matrix operand + * @param int $matrix2Rows Row size of second matrix operand + * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesShrink(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns) { @@ -2912,30 +2852,29 @@ class Calculation } } - /** * Ensure that paired matrix operands are both matrices of the same size * * @param mixed &$matrix1 First matrix operand * @param mixed &$matrix2 Second matrix operand - * @param integer $matrix1Rows Row size of first matrix operand - * @param integer $matrix1Columns Column size of first matrix operand - * @param integer $matrix2Rows Row size of second matrix operand - * @param integer $matrix2Columns Column size of second matrix operand + * @param int $matrix1Rows Row size of first matrix operand + * @param int $matrix1Columns Column size of first matrix operand + * @param int $matrix2Rows Row size of second matrix operand + * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesExtend(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns) { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { - $x = $matrix2[$i][$matrix2Columns-1]; + $x = $matrix2[$i][$matrix2Columns - 1]; for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { $matrix2[$i][$j] = $x; } } } if ($matrix2Rows < $matrix1Rows) { - $x = $matrix2[$matrix2Rows-1]; + $x = $matrix2[$matrix2Rows - 1]; for ($i = 0; $i < $matrix1Rows; ++$i) { $matrix2[$i] = $x; } @@ -2945,14 +2884,14 @@ class Calculation if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { - $x = $matrix1[$i][$matrix1Columns-1]; + $x = $matrix1[$i][$matrix1Columns - 1]; for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { $matrix1[$i][$j] = $x; } } } if ($matrix1Rows < $matrix2Rows) { - $x = $matrix1[$matrix1Rows-1]; + $x = $matrix1[$matrix1Rows - 1]; for ($i = 0; $i < $matrix2Rows; ++$i) { $matrix1[$i] = $x; } @@ -2960,7 +2899,6 @@ class Calculation } } - /** * Format details of an operand for display in the log (based on operand type) * @@ -2976,27 +2914,28 @@ class Calculation } if (is_array($value)) { - $returnMatrix = array(); + $returnMatrix = []; $pad = $rpad = ', '; foreach ($value as $row) { if (is_array($row)) { - $returnMatrix[] = implode($pad, array_map(array($this, 'showValue'), $row)); + $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row)); $rpad = '; '; } else { $returnMatrix[] = $this->showValue($row); } } - return '{ '.implode($rpad, $returnMatrix).' }'; + + return '{ ' . implode($rpad, $returnMatrix) . ' }'; } elseif (is_string($value) && (trim($value, '"') == $value)) { - return '"'.$value.'"'; + return '"' . $value . '"'; } elseif (is_bool($value)) { return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } } + return Calculation\Functions::flattenSingleValue($value); } - /** * Format type and details of an operand for display in the log (based on operand type) * @@ -3025,20 +2964,20 @@ class Calculation if ($value == '') { return 'an empty string'; } elseif ($value{0} == '#') { - return 'a '.$value.' error'; + return 'a ' . $value . ' error'; } else { $typeString = 'a string'; } } - return $typeString.' with a value of '.$this->showValue($value); + + return $typeString . ' with a value of ' . $this->showValue($value); } } - private function convertMatrixReferences($formula) { - static $matrixReplaceFrom = array('{', ';', '}'); - static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))'); + static $matrixReplaceFrom = ['{', ';', '}']; + static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))']; // Convert any Excel matrix references to the MKMATRIX() function if (strpos($formula, '{') !== false) { @@ -3086,33 +3025,31 @@ class Calculation return $formula; } - private static function mkMatrix() { return func_get_args(); } - // Binary Operators // These operators always work on two values // Array key is the operator, the value indicates whether this is a left or right associative operator - private static $operatorAssociativity = array( + private static $operatorAssociativity = [ '^' => 0, // Exponentiation '*' => 0, '/' => 0, // Multiplication and Division '+' => 0, '-' => 0, // Addition and Subtraction '&' => 0, // Concatenation '|' => 0, ':' => 0, // Intersect and Range - '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison - ); + '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison + ]; // Comparison (Boolean) Operators // These operators work on two values, but always return a boolean result - private static $comparisonOperators = array('>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true); + private static $comparisonOperators = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true]; // Operator Precedence // This list includes all valid operators, whether binary (including boolean) or unary (such as %) // Array key is the operator, the value is its precedence - private static $operatorPrecedence = array( + private static $operatorPrecedence = [ ':' => 8, // Range '|' => 7, // Intersect '~' => 6, // Negation @@ -3121,8 +3058,8 @@ class Calculation '*' => 3, '/' => 3, // Multiplication and Division '+' => 2, '-' => 2, // Addition and Subtraction '&' => 1, // Concatenation - '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison - ); + '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison + ]; // Convert infix to postfix notation private function _parseFormula($formula, Cell $pCell = null) @@ -3135,19 +3072,19 @@ class Calculation // so we store the parent worksheet so that we can re-attach it when necessary $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null; - $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION. - '|'.self::CALCULATION_REGEXP_CELLREF. - '|'.self::CALCULATION_REGEXP_NUMBER. - '|'.self::CALCULATION_REGEXP_STRING. - '|'.self::CALCULATION_REGEXP_OPENBRACE. - '|'.self::CALCULATION_REGEXP_NAMEDRANGE. - '|'.self::CALCULATION_REGEXP_ERROR. + $regexpMatchString = '/^(' . self::CALCULATION_REGEXP_FUNCTION . + '|' . self::CALCULATION_REGEXP_CELLREF . + '|' . self::CALCULATION_REGEXP_NUMBER . + '|' . self::CALCULATION_REGEXP_STRING . + '|' . self::CALCULATION_REGEXP_OPENBRACE . + '|' . self::CALCULATION_REGEXP_NAMEDRANGE . + '|' . self::CALCULATION_REGEXP_ERROR . ')/si'; // Start with initialisation $index = 0; - $stack = new Calculation\Token\Stack; - $output = array(); + $stack = new Calculation\Token\Stack(); + $output = []; $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a // - is a negation or + is a positive operator rather than an operation $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand @@ -3155,10 +3092,10 @@ class Calculation // The guts of the lexical parser // Loop through the formula extracting each operator and operand in turn while (true) { -//echo 'Assessing Expression '.substr($formula, $index), PHP_EOL; + //echo 'Assessing Expression '.substr($formula, $index), PHP_EOL; $opCharacter = $formula{$index}; // Get the first character of the value at the current index position //echo 'Initial character of expression block is '.$opCharacter, PHP_EOL; - if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$comparisonOperators[$formula{$index+1}]))) { + if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$comparisonOperators[$formula{$index + 1}]))) { $opCharacter .= $formula{++$index}; //echo 'Initial character of expression block is comparison operator '.$opCharacter.PHP_EOL; } @@ -3173,7 +3110,7 @@ class Calculation $stack->push('Unary Operator', '~'); // Put a negation on the stack ++$index; // and drop the negation symbol } elseif ($opCharacter == '%' && $expectingOperator) { -//echo 'Element is a Percentage operator', PHP_EOL; + //echo 'Element is a Percentage operator', PHP_EOL; $stack->push('Unary Operator', '%'); // Put a percentage on the stack ++$index; } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded? @@ -3203,7 +3140,7 @@ class Calculation } } $d = $stack->last(2); - if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function? + if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $d['value'], $matches)) { // Did this parenthesis just close a function? $functionName = $matches[1]; // Get the function name //echo 'Closed Function is '.$functionName, PHP_EOL; $d = $stack->pop(); @@ -3218,27 +3155,27 @@ class Calculation $output[] = $d; // Dump the argument count on the output $output[] = $stack->pop(); // Pop the function and push onto the output if (isset(self::$controlFunctions[$functionName])) { -//echo 'Built-in function '.$functionName, PHP_EOL; + //echo 'Built-in function '.$functionName, PHP_EOL; $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount']; $functionCall = self::$controlFunctions[$functionName]['functionCall']; } elseif (isset(self::$phpSpreadsheetFunctions[$functionName])) { -//echo 'PhpSpreadsheet function '.$functionName, PHP_EOL; + //echo 'PhpSpreadsheet function '.$functionName, PHP_EOL; $expectedArgumentCount = self::$phpSpreadsheetFunctions[$functionName]['argumentCount']; $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall']; } else { // did we somehow push a non-function on the stack? this should never happen - return $this->raiseFormulaError("Formula Error: Internal error, non-function on stack"); + return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack'); } // Check the argument count $argumentCountError = false; if (is_numeric($expectedArgumentCount)) { if ($expectedArgumentCount < 0) { -//echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount), PHP_EOL; + //echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount), PHP_EOL; if ($argumentCount > abs($expectedArgumentCount)) { $argumentCountError = true; - $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount); + $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount); } } else { -//echo '$expectedArgumentCount is numeric '.$expectedArgumentCount, PHP_EOL; + //echo '$expectedArgumentCount is numeric '.$expectedArgumentCount, PHP_EOL; if ($argumentCount != $expectedArgumentCount) { $argumentCountError = true; $expectedArgumentCountString = $expectedArgumentCount; @@ -3252,25 +3189,25 @@ class Calculation case '+': if ($argumentCount < $argMatch[1]) { $argumentCountError = true; - $expectedArgumentCountString = $argMatch[1].' or more '; + $expectedArgumentCountString = $argMatch[1] . ' or more '; } break; case '-': if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) { $argumentCountError = true; - $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3]; + $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3]; } break; case ',': if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) { $argumentCountError = true; - $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3]; + $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3]; } break; } } if ($argumentCountError) { - return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected"); + return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected'); } } ++$index; @@ -3278,7 +3215,7 @@ class Calculation //echo 'Element is a Function argument separator', PHP_EOL; while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last ( if ($o2 === null) { - return $this->raiseFormulaError("Formula Error: Unexpected ,"); + return $this->raiseFormulaError('Formula Error: Unexpected ,'); } else { $output[] = $o2; // pop the argument expression stuff and push onto the output } @@ -3286,12 +3223,12 @@ class Calculation // If we've a comma when we're expecting an operand, then what we actually have is a null operand; // so push a null onto the stack if (($expectingOperand) || (!$expectingOperator)) { - $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null); + $output[] = ['type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null]; } // make sure there was a function $d = $stack->last(2); - if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { - return $this->raiseFormulaError("Formula Error: Unexpected ,"); + if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $d['value'], $matches)) { + return $this->raiseFormulaError('Formula Error: Unexpected ,'); } $d = $stack->pop(); $stack->push($d['type'], ++$d['value'], $d['reference']); // increment the argument count @@ -3300,7 +3237,7 @@ class Calculation $expectingOperand = true; ++$index; } elseif ($opCharacter == '(' && !$expectingOperator) { -// echo 'Element is an Opening Bracket
'; + // echo 'Element is an Opening Bracket
'; $stack->push('Brace', '('); ++$index; } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number? @@ -3310,25 +3247,25 @@ class Calculation $length = strlen($val); // echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function
'; - if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) { + if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $val, $matches)) { $val = preg_replace('/\s/u', '', $val); // echo 'Element '.$val.' is a Function
'; if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function $stack->push('Function', strtoupper($val)); - $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index+$length), $amatch); + $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index + $length), $amatch); if ($ax) { - $stack->push('Operand Count for Function '.strtoupper($val).')', 0); + $stack->push('Operand Count for Function ' . strtoupper($val) . ')', 0); $expectingOperator = true; } else { - $stack->push('Operand Count for Function '.strtoupper($val).')', 1); + $stack->push('Operand Count for Function ' . strtoupper($val) . ')', 1); $expectingOperator = false; } $stack->push('Brace', '('); } else { // it's a var w/ implicit multiplication - $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => null); + $output[] = ['type' => 'Value', 'value' => $matches[1], 'reference' => null]; } - } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) { -// echo 'Element '.$val.' is a Cell reference
'; + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $val, $matches)) { + // echo 'Element '.$val.' is a Cell reference
'; // Watch for this case-change when modifying to allow cell references in different worksheets... // Should only be applied to the actual cell column, not the worksheet name @@ -3339,24 +3276,24 @@ class Calculation if ($matches[2] == '') { // Otherwise, we 'inherit' the worksheet reference from the start cell reference // The start of the cell range reference should be the last entry in $output - $startCellRef = $output[count($output)-1]['value']; - preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches); + $startCellRef = $output[count($output) - 1]['value']; + preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $startCellRef, $startMatches); if ($startMatches[2] > '') { - $val = $startMatches[2].'!'.$val; + $val = $startMatches[2] . '!' . $val; } } else { - return $this->raiseFormulaError("3D Range references are not yet supported"); + return $this->raiseFormulaError('3D Range references are not yet supported'); } } - $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val); + $output[] = ['type' => 'Cell Reference', 'value' => $val, 'reference' => $val]; // $expectingOperator = FALSE; } else { // it's a variable, constant, string, number or boolean // echo 'Element is a Variable, Constant, String, Number or Boolean
'; // If the last entry on the stack was a : operator, then we may have a row or column range reference $testPrevOp = $stack->last(1); if ($testPrevOp['value'] == ':') { - $startRowColRef = $output[count($output)-1]['value']; + $startRowColRef = $output[count($output) - 1]['value']; $rangeWS1 = ''; if (strpos('!', $startRowColRef) !== false) { list($rangeWS1, $startRowColRef) = explode('!', $startRowColRef); @@ -3375,29 +3312,29 @@ class Calculation ($startRowColRef <= 1048576) && ($val <= 1048576)) { // Row range $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007 - $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef; - $val = $rangeWS2.$endRowColRef.$val; + $output[count($output) - 1]['value'] = $rangeWS1 . 'A' . $startRowColRef; + $val = $rangeWS2 . $endRowColRef . $val; } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) && (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) { // Column range $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007 - $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1'; - $val = $rangeWS2.$val.$endRowColRef; + $output[count($output) - 1]['value'] = $rangeWS1 . strtoupper($startRowColRef) . '1'; + $val = $rangeWS2 . $val . $endRowColRef; } } $localeConstant = false; if ($opCharacter == '"') { -// echo 'Element is a String
'; + // echo 'Element is a String
'; // UnEscape any quotes within the string $val = self::wrapResult(str_replace('""', '"', self::unwrapResult($val))); } elseif (is_numeric($val)) { -// echo 'Element is a Number
'; + // echo 'Element is a Number
'; if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { -// echo 'Casting '.$val.' to float
'; + // echo 'Casting '.$val.' to float
'; $val = (float) $val; } else { -// echo 'Casting '.$val.' to integer
'; + // echo 'Casting '.$val.' to integer
'; $val = (integer) $val; } } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { @@ -3405,10 +3342,10 @@ class Calculation // echo 'Element '.$excelConstant.' is an Excel Constant
'; $val = self::$excelConstants[$excelConstant]; } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { -// echo 'Element '.$localeConstant.' is an Excel Constant
'; + // echo 'Element '.$localeConstant.' is an Excel Constant
'; $val = self::$excelConstants[$localeConstant]; } - $details = array('type' => 'Value', 'value' => $val, 'reference' => null); + $details = ['type' => 'Value', 'value' => $val, 'reference' => null]; if ($localeConstant) { $details['localeValue'] = $localeConstant; } @@ -3419,7 +3356,7 @@ class Calculation ++$index; } elseif ($opCharacter == ')') { // miscellaneous error checking if ($expectingOperand) { - $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null); + $output[] = ['type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null]; $expectingOperand = false; $expectingOperator = true; } else { @@ -3428,7 +3365,7 @@ class Calculation } elseif (isset(self::$operators[$opCharacter]) && !$expectingOperator) { return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'"); } else { // I don't even want to know what you did to get here - return $this->raiseFormulaError("Formula Error: An unexpected error occured"); + return $this->raiseFormulaError('Formula Error: An unexpected error occured'); } // Test for end of formula string if ($index == strlen($formula)) { @@ -3451,9 +3388,9 @@ class Calculation // If we're expecting an operator, but only have a space between the previous and next operands (and both are // Cell References) then we have an INTERSECTION operator // echo 'Possible Intersect Operator
'; - if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) && - ($output[count($output)-1]['type'] == 'Cell Reference')) { -// echo 'Element is an Intersect Operator
'; + if (($expectingOperator) && (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/Ui', substr($formula, $index), $match)) && + ($output[count($output) - 1]['type'] == 'Cell Reference')) { + // echo 'Element is an Intersect Operator
'; while ($stack->count() > 0 && ($o2 = $stack->last()) && isset(self::$operators[$o2['value']]) && @@ -3472,10 +3409,10 @@ class Calculation } $output[] = $op; } + return $output; } - private static function dataTestReference(&$operandData) { $operand = $operandData['value']; @@ -3485,9 +3422,10 @@ class Calculation $cKeys = array_keys(array_keys($operand[$rowKey])); $colKey = array_shift($cKeys); if (ctype_upper($colKey)) { - $operandData['reference'] = $colKey.$rowKey; + $operandData['reference'] = $colKey . $rowKey; } } + return $operand; } @@ -3502,17 +3440,17 @@ class Calculation // so we store the parent cell collection so that we can re-attach it when necessary $pCellWorksheet = ($pCell !== null) ? $pCell->getWorksheet() : null; $pCellParent = ($pCell !== null) ? $pCell->getParent() : null; - $stack = new Calculation\Token\Stack; + $stack = new Calculation\Token\Stack(); // Loop through each token in turn foreach ($tokens as $tokenData) { -// print_r($tokenData); + // print_r($tokenData); // echo '
'; $token = $tokenData['value']; // echo 'Token is '.$token.'
'; // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack if (isset(self::$binaryOperators[$token])) { -// echo 'Token is a binary operator
'; + // echo 'Token is a binary operator
'; // We must have two operands, error if we don't if (($operand2Data = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); @@ -3558,31 +3496,31 @@ class Calculation if ($sheet1 == $sheet2) { if ($operand1Data['reference'] === null) { if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { - $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value']; + $operand1Data['reference'] = $pCell->getColumn() . $operand1Data['value']; } elseif (trim($operand1Data['reference']) == '') { $operand1Data['reference'] = $pCell->getCoordinate(); } else { - $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow(); + $operand1Data['reference'] = $operand1Data['value'] . $pCell->getRow(); } } if ($operand2Data['reference'] === null) { if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) { - $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value']; + $operand2Data['reference'] = $pCell->getColumn() . $operand2Data['value']; } elseif (trim($operand2Data['reference']) == '') { $operand2Data['reference'] = $pCell->getCoordinate(); } else { - $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow(); + $operand2Data['reference'] = $operand2Data['value'] . $pCell->getRow(); } } $oData = array_merge(explode(':', $operand1Data['reference']), explode(':', $operand2Data['reference'])); - $oCol = $oRow = array(); + $oCol = $oRow = []; foreach ($oData as $oDatum) { $oCR = Cell::coordinateFromString($oDatum); $oCol[] = Cell::columnIndexFromString($oCR[0]) - 1; $oRow[] = $oCR[1]; } - $cellRef = Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.Cell::stringFromColumnIndex(max($oCol)).max($oRow); + $cellRef = Cell::stringFromColumnIndex(min($oCol)) . min($oRow) . ':' . Cell::stringFromColumnIndex(max($oCol)) . max($oRow); if ($pCellParent !== null) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false); } else { @@ -3632,14 +3570,14 @@ class Calculation $result = '#VALUE!'; } } else { - $result = '"'.str_replace('""', '"', self::unwrapResult($operand1, '"').self::unwrapResult($operand2, '"')).'"'; + $result = '"' . str_replace('""', '"', self::unwrapResult($operand1, '"') . self::unwrapResult($operand2, '"')) . '"'; } $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); $stack->push('Value', $result); break; case '|': // Intersect $rowIntersect = array_intersect_key($operand1, $operand2); - $cellIntersect = $oCol = $oRow = array(); + $cellIntersect = $oCol = $oRow = []; foreach (array_keys($rowIntersect) as $row) { $oRow[] = $row; foreach ($rowIntersect[$row] as $col => $data) { @@ -3647,7 +3585,7 @@ class Calculation $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]); } } - $cellRef = Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.Cell::stringFromColumnIndex(max($oCol)).max($oRow); + $cellRef = Cell::stringFromColumnIndex(min($oCol)) . min($oRow) . ':' . Cell::stringFromColumnIndex(max($oCol)) . max($oRow); $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($cellIntersect)); $stack->push('Value', $cellIntersect, $cellRef); break; @@ -3655,17 +3593,17 @@ class Calculation // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on } elseif (($token === '~') || ($token === '%')) { -// echo 'Token is a unary operator
'; + // echo 'Token is a unary operator
'; if (($arg = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $arg = $arg['value']; if ($token === '~') { -// echo 'Token is a negation operator
'; + // echo 'Token is a negation operator
'; $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->showValue($arg)); $multiplier = -1; } else { -// echo 'Token is a percentile operator
'; + // echo 'Token is a percentile operator
'; $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->showValue($arg)); $multiplier = 0.01; } @@ -3684,16 +3622,16 @@ class Calculation } else { $this->executeNumericBinaryOperation($cellID, $multiplier, $arg, '*', 'arrayTimesEquals', $stack); } - } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) { + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token, $matches)) { $cellRef = null; // echo 'Element '.$token.' is a Cell reference
'; if (isset($matches[8])) { -// echo 'Reference is a Range of cells
'; + // echo 'Reference is a Range of cells
'; if ($pCell === null) { -// We can't access the range, so return a REF error + // We can't access the range, so return a REF error $cellValue = Calculation\Functions::REF(); } else { - $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10]; + $cellRef = $matches[6] . $matches[7] . ':' . $matches[9] . $matches[10]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) { @@ -3711,7 +3649,7 @@ class Calculation $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue)); // $cellRef = $matches[2].'!'.$cellRef; } else { -// echo '$cellRef='.$cellRef.' in current worksheet
'; + // echo '$cellRef='.$cellRef.' in current worksheet
'; $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet'); if ($pCellParent !== null) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); @@ -3722,12 +3660,12 @@ class Calculation } } } else { -// echo 'Reference is a single Cell
'; + // echo 'Reference is a single Cell
'; if ($pCell === null) { -// We can't access the cell, so return a REF error + // We can't access the cell, so return a REF error $cellValue = Calculation\Functions::REF(); } else { - $cellRef = $matches[6].$matches[7]; + $cellRef = $matches[6] . $matches[7]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) { @@ -3750,7 +3688,7 @@ class Calculation $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue)); // $cellRef = $matches[2].'!'.$cellRef; } else { -// echo '$cellRef='.$cellRef.' in current worksheet
'; + // echo '$cellRef='.$cellRef.' in current worksheet
'; $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet'); if ($pCellParent->isDataSet($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); @@ -3765,8 +3703,8 @@ class Calculation $stack->push('Value', $cellValue, $cellRef); // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on - } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) { -// echo 'Token is a function
'; + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $token, $matches)) { + // echo 'Token is a function
'; $functionName = $matches[1]; $argCount = $stack->pop(); $argCount = $argCount['value']; @@ -3785,7 +3723,7 @@ class Calculation } // get the arguments for this function // echo 'Function '.$functionName.' expects '.$argCount.' arguments
'; - $args = $argArrayVals = array(); + $args = $argArrayVals = []; for ($i = 0; $i < $argCount; ++$i) { $arg = $stack->pop(); $a = $argCount - $i - 1; @@ -3822,7 +3760,7 @@ class Calculation if ($functionName != 'MKMATRIX') { if ($this->_debugLog->getWriteDebugLog()) { krsort($argArrayVals); - $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator.' ', Calculation\Functions::flattenArray($argArrayVals)), ' )'); + $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator . ' ', Calculation\Functions::flattenArray($argArrayVals)), ' )'); } } // Process each argument in turn, building the return value as an array @@ -3874,11 +3812,11 @@ class Calculation $stack->push('Constant Value', self::$excelConstants[$excelConstant]); $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->showTypeDetails(self::$excelConstants[$excelConstant])); } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) { -// echo 'Token is a number, boolean, string, null or an Excel error
'; + // echo 'Token is a number, boolean, string, null or an Excel error
'; $stack->push('Value', $token); // if the token is a named range, push the named range name onto the stack - } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) { -// echo 'Token is a named range
'; + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $token, $matches)) { + // echo 'Token is a named range
'; $namedRange = $matches[6]; // echo 'Named Range is '.$namedRange.'
'; $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange); @@ -3893,7 +3831,7 @@ class Calculation } // when we're out of tokens, the stack should have a single element, the final result if ($stack->count() != 1) { - return $this->raiseFormulaError("internal error"); + return $this->raiseFormulaError('internal error'); } $output = $stack->pop(); $output = $output['value']; @@ -3904,7 +3842,6 @@ class Calculation return $output; } - private function validateBinaryOperand($cellID, &$operand, &$stack) { if (is_array($operand)) { @@ -3927,11 +3864,13 @@ class Calculation if ($operand > '' && $operand{0} == '#') { $stack->push('Value', $operand); $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($operand)); + return false; } elseif (!Shared\StringHelper::convertToNumberIfFraction($operand)) { // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations $stack->push('Value', '#VALUE!'); $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->showTypeDetails('#VALUE!')); + return false; } } @@ -3941,12 +3880,11 @@ class Calculation return true; } - private function executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays = false) { // If we're dealing with matrix operations, we want a matrix result if ((is_array($operand1)) || (is_array($operand2))) { - $result = array(); + $result = []; if ((is_array($operand1)) && (!is_array($operand2))) { foreach ($operand1 as $x => $operandData) { $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2)); @@ -3976,6 +3914,7 @@ class Calculation $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Array', $result); + return true; } @@ -4059,6 +3998,7 @@ class Calculation $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); + return true; } @@ -4066,7 +4006,7 @@ class Calculation * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters * @param string $str1 First string value for the comparison * @param string $str2 Second string value for the comparison - * @return integer + * @return int */ private function strcmpLowercaseFirst($str1, $str2) { @@ -4105,8 +4045,8 @@ class Calculation } } else { if ((Calculation\Functions::getCompatibilityMode() != Calculation\Functions::COMPATIBILITY_OPENOFFICE) && - ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1)>0) || - (is_string($operand2) && !is_numeric($operand2) && strlen($operand2)>0))) { + ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1) > 0) || + (is_string($operand2) && !is_numeric($operand2) && strlen($operand2) > 0))) { $result = Calculation\Functions::VALUE(); } else { // If we're dealing with non-matrix operations, execute the necessary operation @@ -4129,6 +4069,7 @@ class Calculation // Trap for Divide by Zero error $stack->push('Value', '#DIV/0!'); $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails('#DIV/0!')); + return false; } else { $result = $operand1 / $operand2; @@ -4146,10 +4087,10 @@ class Calculation $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); + return true; } - // trigger an error, but nicely, if need be protected function raiseFormulaError($errorMessage) { @@ -4161,20 +4102,19 @@ class Calculation trigger_error($errorMessage, E_USER_ERROR); } - /** * Extract range values * * @param string &$pRange String based range representation * @param Worksheet $pSheet Worksheet - * @param boolean $resetLog Flag indicating whether calculation log should be reset or not - * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. + * @param bool $resetLog Flag indicating whether calculation log should be reset or not * @throws Calculation\Exception + * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractCellRange(&$pRange = 'A1', Worksheet $pSheet = null, $resetLog = true) { // Return value - $returnValue = array (); + $returnValue = []; // echo 'extractCellRange('.$pRange.')', PHP_EOL; if ($pSheet !== null) { @@ -4182,7 +4122,7 @@ class Calculation // echo 'Passed sheet name is '.$pSheetName.PHP_EOL; // echo 'Range reference is '.$pRange.PHP_EOL; if (strpos($pRange, '!') !== false) { -// echo '$pRange reference includes sheet reference', PHP_EOL; + // echo '$pRange reference includes sheet reference', PHP_EOL; list($pSheetName, $pRange) = Worksheet::extractSheetTitle($pRange, true); // echo 'New sheet name is '.$pSheetName, PHP_EOL; // echo 'Adjusted Range reference is '.$pRange, PHP_EOL; @@ -4191,7 +4131,7 @@ class Calculation // Extract range $aReferences = Cell::extractAllCellReferencesInRange($pRange); - $pRange = $pSheetName.'!'.$pRange; + $pRange = $pSheetName . '!' . $pRange; if (!isset($aReferences[1])) { // Single cell in range sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); @@ -4219,20 +4159,19 @@ class Calculation return $returnValue; } - /** * Extract range values * * @param string &$pRange String based range representation * @param Worksheet $pSheet Worksheet - * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. - * @param boolean $resetLog Flag indicating whether calculation log should be reset or not + * @param bool $resetLog Flag indicating whether calculation log should be reset or not * @throws Calculation\Exception + * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractNamedRange(&$pRange = 'A1', Worksheet $pSheet = null, $resetLog = true) { // Return value - $returnValue = array (); + $returnValue = []; // echo 'extractNamedRange('.$pRange.')
'; if ($pSheet !== null) { @@ -4240,7 +4179,7 @@ class Calculation // echo 'Current sheet name is '.$pSheetName.'
'; // echo 'Range reference is '.$pRange.'
'; if (strpos($pRange, '!') !== false) { -// echo '$pRange reference includes sheet reference', PHP_EOL; + // echo '$pRange reference includes sheet reference', PHP_EOL; list($pSheetName, $pRange) = Worksheet::extractSheetTitle($pRange, true); // echo 'New sheet name is '.$pSheetName, PHP_EOL; // echo 'Adjusted Range reference is '.$pRange, PHP_EOL; @@ -4306,24 +4245,22 @@ class Calculation return $returnValue; } - /** * Is a specific function implemented? * * @param string $pFunction Function Name - * @return boolean + * @return bool */ public function isImplemented($pFunction = '') { $pFunction = strtoupper($pFunction); if (isset(self::$phpSpreadsheetFunctions[$pFunction])) { - return (self::$phpSpreadsheetFunctions[$pFunction]['functionCall'] != 'Calculation\Categories::DUMMY'); + return self::$phpSpreadsheetFunctions[$pFunction]['functionCall'] != 'Calculation\Categories::DUMMY'; } else { return false; } } - /** * Get a list of all implemented functions as an array of function objects * @@ -4331,7 +4268,7 @@ class Calculation */ public function listFunctions() { - $returnValue = array(); + $returnValue = []; foreach (self::$phpSpreadsheetFunctions as $functionName => $function) { if ($function['functionCall'] != 'Calculation\Categories::DUMMY') { @@ -4346,7 +4283,6 @@ class Calculation return $returnValue; } - /** * Get a list of all Excel function names * @@ -4364,7 +4300,7 @@ class Calculation */ public function listFunctionNames() { - $returnValue = array(); + $returnValue = []; foreach (self::$phpSpreadsheetFunctions as $functionName => $function) { if ($function['functionCall'] != 'Calculation\Categories::DUMMY') { $returnValue[] = $functionName; diff --git a/src/PhpSpreadsheet/Calculation/Categories.php b/src/PhpSpreadsheet/Calculation/Categories.php index e5bec251..4ecc609c 100644 --- a/src/PhpSpreadsheet/Calculation/Categories.php +++ b/src/PhpSpreadsheet/Calculation/Categories.php @@ -27,17 +27,17 @@ namespace PhpSpreadsheet\Calculation; class Categories { /* Function categories */ - const CATEGORY_CUBE = 'Cube'; - const CATEGORY_DATABASE = 'Database'; - const CATEGORY_DATE_AND_TIME = 'Date and Time'; - const CATEGORY_ENGINEERING = 'Engineering'; - const CATEGORY_FINANCIAL = 'Financial'; - const CATEGORY_INFORMATION = 'Information'; - const CATEGORY_LOGICAL = 'Logical'; + const CATEGORY_CUBE = 'Cube'; + const CATEGORY_DATABASE = 'Database'; + const CATEGORY_DATE_AND_TIME = 'Date and Time'; + const CATEGORY_ENGINEERING = 'Engineering'; + const CATEGORY_FINANCIAL = 'Financial'; + const CATEGORY_INFORMATION = 'Information'; + const CATEGORY_LOGICAL = 'Logical'; const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference'; - const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; - const CATEGORY_STATISTICAL = 'Statistical'; - const CATEGORY_TEXT_AND_DATA = 'Text and Data'; + const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; + const CATEGORY_STATISTICAL = 'Statistical'; + const CATEGORY_TEXT_AND_DATA = 'Text and Data'; /** * Category (represented by CATEGORY_*) @@ -71,11 +71,11 @@ class Categories { if (($pCategory !== null) && ($pExcelName !== null) && ($spreadsheetName !== null)) { // Initialise values - $this->category = $pCategory; - $this->excelName = $pExcelName; + $this->category = $pCategory; + $this->excelName = $pExcelName; $this->spreadsheetName = $spreadsheetName; } else { - throw new Exception("Invalid parameters passed."); + throw new Exception('Invalid parameters passed.'); } } @@ -100,7 +100,7 @@ class Categories if (!is_null($value)) { $this->category = $value; } else { - throw new Exception("Invalid parameter passed."); + throw new Exception('Invalid parameter passed.'); } } diff --git a/src/PhpSpreadsheet/Calculation/Database.php b/src/PhpSpreadsheet/Calculation/Database.php index 36715f7d..1468b9d3 100644 --- a/src/PhpSpreadsheet/Calculation/Database.php +++ b/src/PhpSpreadsheet/Calculation/Database.php @@ -31,7 +31,6 @@ class Database * * 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. * A database is a list of related data in which rows of related * 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 * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. - * @return string|NULL - * + * @return string|null */ private static function fieldExtract($database, $field) { @@ -51,9 +49,11 @@ class Database if (is_numeric($field)) { $keys = array_keys($fieldNames); - return $keys[$field-1]; + + return $keys[$field - 1]; } $key = array_search($field, $fieldNames); + return ($key) ? $key : null; } @@ -63,7 +63,6 @@ class Database * Parses the selection criteria, extracts the database rows that match those criteria, and * returns that subset of rows. * - * @access private * @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 * 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 * column. * @return array of mixed - * */ private static function filter($database, $criteria) { @@ -82,23 +80,23 @@ class Database $criteriaNames = array_shift($criteria); // Convert the criteria into a set of AND/OR conditions with [:placeholders] - $testConditions = $testValues = array(); + $testConditions = $testValues = []; $testConditionsCount = 0; foreach ($criteriaNames as $key => $criteriaName) { - $testCondition = array(); + $testCondition = []; $testConditionCount = 0; foreach ($criteria as $row => $criterion) { if ($criterion[$key] > '') { - $testCondition[] = '[:'.$criteriaName.']'.Functions::ifCondition($criterion[$key]); - $testConditionCount++; + $testCondition[] = '[:' . $criteriaName . ']' . Functions::ifCondition($criterion[$key]); + ++$testConditionCount; } } if ($testConditionCount > 1) { $testConditions[] = 'OR(' . implode(',', $testCondition) . ')'; - $testConditionsCount++; + ++$testConditionsCount; } elseif ($testConditionCount == 1) { $testConditions[] = $testCondition[0]; - $testConditionsCount++; + ++$testConditionsCount; } } @@ -121,7 +119,7 @@ class Database } } // 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 (!$result) { unset($database[$dataRow]); @@ -131,13 +129,12 @@ class Database return $database; } - private static function getFilteredColumn($database, $field, $criteria) { // reduce the database to a set of rows that match all the criteria $database = self::filter($database, $criteria); // extract an array of values for the requested column - $colData = array(); + $colData = []; foreach ($database as $row) { $colData[] = $row[$field]; } @@ -153,13 +150,12 @@ class Database * Excel Function: * DAVERAGE(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DAVERAGE($database, $field, $criteria) { @@ -185,7 +180,6 @@ class Database ); } - /** * DCOUNT * @@ -198,13 +192,12 @@ class Database * Excel Function: * DAVERAGE(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * the column label in which you specify a condition for the * column. - * @return integer + * @return int * * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the * database that match the criteria. - * */ public static function DCOUNT($database, $field, $criteria) { @@ -233,7 +225,6 @@ class Database ); } - /** * DCOUNTA * @@ -242,13 +233,12 @@ class Database * Excel Function: * DCOUNTA(database,[field],criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * the column label in which you specify a condition for the * column. - * @return integer + * @return int * * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the * database that match the 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 $database = self::filter($database, $criteria); // extract an array of values for the requested column - $colData = array(); + $colData = []; foreach ($database as $row) { $colData[] = $row[$field]; } @@ -285,7 +274,6 @@ class Database ); } - /** * DGET * @@ -295,13 +283,12 @@ class Database * Excel Function: * DGET(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return mixed - * */ public static function DGET($database, $field, $criteria) { @@ -330,7 +316,6 @@ class Database return $colData[0]; } - /** * DMAX * @@ -340,13 +325,12 @@ class Database * Excel Function: * DMAX(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DMAX($database, $field, $criteria) { @@ -372,7 +355,6 @@ class Database ); } - /** * DMIN * @@ -382,13 +364,12 @@ class Database * Excel Function: * DMIN(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DMIN($database, $field, $criteria) { @@ -414,7 +394,6 @@ class Database ); } - /** * DPRODUCT * @@ -423,13 +402,12 @@ class Database * Excel Function: * DPRODUCT(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DPRODUCT($database, $field, $criteria) { @@ -455,7 +432,6 @@ class Database ); } - /** * DSTDEV * @@ -465,13 +441,12 @@ class Database * Excel Function: * DSTDEV(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DSTDEV($database, $field, $criteria) { @@ -497,7 +471,6 @@ class Database ); } - /** * DSTDEVP * @@ -507,13 +480,12 @@ class Database * Excel Function: * DSTDEVP(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DSTDEVP($database, $field, $criteria) { @@ -539,7 +510,6 @@ class Database ); } - /** * DSUM * @@ -548,13 +518,12 @@ class Database * Excel Function: * DSUM(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DSUM($database, $field, $criteria) { @@ -580,7 +548,6 @@ class Database ); } - /** * DVAR * @@ -590,13 +557,12 @@ class Database * Excel Function: * DVAR(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DVAR($database, $field, $criteria) { @@ -622,7 +587,6 @@ class Database ); } - /** * DVARP * @@ -632,13 +596,12 @@ class Database * Excel Function: * DVARP(database,field,criteria) * - * @access public * @category Database Functions * @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 * information are records, and columns of data are fields. The * 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 * "Age" or "Yield," or a number (without quotation marks) that * 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 * column. * @return float - * */ public static function DVARP($database, $field, $criteria) { diff --git a/src/PhpSpreadsheet/Calculation/DateTime.php b/src/PhpSpreadsheet/Calculation/DateTime.php index 1f3ceeca..b6feca89 100644 --- a/src/PhpSpreadsheet/Calculation/DateTime.php +++ b/src/PhpSpreadsheet/Calculation/DateTime.php @@ -29,26 +29,25 @@ class DateTime /** * Identify if a year is a leap year or not * - * @param integer $year The year to test - * @return boolean TRUE if the year is a leap year, otherwise FALSE + * @param int $year The year to test + * @return bool TRUE if the year is a leap year, otherwise FALSE */ 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 * - * @param integer $startDay Day of month of the start date - * @param integer $startMonth Month of the start date - * @param integer $startYear Year of the start date - * @param integer $endDay Day of month of the start date - * @param integer $endMonth Month of the start date - * @param integer $endYear Year of the start date - * @param boolean $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 + * @param int $startDay Day of month of the start date + * @param int $startMonth Month of the start date + * @param int $startYear Year of the start date + * @param int $endDay Day of month of the start date + * @param int $endMonth Month of the start date + * @param int $endYear Year of the start date + * @param bool $methodUS Whether to use the US method or the European method of calculation + * @return int Number of days between the start date and the end date */ 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; } - /** * getDateValue * @@ -97,10 +95,10 @@ class DateTime Functions::setReturnDateType($saveReturnDateType); } } + return $dateValue; } - /** * getTimeValue * @@ -113,10 +111,10 @@ class DateTime Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); $timeValue = self::TIMEVALUE($timeValue); Functions::setReturnDateType($saveReturnDateType); + return $timeValue; } - private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) { // Execute function @@ -126,10 +124,10 @@ class DateTime $adjustmentMonthsString = (string) $adjustmentMonths; if ($adjustmentMonths > 0) { - $adjustmentMonthsString = '+'.$adjustmentMonths; + $adjustmentMonthsString = '+' . $adjustmentMonths; } if ($adjustmentMonths != 0) { - $PHPDateObject->modify($adjustmentMonthsString.' months'); + $PHPDateObject->modify($adjustmentMonthsString . ' months'); } $nMonth = (int) $PHPDateObject->format('m'); $nYear = (int) $PHPDateObject->format('Y'); @@ -137,13 +135,13 @@ class DateTime $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); if ($monthDiff != $adjustmentMonths) { $adjustDays = (int) $PHPDateObject->format('d'); - $adjustDaysString = '-'.$adjustDays.' days'; + $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); } + return $PHPDateObject; } - /** * DATETIMENOW * @@ -158,7 +156,6 @@ class DateTime * Excel Function: * NOW() * - * @access public * @category Date/Time Functions * @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 @@ -184,7 +181,6 @@ class DateTime return $retValue; } - /** * DATENOW * @@ -199,7 +195,6 @@ class DateTime * Excel Function: * TODAY() * - * @access public * @category Date/Time Functions * @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 @@ -226,7 +221,6 @@ class DateTime return $retValue; } - /** * 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, * 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 - * @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 * date system: 1900 or 1904. * If year is between 0 (zero) and 1899 (inclusive), Excel adds that @@ -255,7 +248,7 @@ class DateTime * 2008. * If year is less than 0 or is 10000 or greater, Excel returns the * #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). * 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) @@ -264,7 +257,7 @@ class DateTime * number of months, plus 1, from the first month in the year * specified. For example, DATE(2008,-3,2) returns the serial number * 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. * 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 @@ -279,9 +272,9 @@ class DateTime */ public static function DATE($year = 0, $month = 1, $day = 1) { - $year = Functions::flattenSingleValue($year); + $year = Functions::flattenSingleValue($year); $month = Functions::flattenSingleValue($month); - $day = Functions::flattenSingleValue($day); + $day = Functions::flattenSingleValue($day); if (($month !== null) && (!is_numeric($month))) { $month = \PhpSpreadsheet\Shared\Date::monthStringToNumber($month); @@ -299,20 +292,20 @@ class DateTime (!is_numeric($day))) { return Functions::VALUE(); } - $year = (integer) $year; - $month = (integer) $month; - $day = (integer) $day; + $year = (integer) $year; + $month = (integer) $month; + $day = (integer) $day; $baseYear = \PhpSpreadsheet\Shared\Date::getExcelCalendar(); // Validate parameters - if ($year < ($baseYear-1900)) { + if ($year < ($baseYear - 1900)) { return Functions::NAN(); } - if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) { + if ((($baseYear - 1900) != 0) && ($year < $baseYear) && ($year >= 1900)) { return Functions::NAN(); } - if (($year < $baseYear) && ($year >= ($baseYear-1900))) { + if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { $year += 1900; } @@ -344,7 +337,6 @@ class DateTime } } - /** * TIME * @@ -356,16 +348,15 @@ class DateTime * Excel Function: * TIME(hour,minute,second) * - * @access public * @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 * will be treated as the hour value. For example, TIME(27,0,0) = * 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. * 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, * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 * or 12:33:20 AM @@ -430,6 +421,7 @@ class DateTime if ($calendar != \PhpSpreadsheet\Shared\Date::CALENDAR_WINDOWS_1900) { $date = 1; } + return (float) \PhpSpreadsheet\Shared\Date::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); case Functions::RETURNDATE_PHP_NUMERIC: 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); $hour = $hour % 24; } - $phpDateObject = new \DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second); + $phpDateObject = new \DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); if ($dayAdjust != 0) { - $phpDateObject->modify($dayAdjust.' days'); + $phpDateObject->modify($dayAdjust . ' days'); } + return $phpDateObject; } } - /** * DATEVALUE * @@ -467,7 +459,6 @@ class DateTime * Excel Function: * DATEVALUE(dateValue) * - * @access public * @category Date/Time Functions * @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 @@ -482,12 +473,12 @@ class DateTime */ public static function DATEVALUE($dateValue = 1) { - $dateValueOrig= $dateValue; + $dateValueOrig = $dateValue; $dateValue = trim(Functions::flattenSingleValue($dateValue), '"'); // Strip any ordinals because they're allowed in Excel (English only) $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) - $dateValue = str_replace(array('/', '.', '-', ' '), array(' ', ' ', ' ', ' '), $dateValue); + $dateValue = str_replace(['/', '.', '-', ' '], [' ', ' ', ' ', ' '], $dateValue); $yearFound = false; $t1 = explode(' ', $dateValue); @@ -541,9 +532,9 @@ class DateTime if ($testVal1 < 31 && $testVal2 < 12 && $testVal3 < 12 && strlen($testVal3) == 2) { $testVal3 += 2000; } - $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3); + $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3); 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)) { return Functions::VALUE(); } @@ -583,13 +574,13 @@ class DateTime case Functions::RETURNDATE_PHP_NUMERIC: return (integer) \PhpSpreadsheet\Shared\Date::excelToTimestamp($excelDateValue); 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(); } - /** * TIMEVALUE * @@ -603,7 +594,6 @@ class DateTime * Excel Function: * TIMEVALUE(timeValue) * - * @access public * @category Date/Time Functions * @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 @@ -615,10 +605,10 @@ class DateTime public static function TIMEVALUE($timeValue) { $timeValue = trim(Functions::flattenSingleValue($timeValue), '"'); - $timeValue = str_replace(array('/', '.'), array('-', '-'), $timeValue); + $timeValue = str_replace(['/', '.'], ['-', '-'], $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); $timeValue = implode(':', $arraySplit); } @@ -642,15 +632,15 @@ class DateTime case Functions::RETURNDATE_EXCEL: return (float) $excelDateValue; 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: - 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(); } - /** * DATEDIF * @@ -659,13 +649,13 @@ class DateTime * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * @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') { $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - $unit = strtoupper(Functions::flattenSingleValue($unit)); + $endDate = Functions::flattenSingleValue($endDate); + $unit = strtoupper(Functions::flattenSingleValue($unit)); if (is_string($startDate = self::getDateValue($startDate))) { return Functions::VALUE(); @@ -719,7 +709,7 @@ class DateTime case 'MD': if ($endDays < $startDays) { $retVal = $endDays; - $PHPEndDateObject->modify('-'.$endDays.' days'); + $PHPEndDateObject->modify('-' . $endDays . ' days'); $adjustDays = $PHPEndDateObject->format('j'); $retVal += ($adjustDays - $startDays); } else { @@ -752,10 +742,10 @@ class DateTime default: $retVal = Functions::VALUE(); } + return $retVal; } - /** * DAYS360 * @@ -766,13 +756,12 @@ class DateTime * Excel Function: * DAYS360(startDate,endDate[,method]) * - * @access public * @category Date/Time Functions * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * 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 * 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 @@ -783,12 +772,12 @@ class DateTime * TRUE: European method. Starting dates and ending dates that * occur on the 31st of a month become equal to the 30th of the * 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) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); + $startDate = Functions::flattenSingleValue($startDate); + $endDate = Functions::flattenSingleValue($endDate); if (is_string($startDate = self::getDateValue($startDate))) { return Functions::VALUE(); @@ -815,7 +804,6 @@ class DateTime return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method); } - /** * YEARFRAC * @@ -827,13 +815,12 @@ class DateTime * Excel Function: * YEARFRAC(startDate,endDate[,method]) * - * @access public * @category Date/Time Functions * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * 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 * 1 Actual/actual * 2 Actual/360 @@ -843,9 +830,9 @@ class DateTime */ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - $method = Functions::flattenSingleValue($method); + $startDate = Functions::flattenSingleValue($startDate); + $endDate = Functions::flattenSingleValue($endDate); + $method = Functions::flattenSingleValue($method); if (is_string($startDate = self::getDateValue($startDate))) { return Functions::VALUE(); @@ -871,7 +858,7 @@ class DateTime $endDay = self::DAYOFMONTH($endDate); if (($startMonth < 3) || (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) { - $leapDays += 1; + $leapDays += 1; } } } else { @@ -901,6 +888,7 @@ class DateTime } $leapDays /= $years; } + return $days / (365 + $leapDays); case 2: return self::DATEDIF($startDate, $endDate) / 360; @@ -910,10 +898,10 @@ class DateTime return self::DAYS360($startDate, $endDate, true) / 360; } } + return Functions::VALUE(); } - /** * NETWORKDAYS * @@ -925,7 +913,6 @@ class DateTime * Excel Function: * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) * - * @access public * @category Date/Time Functions * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string @@ -935,13 +922,13 @@ class DateTime * timestamp (integer), PHP DateTime object, or a standard date * strings that will be excluded from the working calendar, such * 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) { // Retrieve the mandatory start and end date that are referenced in the function definition - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); + $startDate = Functions::flattenSingleValue($startDate); + $endDate = Functions::flattenSingleValue($endDate); // 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()); array_shift($dateArgs); @@ -979,7 +966,7 @@ class DateTime } // Test any extra holiday parameters - $holidayCountedArray = array(); + $holidayCountedArray = []; foreach ($dateArgs as $holidayDate) { if (is_string($holidayDate = self::getDateValue($holidayDate))) { return Functions::VALUE(); @@ -995,10 +982,10 @@ class DateTime if ($sDate > $eDate) { return 0 - ($wholeWeekDays + $partWeekDays); } + return $wholeWeekDays + $partWeekDays; } - /** * WORKDAY * @@ -1010,11 +997,10 @@ class DateTime * Excel Function: * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) * - * @access public * @category Date/Time Functions * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * 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 * negative value yields a past 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) { // Retrieve the mandatory start date and days that are referenced in the function definition - $startDate = Functions::flattenSingleValue($startDate); - $endDays = Functions::flattenSingleValue($endDays); + $startDate = Functions::flattenSingleValue($startDate); + $endDays = Functions::flattenSingleValue($endDays); // 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()); array_shift($dateArgs); @@ -1065,7 +1051,7 @@ class DateTime // Test any extra holiday parameters if (!empty($dateArgs)) { - $holidayCountedArray = $holidayDates = array(); + $holidayCountedArray = $holidayDates = []; foreach ($dateArgs as $holidayDate) { if (($holidayDate !== null) && (trim($holidayDate) > '')) { if (is_string($holidayDate = self::getDateValue($holidayDate))) { @@ -1115,7 +1101,6 @@ class DateTime } } - /** * DAYOFMONTH * @@ -1131,7 +1116,7 @@ class DateTime */ public static function DAYOFMONTH($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); + $dateValue = Functions::flattenSingleValue($dateValue); if ($dateValue === null) { $dateValue = 1; @@ -1149,7 +1134,6 @@ class DateTime return (int) $PHPDateObject->format('j'); } - /** * DAYOFWEEK * @@ -1169,8 +1153,8 @@ class DateTime */ public static function DAYOFWEEK($dateValue = 1, $style = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - $style = Functions::flattenSingleValue($style); + $dateValue = Functions::flattenSingleValue($dateValue); + $style = Functions::flattenSingleValue($style); if (!is_numeric($style)) { return Functions::VALUE(); @@ -1222,7 +1206,6 @@ class DateTime return (int) $DoW; } - /** * WEEKOFYEAR * @@ -1238,15 +1221,15 @@ class DateTime * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * 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. * 2 Week begins on Monday. * @return int Week Number */ public static function WEEKOFYEAR($dateValue = 1, $method = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - $method = Functions::flattenSingleValue($method); + $dateValue = Functions::flattenSingleValue($dateValue); + $method = Functions::flattenSingleValue($method); if (!is_numeric($method)) { return Functions::VALUE(); @@ -1275,7 +1258,6 @@ class DateTime return (int) $weekOfYear; } - /** * MONTHOFYEAR * @@ -1291,7 +1273,7 @@ class DateTime */ public static function MONTHOFYEAR($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); + $dateValue = Functions::flattenSingleValue($dateValue); if (empty($dateValue)) { $dateValue = 1; @@ -1308,7 +1290,6 @@ class DateTime return (int) $PHPDateObject->format('n'); } - /** * YEAR * @@ -1324,7 +1305,7 @@ class DateTime */ public static function YEAR($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); + $dateValue = Functions::flattenSingleValue($dateValue); if ($dateValue === null) { $dateValue = 1; @@ -1340,7 +1321,6 @@ class DateTime return (int) $PHPDateObject->format('Y'); } - /** * HOUROFDAY * @@ -1356,7 +1336,7 @@ class DateTime */ public static function HOUROFDAY($timeValue = 0) { - $timeValue = Functions::flattenSingleValue($timeValue); + $timeValue = Functions::flattenSingleValue($timeValue); if (!is_numeric($timeValue)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { @@ -1381,7 +1361,6 @@ class DateTime return (int) gmdate('G', $timeValue); } - /** * MINUTEOFHOUR * @@ -1397,7 +1376,7 @@ class DateTime */ public static function MINUTEOFHOUR($timeValue = 0) { - $timeValue = $timeTester = Functions::flattenSingleValue($timeValue); + $timeValue = $timeTester = Functions::flattenSingleValue($timeValue); if (!is_numeric($timeValue)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { @@ -1422,7 +1401,6 @@ class DateTime return (int) gmdate('i', $timeValue); } - /** * SECONDOFMINUTE * @@ -1438,7 +1416,7 @@ class DateTime */ public static function SECONDOFMINUTE($timeValue = 0) { - $timeValue = Functions::flattenSingleValue($timeValue); + $timeValue = Functions::flattenSingleValue($timeValue); if (!is_numeric($timeValue)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { @@ -1463,7 +1441,6 @@ class DateTime return (int) gmdate('s', $timeValue); } - /** * EDATE * @@ -1485,8 +1462,8 @@ class DateTime */ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) { - $dateValue = Functions::flattenSingleValue($dateValue); - $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); + $dateValue = Functions::flattenSingleValue($dateValue); + $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); if (!is_numeric($adjustmentMonths)) { return Functions::VALUE(); @@ -1510,7 +1487,6 @@ class DateTime } } - /** * EOMONTH * @@ -1531,8 +1507,8 @@ class DateTime */ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) { - $dateValue = Functions::flattenSingleValue($dateValue); - $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); + $dateValue = Functions::flattenSingleValue($dateValue); + $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); if (!is_numeric($adjustmentMonths)) { return Functions::VALUE(); @@ -1544,7 +1520,7 @@ class DateTime } // Execute function - $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths+1); + $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths + 1); $adjustDays = (int) $PHPDateObject->format('d'); $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); diff --git a/src/PhpSpreadsheet/Calculation/Engineering.php b/src/PhpSpreadsheet/Calculation/Engineering.php index d760f8f8..d893f1a1 100644 --- a/src/PhpSpreadsheet/Calculation/Engineering.php +++ b/src/PhpSpreadsheet/Calculation/Engineering.php @@ -2,7 +2,7 @@ namespace PhpSpreadsheet\Calculation; -/** EULER */ +/* EULER */ define('EULER', 2.71828182845904523536); /** @@ -34,145 +34,145 @@ class Engineering * * @var mixed[] */ - private static $conversionUnits = array( - 'g' => array('Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => true), - 'sg' => array('Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => false), - 'lbm' => array('Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false), - 'u' => array('Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true), - 'ozm' => array('Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false), - 'm' => array('Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => true), - 'mi' => array('Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => false), - 'Nmi' => array('Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false), - 'in' => array('Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => false), - 'ft' => array('Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => false), - 'yd' => array('Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => false), - 'ang' => array('Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => true), - 'Pica' => array('Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false), - 'yr' => array('Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => false), - 'day' => array('Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => false), - 'hr' => array('Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => false), - 'mn' => array('Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => false), - 'sec' => array('Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => true), - 'Pa' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true), - 'p' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true), - 'atm' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true), - 'at' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true), - 'mmHg' => array('Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true), - 'N' => array('Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => true), - 'dyn' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true), - 'dy' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true), - 'lbf' => array('Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => false), - 'J' => array('Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => true), - 'e' => array('Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => true), - 'c' => array('Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true), - 'cal' => array('Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => true), - 'eV' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true), - 'ev' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true), - 'HPh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false), - 'hh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false), - 'Wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true), - 'wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true), - 'flb' => array('Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false), - 'BTU' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false), - 'btu' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false), - 'HP' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false), - 'h' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false), - 'W' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true), - 'w' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true), - 'T' => array('Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => true), - 'ga' => array('Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => true), - 'C' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false), - 'cel' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false), - 'F' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false), - 'fah' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false), - 'K' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false), - 'kel' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false), - 'tsp' => array('Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false), - 'tbs' => array('Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false), - 'oz' => array('Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false), - 'cup' => array('Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => false), - 'pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false), - 'us_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false), - 'uk_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false), - 'qt' => array('Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => false), - 'gal' => array('Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => false), - 'l' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true), - 'lt' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true), - ); + private static $conversionUnits = [ + 'g' => ['Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => true], + 'sg' => ['Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => false], + 'lbm' => ['Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], + 'u' => ['Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true], + 'ozm' => ['Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], + 'm' => ['Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => true], + 'mi' => ['Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => false], + 'Nmi' => ['Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false], + 'in' => ['Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => false], + 'ft' => ['Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => false], + 'yd' => ['Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => false], + 'ang' => ['Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => true], + 'Pica' => ['Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], + 'yr' => ['Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => false], + 'day' => ['Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => false], + 'hr' => ['Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => false], + 'mn' => ['Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => false], + 'sec' => ['Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => true], + 'Pa' => ['Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true], + 'p' => ['Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true], + 'atm' => ['Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], + 'at' => ['Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], + 'mmHg' => ['Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true], + 'N' => ['Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => true], + 'dyn' => ['Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true], + 'dy' => ['Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true], + 'lbf' => ['Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => false], + 'J' => ['Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => true], + 'e' => ['Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => true], + 'c' => ['Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true], + 'cal' => ['Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => true], + 'eV' => ['Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], + 'ev' => ['Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], + 'HPh' => ['Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], + 'hh' => ['Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], + 'Wh' => ['Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], + 'wh' => ['Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], + 'flb' => ['Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false], + 'BTU' => ['Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false], + 'btu' => ['Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false], + 'HP' => ['Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], + 'h' => ['Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], + 'W' => ['Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true], + 'w' => ['Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true], + 'T' => ['Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => true], + 'ga' => ['Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => true], + 'C' => ['Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false], + 'cel' => ['Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false], + 'F' => ['Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false], + 'fah' => ['Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false], + 'K' => ['Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], + 'kel' => ['Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], + 'tsp' => ['Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false], + 'tbs' => ['Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false], + 'oz' => ['Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false], + 'cup' => ['Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => false], + 'pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], + 'us_pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], + 'uk_pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false], + 'qt' => ['Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => false], + 'gal' => ['Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => false], + 'l' => ['Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true], + 'lt' => ['Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true], + ]; /** * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM() * * @var mixed[] */ - private static $conversionMultipliers = array( - 'Y' => array('multiplier' => 1E24, 'name' => 'yotta'), - 'Z' => array('multiplier' => 1E21, 'name' => 'zetta'), - 'E' => array('multiplier' => 1E18, 'name' => 'exa'), - 'P' => array('multiplier' => 1E15, 'name' => 'peta'), - 'T' => array('multiplier' => 1E12, 'name' => 'tera'), - 'G' => array('multiplier' => 1E9, 'name' => 'giga'), - 'M' => array('multiplier' => 1E6, 'name' => 'mega'), - 'k' => array('multiplier' => 1E3, 'name' => 'kilo'), - 'h' => array('multiplier' => 1E2, 'name' => 'hecto'), - 'e' => array('multiplier' => 1E1, 'name' => 'deka'), - 'd' => array('multiplier' => 1E-1, 'name' => 'deci'), - 'c' => array('multiplier' => 1E-2, 'name' => 'centi'), - 'm' => array('multiplier' => 1E-3, 'name' => 'milli'), - 'u' => array('multiplier' => 1E-6, 'name' => 'micro'), - 'n' => array('multiplier' => 1E-9, 'name' => 'nano'), - 'p' => array('multiplier' => 1E-12, 'name' => 'pico'), - 'f' => array('multiplier' => 1E-15, 'name' => 'femto'), - 'a' => array('multiplier' => 1E-18, 'name' => 'atto'), - 'z' => array('multiplier' => 1E-21, 'name' => 'zepto'), - 'y' => array('multiplier' => 1E-24, 'name' => 'yocto'), - ); + private static $conversionMultipliers = [ + 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], + 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], + 'E' => ['multiplier' => 1E18, 'name' => 'exa'], + 'P' => ['multiplier' => 1E15, 'name' => 'peta'], + 'T' => ['multiplier' => 1E12, 'name' => 'tera'], + 'G' => ['multiplier' => 1E9, 'name' => 'giga'], + 'M' => ['multiplier' => 1E6, 'name' => 'mega'], + 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], + 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], + 'e' => ['multiplier' => 1E1, 'name' => 'deka'], + 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], + 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], + 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], + 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], + 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], + 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], + 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], + 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], + 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], + 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], + ]; /** * Details of the Units of measure conversion factors, organised by group * * @var mixed[] */ - private static $unitConversions = array( - 'Mass' => array( - 'g' => array( + private static $unitConversions = [ + 'Mass' => [ + 'g' => [ 'g' => 1.0, 'sg' => 6.85220500053478E-05, 'lbm' => 2.20462291469134E-03, 'u' => 6.02217000000000E+23, 'ozm' => 3.52739718003627E-02, - ), - 'sg' => array( + ], + 'sg' => [ 'g' => 1.45938424189287E+04, 'sg' => 1.0, 'lbm' => 3.21739194101647E+01, 'u' => 8.78866000000000E+27, 'ozm' => 5.14782785944229E+02, - ), - 'lbm' => array( + ], + 'lbm' => [ 'g' => 4.5359230974881148E+02, 'sg' => 3.10810749306493E-02, 'lbm' => 1.0, 'u' => 2.73161000000000E+26, 'ozm' => 1.60000023429410E+01, - ), - 'u' => array( + ], + 'u' => [ 'g' => 1.66053100460465E-24, 'sg' => 1.13782988532950E-28, 'lbm' => 3.66084470330684E-27, 'u' => 1.0, 'ozm' => 5.85735238300524E-26, - ), - 'ozm' => array( + ], + 'ozm' => [ 'g' => 2.83495152079732E+01, 'sg' => 1.94256689870811E-03, 'lbm' => 6.24999908478882E-02, 'u' => 1.70725600000000E+25, 'ozm' => 1.0, - ), - ), - 'Distance' => array( - 'm' => array( + ], + ], + 'Distance' => [ + 'm' => [ 'm' => 1.0, 'mi' => 6.21371192237334E-04, 'Nmi' => 5.39956803455724E-04, @@ -181,8 +181,8 @@ class Engineering 'yd' => 1.09361329797891E+00, 'ang' => 1.00000000000000E+10, 'Pica' => 2.83464566929116E+03, - ), - 'mi' => array( + ], + 'mi' => [ 'm' => 1.60934400000000E+03, 'mi' => 1.0, 'Nmi' => 8.68976241900648E-01, @@ -191,8 +191,8 @@ class Engineering 'yd' => 1.76000000000000E+03, 'ang' => 1.60934400000000E+13, 'Pica' => 4.56191999999971E+06, - ), - 'Nmi' => array( + ], + 'Nmi' => [ 'm' => 1.85200000000000E+03, 'mi' => 1.15077944802354E+00, 'Nmi' => 1.0, @@ -201,8 +201,8 @@ class Engineering 'yd' => 2.02537182785694E+03, 'ang' => 1.85200000000000E+13, 'Pica' => 5.24976377952723E+06, - ), - 'in' => array( + ], + 'in' => [ 'm' => 2.54000000000000E-02, 'mi' => 1.57828282828283E-05, 'Nmi' => 1.37149028077754E-05, @@ -211,8 +211,8 @@ class Engineering 'yd' => 2.77777777686643E-02, 'ang' => 2.54000000000000E+08, 'Pica' => 7.19999999999955E+01, - ), - 'ft' => array( + ], + 'ft' => [ 'm' => 3.04800000000000E-01, 'mi' => 1.89393939393939E-04, 'Nmi' => 1.64578833693305E-04, @@ -221,8 +221,8 @@ class Engineering 'yd' => 3.33333333223972E-01, 'ang' => 3.04800000000000E+09, 'Pica' => 8.63999999999946E+02, - ), - 'yd' => array( + ], + 'yd' => [ 'm' => 9.14400000300000E-01, 'mi' => 5.68181818368230E-04, 'Nmi' => 4.93736501241901E-04, @@ -231,8 +231,8 @@ class Engineering 'yd' => 1.0, 'ang' => 9.14400000300000E+09, 'Pica' => 2.59200000085023E+03, - ), - 'ang' => array( + ], + 'ang' => [ 'm' => 1.00000000000000E-10, 'mi' => 6.21371192237334E-14, 'Nmi' => 5.39956803455724E-14, @@ -241,8 +241,8 @@ class Engineering 'yd' => 1.09361329797891E-10, 'ang' => 1.0, 'Pica' => 2.83464566929116E-07, - ), - 'Pica' => array( + ], + 'Pica' => [ 'm' => 3.52777777777800E-04, 'mi' => 2.19205948372629E-07, 'Nmi' => 1.90484761219114E-07, @@ -251,110 +251,110 @@ class Engineering 'yd' => 3.85802469009251E-04, 'ang' => 3.52777777777800E+06, 'Pica' => 1.0, - ), - ), - 'Time' => array( - 'yr' => array( + ], + ], + 'Time' => [ + 'yr' => [ 'yr' => 1.0, 'day' => 365.25, 'hr' => 8766.0, 'mn' => 525960.0, 'sec' => 31557600.0, - ), - 'day' => array( + ], + 'day' => [ 'yr' => 2.73785078713210E-03, 'day' => 1.0, 'hr' => 24.0, 'mn' => 1440.0, 'sec' => 86400.0, - ), - 'hr' => array( + ], + 'hr' => [ 'yr' => 1.14077116130504E-04, 'day' => 4.16666666666667E-02, 'hr' => 1.0, 'mn' => 60.0, 'sec' => 3600.0, - ), - 'mn' => array( + ], + 'mn' => [ 'yr' => 1.90128526884174E-06, 'day' => 6.94444444444444E-04, 'hr' => 1.66666666666667E-02, 'mn' => 1.0, 'sec' => 60.0, - ), - 'sec' => array( + ], + 'sec' => [ 'yr' => 3.16880878140289E-08, 'day' => 1.15740740740741E-05, 'hr' => 2.77777777777778E-04, 'mn' => 1.66666666666667E-02, 'sec' => 1.0, - ), - ), - 'Pressure' => array( - 'Pa' => array( + ], + ], + 'Pressure' => [ + 'Pa' => [ 'Pa' => 1.0, 'p' => 1.0, 'atm' => 9.86923299998193E-06, 'at' => 9.86923299998193E-06, 'mmHg' => 7.50061707998627E-03, - ), - 'p' => array( + ], + 'p' => [ 'Pa' => 1.0, 'p' => 1.0, 'atm' => 9.86923299998193E-06, 'at' => 9.86923299998193E-06, 'mmHg' => 7.50061707998627E-03, - ), - 'atm' => array( + ], + 'atm' => [ 'Pa' => 1.01324996583000E+05, 'p' => 1.01324996583000E+05, 'atm' => 1.0, 'at' => 1.0, 'mmHg' => 760.0, - ), - 'at' => array( + ], + 'at' => [ 'Pa' => 1.01324996583000E+05, 'p' => 1.01324996583000E+05, 'atm' => 1.0, 'at' => 1.0, 'mmHg' => 760.0, - ), - 'mmHg' => array( + ], + 'mmHg' => [ 'Pa' => 1.33322363925000E+02, 'p' => 1.33322363925000E+02, 'atm' => 1.31578947368421E-03, 'at' => 1.31578947368421E-03, 'mmHg' => 1.0, - ), - ), - 'Force' => array( - 'N' => array( + ], + ], + 'Force' => [ + 'N' => [ 'N' => 1.0, 'dyn' => 1.0E+5, 'dy' => 1.0E+5, 'lbf' => 2.24808923655339E-01, - ), - 'dyn' => array( + ], + 'dyn' => [ 'N' => 1.0E-5, 'dyn' => 1.0, 'dy' => 1.0, 'lbf' => 2.24808923655339E-06, - ), - 'dy' => array( + ], + 'dy' => [ 'N' => 1.0E-5, 'dyn' => 1.0, 'dy' => 1.0, 'lbf' => 2.24808923655339E-06, - ), - 'lbf' => array( + ], + 'lbf' => [ 'N' => 4.448222, 'dyn' => 4.448222E+5, 'dy' => 4.448222E+5, 'lbf' => 1.0, - ), - ), - 'Energy' => array( - 'J' => array( + ], + ], + 'Energy' => [ + 'J' => [ 'J' => 1.0, 'e' => 9.99999519343231E+06, 'c' => 2.39006249473467E-01, @@ -368,8 +368,8 @@ class Engineering 'flb' => 2.37304222192651E+01, 'BTU' => 9.47815067349015E-04, 'btu' => 9.47815067349015E-04, - ), - 'e' => array( + ], + 'e' => [ 'J' => 1.00000048065700E-07, 'e' => 1.0, 'c' => 2.39006364353494E-08, @@ -383,8 +383,8 @@ class Engineering 'flb' => 2.37304336254586E-06, 'BTU' => 9.47815522922962E-11, 'btu' => 9.47815522922962E-11, - ), - 'c' => array( + ], + 'c' => [ 'J' => 4.18399101363672E+00, 'e' => 4.18398900257312E+07, 'c' => 1.0, @@ -398,8 +398,8 @@ class Engineering 'flb' => 9.92878733152102E+01, 'BTU' => 3.96564972437776E-03, 'btu' => 3.96564972437776E-03, - ), - 'cal' => array( + ], + 'cal' => [ 'J' => 4.18679484613929E+00, 'e' => 4.18679283372801E+07, 'c' => 1.00067013349059E+00, @@ -413,8 +413,8 @@ class Engineering 'flb' => 9.93544094443283E+01, 'BTU' => 3.96830723907002E-03, 'btu' => 3.96830723907002E-03, - ), - 'eV' => array( + ], + 'eV' => [ 'J' => 1.60219000146921E-19, 'e' => 1.60218923136574E-12, 'c' => 3.82933423195043E-20, @@ -428,8 +428,8 @@ class Engineering 'flb' => 3.80206452103492E-18, 'BTU' => 1.51857982414846E-22, 'btu' => 1.51857982414846E-22, - ), - 'ev' => array( + ], + 'ev' => [ 'J' => 1.60219000146921E-19, 'e' => 1.60218923136574E-12, 'c' => 3.82933423195043E-20, @@ -443,8 +443,8 @@ class Engineering 'flb' => 3.80206452103492E-18, 'BTU' => 1.51857982414846E-22, 'btu' => 1.51857982414846E-22, - ), - 'HPh' => array( + ], + 'HPh' => [ 'J' => 2.68451741316170E+06, 'e' => 2.68451612283024E+13, 'c' => 6.41616438565991E+05, @@ -458,8 +458,8 @@ class Engineering 'flb' => 6.37047316692964E+07, 'BTU' => 2.54442605275546E+03, 'btu' => 2.54442605275546E+03, - ), - 'hh' => array( + ], + 'hh' => [ 'J' => 2.68451741316170E+06, 'e' => 2.68451612283024E+13, 'c' => 6.41616438565991E+05, @@ -473,8 +473,8 @@ class Engineering 'flb' => 6.37047316692964E+07, 'BTU' => 2.54442605275546E+03, 'btu' => 2.54442605275546E+03, - ), - 'Wh' => array( + ], + 'Wh' => [ 'J' => 3.59999820554720E+03, 'e' => 3.59999647518369E+10, 'c' => 8.60422069219046E+02, @@ -488,8 +488,8 @@ class Engineering 'flb' => 8.54294774062316E+04, 'BTU' => 3.41213254164705E+00, 'btu' => 3.41213254164705E+00, - ), - 'wh' => array( + ], + 'wh' => [ 'J' => 3.59999820554720E+03, 'e' => 3.59999647518369E+10, 'c' => 8.60422069219046E+02, @@ -503,8 +503,8 @@ class Engineering 'flb' => 8.54294774062316E+04, 'BTU' => 3.41213254164705E+00, 'btu' => 3.41213254164705E+00, - ), - 'flb' => array( + ], + 'flb' => [ 'J' => 4.21400003236424E-02, 'e' => 4.21399800687660E+05, 'c' => 1.00717234301644E-02, @@ -518,8 +518,8 @@ class Engineering 'flb' => 1.0, 'BTU' => 3.99409272448406E-05, 'btu' => 3.99409272448406E-05, - ), - 'BTU' => array( + ], + 'BTU' => [ 'J' => 1.05505813786749E+03, 'e' => 1.05505763074665E+10, 'c' => 2.52165488508168E+02, @@ -533,8 +533,8 @@ class Engineering 'flb' => 2.50369750774671E+04, 'BTU' => 1.0, 'btu' => 1.0, - ), - 'btu' => array( + ], + 'btu' => [ 'J' => 1.05505813786749E+03, 'e' => 1.05505763074665E+10, 'c' => 2.52165488508168E+02, @@ -548,46 +548,46 @@ class Engineering 'flb' => 2.50369750774671E+04, 'BTU' => 1.0, 'btu' => 1.0, - ), - ), - 'Power' => array( - 'HP' => array( + ], + ], + 'Power' => [ + 'HP' => [ 'HP' => 1.0, 'h' => 1.0, 'W' => 7.45701000000000E+02, 'w' => 7.45701000000000E+02, - ), - 'h' => array( + ], + 'h' => [ 'HP' => 1.0, 'h' => 1.0, 'W' => 7.45701000000000E+02, 'w' => 7.45701000000000E+02, - ), - 'W' => array( + ], + 'W' => [ 'HP' => 1.34102006031908E-03, 'h' => 1.34102006031908E-03, 'W' => 1.0, 'w' => 1.0, - ), - 'w' => array( + ], + 'w' => [ 'HP' => 1.34102006031908E-03, 'h' => 1.34102006031908E-03, 'W' => 1.0, 'w' => 1.0, - ), - ), - 'Magnetism' => array( - 'T' => array( + ], + ], + 'Magnetism' => [ + 'T' => [ 'T' => 1.0, 'ga' => 10000.0, - ), - 'ga' => array( + ], + 'ga' => [ 'T' => 0.0001, 'ga' => 1.0, - ), - ), - 'Liquid' => array( - 'tsp' => array( + ], + ], + 'Liquid' => [ + 'tsp' => [ 'tsp' => 1.0, 'tbs' => 3.33333333333333E-01, 'oz' => 1.66666666666667E-01, @@ -599,8 +599,8 @@ class Engineering 'gal' => 1.30208333333333E-03, 'l' => 4.92999408400710E-03, 'lt' => 4.92999408400710E-03, - ), - 'tbs' => array( + ], + 'tbs' => [ 'tsp' => 3.00000000000000E+00, 'tbs' => 1.0, 'oz' => 5.00000000000000E-01, @@ -612,8 +612,8 @@ class Engineering 'gal' => 3.90625000000000E-03, 'l' => 1.47899822520213E-02, 'lt' => 1.47899822520213E-02, - ), - 'oz' => array( + ], + 'oz' => [ 'tsp' => 6.00000000000000E+00, 'tbs' => 2.00000000000000E+00, 'oz' => 1.0, @@ -625,8 +625,8 @@ class Engineering 'gal' => 7.81250000000000E-03, 'l' => 2.95799645040426E-02, 'lt' => 2.95799645040426E-02, - ), - 'cup' => array( + ], + 'cup' => [ 'tsp' => 4.80000000000000E+01, 'tbs' => 1.60000000000000E+01, 'oz' => 8.00000000000000E+00, @@ -638,8 +638,8 @@ class Engineering 'gal' => 6.25000000000000E-02, 'l' => 2.36639716032341E-01, 'lt' => 2.36639716032341E-01, - ), - 'pt' => array( + ], + 'pt' => [ 'tsp' => 9.60000000000000E+01, 'tbs' => 3.20000000000000E+01, 'oz' => 1.60000000000000E+01, @@ -651,8 +651,8 @@ class Engineering 'gal' => 1.25000000000000E-01, 'l' => 4.73279432064682E-01, 'lt' => 4.73279432064682E-01, - ), - 'us_pt' => array( + ], + 'us_pt' => [ 'tsp' => 9.60000000000000E+01, 'tbs' => 3.20000000000000E+01, 'oz' => 1.60000000000000E+01, @@ -664,8 +664,8 @@ class Engineering 'gal' => 1.25000000000000E-01, 'l' => 4.73279432064682E-01, 'lt' => 4.73279432064682E-01, - ), - 'uk_pt' => array( + ], + 'uk_pt' => [ 'tsp' => 1.15266000000000E+02, 'tbs' => 3.84220000000000E+01, 'oz' => 1.92110000000000E+01, @@ -677,8 +677,8 @@ class Engineering 'gal' => 1.50085937500000E-01, 'l' => 5.68260698087162E-01, 'lt' => 5.68260698087162E-01, - ), - 'qt' => array( + ], + 'qt' => [ 'tsp' => 1.92000000000000E+02, 'tbs' => 6.40000000000000E+01, 'oz' => 3.20000000000000E+01, @@ -690,8 +690,8 @@ class Engineering 'gal' => 2.50000000000000E-01, 'l' => 9.46558864129363E-01, 'lt' => 9.46558864129363E-01, - ), - 'gal' => array( + ], + 'gal' => [ 'tsp' => 7.68000000000000E+02, 'tbs' => 2.56000000000000E+02, 'oz' => 1.28000000000000E+02, @@ -703,8 +703,8 @@ class Engineering 'gal' => 1.0, 'l' => 3.78623545651745E+00, 'lt' => 3.78623545651745E+00, - ), - 'l' => array( + ], + 'l' => [ 'tsp' => 2.02840000000000E+02, 'tbs' => 6.76133333333333E+01, 'oz' => 3.38066666666667E+01, @@ -716,8 +716,8 @@ class Engineering 'gal' => 2.64114583333333E-01, 'l' => 1.0, 'lt' => 1.0, - ), - 'lt' => array( + ], + 'lt' => [ 'tsp' => 2.02840000000000E+02, 'tbs' => 6.76133333333333E+01, 'oz' => 3.38066666666667E+01, @@ -729,10 +729,9 @@ class Engineering 'gal' => 2.64114583333333E-01, 'l' => 1.0, 'lt' => 1.0, - ), - ), - ); - + ], + ], + ]; /** * parseComplex @@ -744,7 +743,7 @@ class Engineering */ public static function parseComplex($complexNumber) { - $workString = (string)$complexNumber; + $workString = (string) $complexNumber; $realNumber = $imaginary = 0; // Extract the suffix, if there is one @@ -783,14 +782,13 @@ class Engineering } } - return array( + return [ 'real' => $realNumber, 'imaginary' => $imaginary, - 'suffix' => $suffix - ); + 'suffix' => $suffix, + ]; } - /** * Cleans the leading characters in a complex number string * @@ -811,6 +809,7 @@ class Engineering if ($complexNumber{0} == '+') { $complexNumber = substr($complexNumber, 1); } + return $complexNumber; } @@ -818,14 +817,14 @@ class Engineering * Formats a number base string value with leading zeroes * * @param string $xVal The "number" to pad - * @param integer $places The length that we want to pad this value + * @param int $places The length that we want to pad this value * @return string The padded "number" */ private static function nbrConversionFormat($xVal, $places) { if (!is_null($places)) { if (is_numeric($places)) { - $places = (int)$places; + $places = (int) $places; } else { return Functions::VALUE(); } @@ -851,16 +850,14 @@ class Engineering * Excel Function: * BESSELI(x,ord) * - * @access public * @category Engineering Functions * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELI returns the #VALUE! error value. - * @param integer $ord The order of the Bessel function. + * @param int $ord The order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELI returns the #VALUE! error value. * If $ord < 0, BESSELI returns the #NUM! error value. * @return float - * */ public static function BESSELI($x, $ord) { @@ -891,12 +888,13 @@ class Engineering $fResult = -$fResult; } } + return (is_nan($fResult)) ? Functions::NAN() : $fResult; } + return Functions::VALUE(); } - /** * BESSELJ * @@ -905,15 +903,13 @@ class Engineering * Excel Function: * BESSELJ(x,ord) * - * @access public * @category Engineering Functions * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELJ returns the #VALUE! error value. - * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. * If $ord < 0, BESSELJ returns the #NUM! error value. * @return float - * */ public static function BESSELJ($x, $ord) { @@ -946,12 +942,13 @@ class Engineering $fResult = -$fResult; } } + return (is_nan($fResult)) ? Functions::NAN() : $fResult; } + return Functions::VALUE(); } - private static function besselK0($fNum) { if ($fNum <= 2) { @@ -966,10 +963,10 @@ class Engineering (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); } + return $fRet; } - private static function besselK1($fNum) { if ($fNum <= 2) { @@ -984,10 +981,10 @@ class Engineering (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * (0.325614e-2 + $y * (-0.68245e-3))))))); } + return $fRet; } - /** * BESSELK * @@ -997,15 +994,13 @@ class Engineering * Excel Function: * BESSELK(x,ord) * - * @access public * @category Engineering Functions * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELK returns the #VALUE! error value. - * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. * If $ord < 0, BESSELK returns the #NUM! error value. * @return float - * */ public static function BESSELK($x, $ord) { @@ -1034,12 +1029,13 @@ class Engineering $fBk = $fBkp; } } + return (is_nan($fBk)) ? Functions::NAN() : $fBk; } + return Functions::VALUE(); } - private static function besselY0($fNum) { if ($fNum < 8.0) { @@ -1055,10 +1051,10 @@ class Engineering $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2); } + return $fRet; } - private static function besselY1($fNum) { if ($fNum < 8.0) { @@ -1071,10 +1067,10 @@ class Engineering } else { $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491); } + return $fRet; } - /** * BESSELY * @@ -1083,11 +1079,10 @@ class Engineering * Excel Function: * BESSELY(x,ord) * - * @access public * @category Engineering Functions * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELK returns the #VALUE! error value. - * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. * If $ord < 0, BESSELK returns the #NUM! error value. * @@ -1120,12 +1115,13 @@ class Engineering $fBy = $fByp; } } + return (is_nan($fBy)) ? Functions::NAN() : $fBy; } + return Functions::VALUE(); } - /** * BINTODEC * @@ -1134,7 +1130,6 @@ class Engineering * Excel Function: * BIN2DEC(x) * - * @access public * @category Engineering Functions * @param string $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant @@ -1150,7 +1145,7 @@ class Engineering if (is_bool($x)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int)$x; + $x = (int) $x; } else { return Functions::VALUE(); } @@ -1158,7 +1153,7 @@ class Engineering if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { $x = floor($x); } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { return Functions::NAN(); } @@ -1167,12 +1162,13 @@ class Engineering } elseif (strlen($x) == 10) { // Two's Complement $x = substr($x, -9); + return '-' . (512 - bindec($x)); } + return bindec($x); } - /** * BINTOHEX * @@ -1181,7 +1177,6 @@ class Engineering * Excel Function: * BIN2HEX(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant @@ -1189,7 +1184,7 @@ class Engineering * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the + * @param int $places The number of characters to use. If places is omitted, BIN2HEX uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1205,7 +1200,7 @@ class Engineering // Argument X if (is_bool($x)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int)$x; + $x = (int) $x; } else { return Functions::VALUE(); } @@ -1213,7 +1208,7 @@ class Engineering if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { $x = floor($x); } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { return Functions::NAN(); } @@ -1223,12 +1218,11 @@ class Engineering // Two's Complement return str_repeat('F', 8) . substr(strtoupper(dechex(bindec(substr($x, -9)))), -2); } - $hexVal = (string)strtoupper(dechex(bindec($x))); + $hexVal = (string) strtoupper(dechex(bindec($x))); return self::nbrConversionFormat($hexVal, $places); } - /** * BINTOOCT * @@ -1237,7 +1231,6 @@ class Engineering * Excel Function: * BIN2OCT(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant @@ -1245,7 +1238,7 @@ class Engineering * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the + * @param int $places The number of characters to use. If places is omitted, BIN2OCT uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1260,7 +1253,7 @@ class Engineering if (is_bool($x)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int)$x; + $x = (int) $x; } else { return Functions::VALUE(); } @@ -1268,7 +1261,7 @@ class Engineering if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { $x = floor($x); } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { return Functions::NAN(); } @@ -1278,12 +1271,11 @@ class Engineering // Two's Complement return str_repeat('7', 7) . substr(strtoupper(decoct(bindec(substr($x, -9)))), -3); } - $octVal = (string)decoct(bindec($x)); + $octVal = (string) decoct(bindec($x)); return self::nbrConversionFormat($octVal, $places); } - /** * DECTOBIN * @@ -1292,7 +1284,6 @@ class Engineering * Excel Function: * DEC2BIN(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The decimal integer you want to convert. If number is negative, * valid place values are ignored and DEC2BIN returns a 10-character @@ -1304,7 +1295,7 @@ class Engineering * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. * If DEC2BIN requires more than places characters, it returns the #NUM! * error value. - * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses + * @param int $places The number of characters to use. If places is omitted, DEC2BIN uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1319,17 +1310,17 @@ class Engineering if (is_bool($x)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int)$x; + $x = (int) $x; } else { return Functions::VALUE(); } } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { return Functions::VALUE(); } - $x = (string)floor($x); + $x = (string) floor($x); if ($x < -512 || $x > 511) { return Functions::NAN(); } @@ -1344,7 +1335,6 @@ class Engineering return self::nbrConversionFormat($r, $places); } - /** * DECTOHEX * @@ -1353,7 +1343,6 @@ class Engineering * Excel Function: * DEC2HEX(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2HEX returns a 10-character (40-bit) @@ -1365,7 +1354,7 @@ class Engineering * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. * If DEC2HEX requires more than places characters, it returns the * #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses + * @param int $places The number of characters to use. If places is omitted, DEC2HEX uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1380,16 +1369,16 @@ class Engineering if (is_bool($x)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int)$x; + $x = (int) $x; } else { return Functions::VALUE(); } } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { return Functions::VALUE(); } - $x = (string)floor($x); + $x = (string) floor($x); $r = strtoupper(dechex($x)); if (strlen($r) == 8) { // Two's Complement @@ -1399,7 +1388,6 @@ class Engineering return self::nbrConversionFormat($r, $places); } - /** * DECTOOCT * @@ -1408,7 +1396,6 @@ class Engineering * Excel Function: * DEC2OCT(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2OCT returns a 10-character (30-bit) @@ -1420,7 +1407,7 @@ class Engineering * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. * If DEC2OCT requires more than places characters, it returns the * #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses + * @param int $places The number of characters to use. If places is omitted, DEC2OCT uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1436,16 +1423,16 @@ class Engineering if (is_bool($x)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int)$x; + $x = (int) $x; } else { return Functions::VALUE(); } } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { return Functions::VALUE(); } - $x = (string)floor($x); + $x = (string) floor($x); $r = decoct($x); if (strlen($r) == 11) { // Two's Complement @@ -1455,7 +1442,6 @@ class Engineering return self::nbrConversionFormat($r, $places); } - /** * HEXTOBIN * @@ -1464,7 +1450,6 @@ class Engineering * Excel Function: * HEX2BIN(x[,places]) * - * @access public * @category Engineering Functions * @param string $x the hexadecimal number you want to convert. * Number cannot contain more than 10 characters. @@ -1476,7 +1461,7 @@ class Engineering * and if number is positive, it cannot be greater than 1FF. * If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. * If HEX2BIN requires more than places characters, it returns the #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, + * @param int $places The number of characters to use. If places is omitted, * HEX2BIN uses the minimum number of characters necessary. Places * is useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1492,7 +1477,7 @@ class Engineering if (is_bool($x)) { return Functions::VALUE(); } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { return Functions::NAN(); } @@ -1500,7 +1485,6 @@ class Engineering return self::DECTOBIN(self::HEXTODEC($x), $places); } - /** * HEXTODEC * @@ -1509,7 +1493,6 @@ class Engineering * Excel Function: * HEX2DEC(x) * - * @access public * @category Engineering Functions * @param string $x The hexadecimal number you want to convert. This number cannot * contain more than 10 characters (40 bits). The most significant @@ -1527,12 +1510,12 @@ class Engineering if (is_bool($x)) { return Functions::VALUE(); } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { return Functions::NAN(); } - if (strlen($x)> 10) { + if (strlen($x) > 10) { return Functions::NAN(); } @@ -1541,15 +1524,16 @@ class Engineering $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); } if (strlen($binX) == 40 && $binX[0] == '1') { - for ($i = 0; $i < 40; $i++) { + for ($i = 0; $i < 40; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } + return (bindec($binX) + 1) * -1; } + return bindec($binX); } - /** * HEXTOOCT * @@ -1558,7 +1542,6 @@ class Engineering * Excel Function: * HEX2OCT(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The hexadecimal number you want to convert. Number cannot * contain more than 10 characters. The most significant bit of @@ -1573,7 +1556,7 @@ class Engineering * the #NUM! error value. * If HEX2OCT requires more than places characters, it returns * the #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, HEX2OCT + * @param int $places The number of characters to use. If places is omitted, HEX2OCT * uses the minimum number of characters necessary. Places is * useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1590,7 +1573,7 @@ class Engineering if (is_bool($x)) { return Functions::VALUE(); } - $x = (string)$x; + $x = (string) $x; if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { return Functions::NAN(); } @@ -1611,7 +1594,6 @@ class Engineering * Excel Function: * OCT2BIN(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The octal number you want to convert. Number may not * contain more than 10 characters. The most significant @@ -1626,7 +1608,7 @@ class Engineering * the #NUM! error value. * If OCT2BIN requires more than places characters, it * returns the #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, + * @param int $places The number of characters to use. If places is omitted, * OCT2BIN uses the minimum number of characters necessary. * Places is useful for padding the return value with * leading 0s (zeros). @@ -1645,7 +1627,7 @@ class Engineering if (is_bool($x)) { return Functions::VALUE(); } - $x = (string)$x; + $x = (string) $x; if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { return Functions::NAN(); } @@ -1653,7 +1635,6 @@ class Engineering return self::DECTOBIN(self::OCTTODEC($x), $places); } - /** * OCTTODEC * @@ -1662,7 +1643,6 @@ class Engineering * Excel Function: * OCT2DEC(x) * - * @access public * @category Engineering Functions * @param string $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant @@ -1680,20 +1660,22 @@ class Engineering if (is_bool($x)) { return Functions::VALUE(); } - $x = (string)$x; + $x = (string) $x; if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { return Functions::NAN(); } $binX = ''; foreach (str_split($x) as $char) { - $binX .= str_pad(decbin((int)$char), 3, '0', STR_PAD_LEFT); + $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); } if (strlen($binX) == 30 && $binX[0] == '1') { - for ($i = 0; $i < 30; $i++) { + for ($i = 0; $i < 30; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } + return (bindec($binX) + 1) * -1; } + return bindec($binX); } @@ -1705,7 +1687,6 @@ class Engineering * Excel Function: * OCT2HEX(x[,places]) * - * @access public * @category Engineering Functions * @param string $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant @@ -1718,7 +1699,7 @@ class Engineering * #NUM! error value. * If OCT2HEX requires more than places characters, it returns * the #NUM! error value. - * @param integer $places The number of characters to use. If places is omitted, OCT2HEX + * @param int $places The number of characters to use. If places is omitted, OCT2HEX * uses the minimum number of characters necessary. Places is useful * for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1734,7 +1715,7 @@ class Engineering if (is_bool($x)) { return Functions::VALUE(); } - $x = (string)$x; + $x = (string) $x; if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { return Functions::NAN(); } @@ -1743,7 +1724,6 @@ class Engineering return self::nbrConversionFormat($hexVal, $places); } - /** * COMPLEX * @@ -1752,7 +1732,6 @@ class Engineering * Excel Function: * COMPLEX(realNumber,imaginary[,places]) * - * @access public * @category Engineering Functions * @param float $realNumber The real coefficient of the complex number. * @param float $imaginary The imaginary coefficient of the complex number. @@ -1769,38 +1748,39 @@ class Engineering if (((is_numeric($realNumber)) && (is_numeric($imaginary))) && (($suffix == 'i') || ($suffix == 'j') || ($suffix == '')) ) { - $realNumber = (float)$realNumber; - $imaginary = (float)$imaginary; + $realNumber = (float) $realNumber; + $imaginary = (float) $imaginary; if ($suffix == '') { $suffix = 'i'; } if ($realNumber == 0.0) { if ($imaginary == 0.0) { - return (string)'0'; + return (string) '0'; } elseif ($imaginary == 1.0) { - return (string)$suffix; + return (string) $suffix; } elseif ($imaginary == -1.0) { - return (string)'-' . $suffix; + return (string) '-' . $suffix; } - return (string)$imaginary . $suffix; + + return (string) $imaginary . $suffix; } elseif ($imaginary == 0.0) { - return (string)$realNumber; + return (string) $realNumber; } elseif ($imaginary == 1.0) { - return (string)$realNumber . '+' . $suffix; + return (string) $realNumber . '+' . $suffix; } elseif ($imaginary == -1.0) { - return (string)$realNumber . '-' . $suffix; + return (string) $realNumber . '-' . $suffix; } if ($imaginary > 0) { - $imaginary = (string)'+' . $imaginary; + $imaginary = (string) '+' . $imaginary; } - return (string)$realNumber . $imaginary . $suffix; + + return (string) $realNumber . $imaginary . $suffix; } return Functions::VALUE(); } - /** * IMAGINARY * @@ -1809,7 +1789,6 @@ class Engineering * Excel Function: * IMAGINARY(complexNumber) * - * @access public * @category Engineering Functions * @param string $complexNumber The complex number for which you want the imaginary * coefficient. @@ -1820,10 +1799,10 @@ class Engineering $complexNumber = Functions::flattenSingleValue($complexNumber); $parsedComplex = self::parseComplex($complexNumber); + return $parsedComplex['imaginary']; } - /** * IMREAL * @@ -1832,7 +1811,6 @@ class Engineering * Excel Function: * IMREAL(complexNumber) * - * @access public * @category Engineering Functions * @param string $complexNumber The complex number for which you want the real coefficient. * @return float @@ -1842,10 +1820,10 @@ class Engineering $complexNumber = Functions::flattenSingleValue($complexNumber); $parsedComplex = self::parseComplex($complexNumber); + return $parsedComplex['real']; } - /** * IMABS * @@ -1869,7 +1847,6 @@ class Engineering ); } - /** * IMARGUMENT * @@ -1903,7 +1880,6 @@ class Engineering } } - /** * IMCONJUGATE * @@ -1934,7 +1910,6 @@ class Engineering } } - /** * IMCOS * @@ -1965,7 +1940,6 @@ class Engineering } } - /** * IMSIN * @@ -1994,7 +1968,6 @@ class Engineering } } - /** * IMSQRT * @@ -2024,7 +1997,6 @@ class Engineering } } - /** * IMLN * @@ -2056,7 +2028,6 @@ class Engineering } } - /** * IMLOG10 * @@ -2083,7 +2054,6 @@ class Engineering return self::IMPRODUCT(log10(EULER), self::IMLN($complexNumber)); } - /** * IMLOG2 * @@ -2110,7 +2080,6 @@ class Engineering return self::IMPRODUCT(log(EULER, 2), self::IMLN($complexNumber)); } - /** * IMEXP * @@ -2143,7 +2112,6 @@ class Engineering } } - /** * IMPOWER * @@ -2179,7 +2147,6 @@ class Engineering } } - /** * IMDIV * @@ -2225,7 +2192,6 @@ class Engineering } } - /** * IMSUB * @@ -2260,7 +2226,6 @@ class Engineering return self::COMPLEX($d1, $d2, $parsedComplex1['suffix']); } - /** * IMSUM * @@ -2296,10 +2261,10 @@ class Engineering if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; } + return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix); } - /** * IMPRODUCT * @@ -2335,10 +2300,10 @@ class Engineering if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; } + return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix); } - /** * DELTA * @@ -2359,10 +2324,9 @@ class Engineering $a = Functions::flattenSingleValue($a); $b = Functions::flattenSingleValue($b); - return (int)($a == $b); + return (int) ($a == $b); } - /** * GESTEP * @@ -2383,10 +2347,9 @@ class Engineering $number = Functions::flattenSingleValue($number); $step = Functions::flattenSingleValue($step); - return (int)($number >= $step); + return (int) ($number >= $step); } - // // Private method to calculate the erf value // @@ -2411,10 +2374,10 @@ class Engineering break; } } while (abs($term / $sum) > PRECISION); + return self::$twoSqrtPi * $sum; } - /** * ERF * @@ -2446,10 +2409,10 @@ class Engineering return self::erfVal($upper) - self::erfVal($lower); } } + return Functions::VALUE(); } - // // Private method to calculate the erfc value // @@ -2479,10 +2442,10 @@ class Engineering $q1 = $q2; $q2 = $b / $d; } while ((abs($q1 - $q2) / $q2) > PRECISION); + return self::$oneSqrtPi * exp(-$x * $x) * $q2; } - /** * ERFC * @@ -2506,10 +2469,10 @@ class Engineering if (is_numeric($x)) { return self::erfcVal($x); } + return Functions::VALUE(); } - /** * getConversionGroups * Returns a list of the different conversion groups for UOM conversions @@ -2518,14 +2481,14 @@ class Engineering */ public static function getConversionGroups() { - $conversionGroups = array(); + $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit) { $conversionGroups[] = $conversionUnit['Group']; } + return array_merge(array_unique($conversionGroups)); } - /** * getConversionGroupUnits * Returns an array of units of measure, for a specified conversion group, or for all groups @@ -2535,16 +2498,16 @@ class Engineering */ public static function getConversionGroupUnits($group = null) { - $conversionGroups = array(); + $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if ((is_null($group)) || ($conversionGroup['Group'] == $group)) { $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; } } + return $conversionGroups; } - /** * getConversionGroupUnitDetails * @@ -2553,19 +2516,19 @@ class Engineering */ public static function getConversionGroupUnitDetails($group = null) { - $conversionGroups = array(); + $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if ((is_null($group)) || ($conversionGroup['Group'] == $group)) { - $conversionGroups[$conversionGroup['Group']][] = array( + $conversionGroups[$conversionGroup['Group']][] = [ 'unit' => $conversionUnit, - 'description' => $conversionGroup['Unit Name'] - ); + 'description' => $conversionGroup['Unit Name'], + ]; } } + return $conversionGroups; } - /** * getConversionMultipliers * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM() @@ -2577,7 +2540,6 @@ class Engineering return self::$conversionMultipliers; } - /** * CONVERTUOM * @@ -2656,6 +2618,7 @@ class Engineering if (($toUOM == 'K') || ($toUOM == 'kel')) { $value += 273.15; } + return $value; } } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) && @@ -2671,13 +2634,16 @@ class Engineering if (($fromUOM == 'K') || ($fromUOM == 'kel')) { $value -= 273.15; } + return ($value * 1.8) + 32; } if (($toUOM == 'C') || ($toUOM == 'cel')) { return $value - 273.15; } + return $value + 273.15; } + return ($value * self::$unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier; } } diff --git a/src/PhpSpreadsheet/Calculation/ExceptionHandler.php b/src/PhpSpreadsheet/Calculation/ExceptionHandler.php index ebbe22e8..cccdf91a 100644 --- a/src/PhpSpreadsheet/Calculation/ExceptionHandler.php +++ b/src/PhpSpreadsheet/Calculation/ExceptionHandler.php @@ -31,7 +31,7 @@ class ExceptionHandler */ public function __construct() { - set_error_handler(array('\\PhpSpreadsheet\\Calculation\\Exception', 'errorHandlerCallback'), E_ALL); + set_error_handler(['\\PhpSpreadsheet\\Calculation\\Exception', 'errorHandlerCallback'], E_ALL); } /** diff --git a/src/PhpSpreadsheet/Calculation/Financial.php b/src/PhpSpreadsheet/Calculation/Financial.php index 9a0be228..e294a26c 100644 --- a/src/PhpSpreadsheet/Calculation/Financial.php +++ b/src/PhpSpreadsheet/Calculation/Financial.php @@ -2,10 +2,10 @@ namespace PhpSpreadsheet\Calculation; -/** FINANCIAL_MAX_ITERATIONS */ +/* FINANCIAL_MAX_ITERATIONS */ define('FINANCIAL_MAX_ITERATIONS', 128); -/** FINANCIAL_PRECISION */ +/* FINANCIAL_PRECISION */ define('FINANCIAL_PRECISION', 1.0e-08); /** @@ -38,28 +38,26 @@ class Financial * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month * * @param DateTime $testDate The date for testing - * @return boolean + * @return bool */ private static function isLastDayOfMonth($testDate) { - return ($testDate->format('d') == $testDate->format('t')); + return $testDate->format('d') == $testDate->format('t'); } - /** * isFirstDayOfMonth * * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month * * @param DateTime $testDate The date for testing - * @return boolean + * @return bool */ private static function isFirstDayOfMonth($testDate) { - return ($testDate->format('d') == 1); + return $testDate->format('d') == 1; } - private static function couponFirstPeriodDate($settlement, $maturity, $frequency, $next) { $months = 12 / $frequency; @@ -68,10 +66,10 @@ class Financial $eom = self::isLastDayOfMonth($result); while ($settlement < \PhpSpreadsheet\Shared\Date::PHPToExcel($result)) { - $result->modify('-'.$months.' months'); + $result->modify('-' . $months . ' months'); } if ($next) { - $result->modify('+'.$months.' months'); + $result->modify('+' . $months . ' months'); } if ($eom) { @@ -81,7 +79,6 @@ class Financial return \PhpSpreadsheet\Shared\Date::PHPToExcel($result); } - private static function isValidFrequency($frequency) { if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) { @@ -91,23 +88,23 @@ class Financial (($frequency == 6) || ($frequency == 12))) { return true; } + return false; } - /** * daysPerYear * * Returns the number of days in a specified year, as defined by the "basis" value * - * @param integer $year The year against which we're testing - * @param integer $basis The type of day count: + * @param int $year The year against which we're testing + * @param int $basis The type of day count: * 0 or omitted US (NASD) 360 * 1 Actual (365 or 366 in a leap year) * 2 360 * 3 365 * 4 European 360 - * @return integer + * @return int */ private static function daysPerYear($year, $basis = 0) { @@ -126,22 +123,22 @@ class Financial default: return Functions::NAN(); } + return $daysPerYear; } - private static function interestAndPrincipal($rate = 0, $per = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) { $pmt = self::PMT($rate, $nper, $pv, $fv, $type); $capital = $pv; - for ($i = 1; $i<= $per; ++$i) { + for ($i = 1; $i <= $per; ++$i) { $interest = ($type && $i == 1) ? 0 : -$capital * $rate; $principal = $pmt - $interest; $capital += $principal; } - return array($interest, $principal); - } + return [$interest, $principal]; + } /** * ACCRINT @@ -151,7 +148,6 @@ class Financial * Excel Function: * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis]) * - * @access public * @category Financial Functions * @param mixed $issue The security's issue date. * @param mixed $firstinterest The security's first interest date. @@ -161,7 +157,7 @@ class Financial * @param float $rate The security's annual coupon rate. * @param float $par The security's par value. * If you omit par, ACCRINT uses $1,000. - * @param integer $frequency the number of coupon payments per year. + * @param int $frequency the number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual @@ -170,7 +166,7 @@ class Financial * also available * 6 Bimonthly * 12 Monthly - * @param integer $basis The type of day count to use. + * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -180,18 +176,18 @@ class Financial */ public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par = 1000, $frequency = 1, $basis = 0) { - $issue = Functions::flattenSingleValue($issue); - $firstinterest = Functions::flattenSingleValue($firstinterest); - $settlement = Functions::flattenSingleValue($settlement); - $rate = Functions::flattenSingleValue($rate); - $par = (is_null($par)) ? 1000 : Functions::flattenSingleValue($par); - $frequency = (is_null($frequency)) ? 1 : Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : Functions::flattenSingleValue($basis); + $issue = Functions::flattenSingleValue($issue); + $firstinterest = Functions::flattenSingleValue($firstinterest); + $settlement = Functions::flattenSingleValue($settlement); + $rate = Functions::flattenSingleValue($rate); + $par = (is_null($par)) ? 1000 : Functions::flattenSingleValue($par); + $frequency = (is_null($frequency)) ? 1 : Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : Functions::flattenSingleValue($basis); // Validate if ((is_numeric($rate)) && (is_numeric($par))) { - $rate = (float) $rate; - $par = (float) $par; + $rate = (float) $rate; + $par = (float) $par; if (($rate <= 0) || ($par <= 0)) { return Functions::NAN(); } @@ -203,10 +199,10 @@ class Financial return $par * $rate * $daysBetweenIssueAndSettlement; } + return Functions::VALUE(); } - /** * ACCRINTM * @@ -215,14 +211,13 @@ class Financial * Excel Function: * ACCRINTM(issue,settlement,rate[,par[,basis]]) * - * @access public * @category Financial Functions * @param mixed issue The security's issue date. * @param mixed settlement The security's settlement (or maturity) date. * @param float rate The security's annual coupon rate. * @param float par The security's par value. * If you omit par, ACCRINT uses $1,000. - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -232,16 +227,16 @@ class Financial */ public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis = 0) { - $issue = Functions::flattenSingleValue($issue); - $settlement = Functions::flattenSingleValue($settlement); - $rate = Functions::flattenSingleValue($rate); - $par = (is_null($par)) ? 1000 : Functions::flattenSingleValue($par); - $basis = (is_null($basis)) ? 0 : Functions::flattenSingleValue($basis); + $issue = Functions::flattenSingleValue($issue); + $settlement = Functions::flattenSingleValue($settlement); + $rate = Functions::flattenSingleValue($rate); + $par = (is_null($par)) ? 1000 : Functions::flattenSingleValue($par); + $basis = (is_null($basis)) ? 0 : Functions::flattenSingleValue($basis); // Validate if ((is_numeric($rate)) && (is_numeric($par))) { - $rate = (float) $rate; - $par = (float) $par; + $rate = (float) $rate; + $par = (float) $par; if (($rate <= 0) || ($par <= 0)) { return Functions::NAN(); } @@ -250,12 +245,13 @@ class Financial // return date error return $daysBetweenIssueAndSettlement; } + return $par * $rate * $daysBetweenIssueAndSettlement; } + return Functions::VALUE(); } - /** * AMORDEGRC * @@ -271,7 +267,6 @@ class Financial * Excel Function: * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * - * @access public * @category Financial Functions * @param float cost The cost of the asset. * @param mixed purchased Date of the purchase of the asset. @@ -279,7 +274,7 @@ class Financial * @param mixed salvage The salvage value at the end of the life of the asset. * @param float period The period. * @param float rate Rate of depreciation. - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -289,13 +284,13 @@ class Financial */ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { - $cost = Functions::flattenSingleValue($cost); - $purchased = Functions::flattenSingleValue($purchased); - $firstPeriod = Functions::flattenSingleValue($firstPeriod); - $salvage = Functions::flattenSingleValue($salvage); - $period = floor(Functions::flattenSingleValue($period)); - $rate = Functions::flattenSingleValue($rate); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $cost = Functions::flattenSingleValue($cost); + $purchased = Functions::flattenSingleValue($purchased); + $firstPeriod = Functions::flattenSingleValue($firstPeriod); + $salvage = Functions::flattenSingleValue($salvage); + $period = floor(Functions::flattenSingleValue($period)); + $rate = Functions::flattenSingleValue($rate); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); // The depreciation coefficients are: // Life of assets (1/rate) Depreciation coefficient @@ -334,10 +329,10 @@ class Financial } $cost -= $fNRate; } + return $fNRate; } - /** * AMORLINC * @@ -348,7 +343,6 @@ class Financial * Excel Function: * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * - * @access public * @category Financial Functions * @param float cost The cost of the asset. * @param mixed purchased Date of the purchase of the asset. @@ -356,7 +350,7 @@ class Financial * @param mixed salvage The salvage value at the end of the life of the asset. * @param float period The period. * @param float rate Rate of depreciation. - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -366,13 +360,13 @@ class Financial */ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { - $cost = Functions::flattenSingleValue($cost); - $purchased = Functions::flattenSingleValue($purchased); + $cost = Functions::flattenSingleValue($cost); + $purchased = Functions::flattenSingleValue($purchased); $firstPeriod = Functions::flattenSingleValue($firstPeriod); - $salvage = Functions::flattenSingleValue($salvage); - $period = Functions::flattenSingleValue($period); - $rate = Functions::flattenSingleValue($rate); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $salvage = Functions::flattenSingleValue($salvage); + $period = Functions::flattenSingleValue($period); + $rate = Functions::flattenSingleValue($rate); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); $fOneRate = $cost * $rate; $fCostDelta = $cost - $salvage; @@ -392,13 +386,12 @@ class Financial } elseif ($period <= $nNumOfFullPeriods) { return $fOneRate; } elseif ($period == ($nNumOfFullPeriods + 1)) { - return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate); + return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; } else { return 0.0; } } - /** * COUPDAYBS * @@ -407,7 +400,6 @@ class Financial * Excel Function: * COUPDAYBS(settlement,maturity,frequency[,basis]) * - * @access public * @category Financial Functions * @param mixed settlement The security's settlement date. * The security settlement date is the date after the issue @@ -423,7 +415,7 @@ class Financial * also available * 6 Bimonthly * 12 Monthly - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -434,9 +426,9 @@ class Financial public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) { $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = (int) Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); if (is_string($settlement = DateTime::getDateValue($settlement))) { return Functions::VALUE(); @@ -457,7 +449,6 @@ class Financial return DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear; } - /** * COUPDAYS * @@ -466,7 +457,6 @@ class Financial * Excel Function: * COUPDAYS(settlement,maturity,frequency[,basis]) * - * @access public * @category Financial Functions * @param mixed settlement The security's settlement date. * The security settlement date is the date after the issue @@ -482,7 +472,7 @@ class Financial * also available * 6 Bimonthly * 12 Monthly - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -493,9 +483,9 @@ class Financial public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) { $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = (int) Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); if (is_string($settlement = DateTime::getDateValue($settlement))) { return Functions::VALUE(); @@ -518,19 +508,21 @@ class Financial // Actual/actual if ($frequency == 1) { $daysPerYear = self::daysPerYear(DateTime::YEAR($maturity), $basis); - return ($daysPerYear / $frequency); + + return $daysPerYear / $frequency; } $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); - return ($next - $prev); + + return $next - $prev; default: // US (NASD) 30/360, Actual/360 or European 30/360 return 360 / $frequency; } + return Functions::VALUE(); } - /** * COUPDAYSNC * @@ -539,7 +531,6 @@ class Financial * Excel Function: * COUPDAYSNC(settlement,maturity,frequency[,basis]) * - * @access public * @category Financial Functions * @param mixed settlement The security's settlement date. * The security settlement date is the date after the issue @@ -555,7 +546,7 @@ class Financial * also available * 6 Bimonthly * 12 Monthly - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -566,9 +557,9 @@ class Financial public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0) { $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = (int) Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); if (is_string($settlement = DateTime::getDateValue($settlement))) { return Functions::VALUE(); @@ -589,7 +580,6 @@ class Financial return DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear; } - /** * COUPNCD * @@ -598,7 +588,6 @@ class Financial * Excel Function: * COUPNCD(settlement,maturity,frequency[,basis]) * - * @access public * @category Financial Functions * @param mixed settlement The security's settlement date. * The security settlement date is the date after the issue @@ -614,7 +603,7 @@ class Financial * also available * 6 Bimonthly * 12 Monthly - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -625,10 +614,10 @@ class Financial */ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = (int) Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); if (is_string($settlement = DateTime::getDateValue($settlement))) { return Functions::VALUE(); @@ -646,7 +635,6 @@ class Financial return self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); } - /** * COUPNUM * @@ -656,7 +644,6 @@ class Financial * Excel Function: * COUPNUM(settlement,maturity,frequency[,basis]) * - * @access public * @category Financial Functions * @param mixed settlement The security's settlement date. * The security settlement date is the date after the issue @@ -672,20 +659,20 @@ class Financial * also available * 6 Bimonthly * 12 Monthly - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 - * @return integer + * @return int */ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = (int) Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); if (is_string($settlement = DateTime::getDateValue($settlement))) { return Functions::VALUE(); @@ -715,10 +702,10 @@ class Financial case 12: // monthly return ceil($daysBetweenSettlementAndMaturity / 30); } + return Functions::VALUE(); } - /** * COUPPCD * @@ -727,7 +714,6 @@ class Financial * Excel Function: * COUPPCD(settlement,maturity,frequency[,basis]) * - * @access public * @category Financial Functions * @param mixed settlement The security's settlement date. * The security settlement date is the date after the issue @@ -743,7 +729,7 @@ class Financial * also available * 6 Bimonthly * 12 Monthly - * @param integer basis The type of day count to use. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -754,10 +740,10 @@ class Financial */ public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = (int) Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); if (is_string($settlement = DateTime::getDateValue($settlement))) { return Functions::VALUE(); @@ -775,7 +761,6 @@ class Financial return self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); } - /** * CUMIPMT * @@ -784,27 +769,26 @@ class Financial * Excel Function: * CUMIPMT(rate,nper,pv,start,end[,type]) * - * @access public * @category Financial Functions * @param float $rate The Interest rate - * @param integer $nper The total number of payment periods + * @param int $nper The total number of payment periods * @param float $pv Present Value - * @param integer $start The first period in the calculation. + * @param int $start The first period in the calculation. * Payment periods are numbered beginning with 1. - * @param integer $end The last period in the calculation. - * @param integer $type A number 0 or 1 and indicates when payments are due: + * @param int $end The last period in the calculation. + * @param int $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @return float */ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $start = (int) Functions::flattenSingleValue($start); - $end = (int) Functions::flattenSingleValue($end); - $type = (int) Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $nper = (int) Functions::flattenSingleValue($nper); + $pv = Functions::flattenSingleValue($pv); + $start = (int) Functions::flattenSingleValue($start); + $end = (int) Functions::flattenSingleValue($end); + $type = (int) Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -823,7 +807,6 @@ class Financial return $interest; } - /** * CUMPRINC * @@ -832,27 +815,26 @@ class Financial * Excel Function: * CUMPRINC(rate,nper,pv,start,end[,type]) * - * @access public * @category Financial Functions * @param float $rate The Interest rate - * @param integer $nper The total number of payment periods + * @param int $nper The total number of payment periods * @param float $pv Present Value - * @param integer $start The first period in the calculation. + * @param int $start The first period in the calculation. * Payment periods are numbered beginning with 1. - * @param integer $end The last period in the calculation. - * @param integer $type A number 0 or 1 and indicates when payments are due: + * @param int $end The last period in the calculation. + * @param int $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @return float */ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $start = (int) Functions::flattenSingleValue($start); - $end = (int) Functions::flattenSingleValue($end); - $type = (int) Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $nper = (int) Functions::flattenSingleValue($nper); + $pv = Functions::flattenSingleValue($pv); + $start = (int) Functions::flattenSingleValue($start); + $end = (int) Functions::flattenSingleValue($end); + $type = (int) Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -871,7 +853,6 @@ class Financial return $principal; } - /** * DB * @@ -885,34 +866,33 @@ class Financial * Excel Function: * DB(cost,salvage,life,period[,month]) * - * @access public * @category Financial Functions * @param float cost Initial cost of the asset. * @param float salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) - * @param integer life Number of periods over which the asset is depreciated. + * @param int life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) - * @param integer period The period for which you want to calculate the + * @param int period The period for which you want to calculate the * depreciation. Period must use the same units as life. - * @param integer month Number of months in the first year. If month is omitted, + * @param int month Number of months in the first year. If month is omitted, * it defaults to 12. * @return float */ public static function DB($cost, $salvage, $life, $period, $month = 12) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - $month = Functions::flattenSingleValue($month); + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + $period = Functions::flattenSingleValue($period); + $month = Functions::flattenSingleValue($month); // Validate if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) { - $cost = (float) $cost; + $cost = (float) $cost; $salvage = (float) $salvage; - $life = (int) $life; - $period = (int) $period; - $month = (int) $month; + $life = (int) $life; + $period = (int) $period; + $month = (int) $month; if ($cost == 0) { return 0.0; } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) { @@ -937,12 +917,13 @@ class Financial if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { $depreciation = round($depreciation, 2); } + return $depreciation; } + return Functions::VALUE(); } - /** * DDB * @@ -952,14 +933,13 @@ class Financial * Excel Function: * DDB(cost,salvage,life,period[,factor]) * - * @access public * @category Financial Functions * @param float cost Initial cost of the asset. * @param float salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) - * @param integer life Number of periods over which the asset is depreciated. + * @param int life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) - * @param integer period The period for which you want to calculate the + * @param int period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param float factor The rate at which the balance declines. * If factor is omitted, it is assumed to be 2 (the @@ -968,19 +948,19 @@ class Financial */ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - $factor = Functions::flattenSingleValue($factor); + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + $period = Functions::flattenSingleValue($period); + $factor = Functions::flattenSingleValue($factor); // Validate if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) { - $cost = (float) $cost; + $cost = (float) $cost; $salvage = (float) $salvage; - $life = (int) $life; - $period = (int) $period; - $factor = (float) $factor; + $life = (int) $life; + $period = (int) $period; + $factor = (float) $factor; if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) { return Functions::NAN(); } @@ -997,12 +977,13 @@ class Financial if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { $depreciation = round($depreciation, 2); } + return $depreciation; } + return Functions::VALUE(); } - /** * DISC * @@ -1011,16 +992,15 @@ class Financial * Excel Function: * DISC(settlement,maturity,price,redemption[,basis]) * - * @access public * @category Financial Functions * @param mixed settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed maturity The security's maturity date. * The maturity date is the date when the security expires. - * @param integer price The security's price per $100 face value. - * @param integer redemption The security's redemption value per $100 face value. - * @param integer basis The type of day count to use. + * @param int price The security's price per $100 face value. + * @param int redemption The security's redemption value per $100 face value. + * @param int basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -1030,17 +1010,17 @@ class Financial */ public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - $redemption = Functions::flattenSingleValue($redemption); - $basis = Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $price = Functions::flattenSingleValue($price); + $redemption = Functions::flattenSingleValue($redemption); + $basis = Functions::flattenSingleValue($basis); // Validate if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) { - $price = (float) $price; - $redemption = (float) $redemption; - $basis = (int) $basis; + $price = (float) $price; + $redemption = (float) $redemption; + $basis = (int) $basis; if (($price <= 0) || ($redemption <= 0)) { return Functions::NAN(); } @@ -1050,12 +1030,12 @@ class Financial return $daysBetweenSettlementAndMaturity; } - return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity); + return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; } + return Functions::VALUE(); } - /** * DOLLARDE * @@ -1066,16 +1046,15 @@ class Financial * Excel Function: * DOLLARDE(fractional_dollar,fraction) * - * @access public * @category Financial Functions * @param float $fractional_dollar Fractional Dollar - * @param integer $fraction Fraction + * @param int $fraction Fraction * @return float */ public static function DOLLARDE($fractional_dollar = null, $fraction = 0) { - $fractional_dollar = Functions::flattenSingleValue($fractional_dollar); - $fraction = (int)Functions::flattenSingleValue($fraction); + $fractional_dollar = Functions::flattenSingleValue($fractional_dollar); + $fraction = (int) Functions::flattenSingleValue($fraction); // Validate parameters if (is_null($fractional_dollar) || $fraction < 0) { @@ -1089,10 +1068,10 @@ class Financial $cents = fmod($fractional_dollar, 1); $cents /= $fraction; $cents *= pow(10, ceil(log10($fraction))); + return $dollars + $cents; } - /** * DOLLARFR * @@ -1103,16 +1082,15 @@ class Financial * Excel Function: * DOLLARFR(decimal_dollar,fraction) * - * @access public * @category Financial Functions * @param float $decimal_dollar Decimal Dollar - * @param integer $fraction Fraction + * @param int $fraction Fraction * @return float */ public static function DOLLARFR($decimal_dollar = null, $fraction = 0) { - $decimal_dollar = Functions::flattenSingleValue($decimal_dollar); - $fraction = (int)Functions::flattenSingleValue($fraction); + $decimal_dollar = Functions::flattenSingleValue($decimal_dollar); + $fraction = (int) Functions::flattenSingleValue($fraction); // Validate parameters if (is_null($decimal_dollar) || $fraction < 0) { @@ -1126,10 +1104,10 @@ class Financial $cents = fmod($decimal_dollar, 1); $cents *= $fraction; $cents *= pow(10, -ceil(log10($fraction))); + return $dollars + $cents; } - /** * EFFECT * @@ -1139,16 +1117,15 @@ class Financial * Excel Function: * EFFECT(nominal_rate,npery) * - * @access public * @category Financial Functions * @param float $nominal_rate Nominal interest rate - * @param integer $npery Number of compounding payments per year + * @param int $npery Number of compounding payments per year * @return float */ public static function EFFECT($nominal_rate = 0, $npery = 0) { - $nominal_rate = Functions::flattenSingleValue($nominal_rate); - $npery = (int)Functions::flattenSingleValue($npery); + $nominal_rate = Functions::flattenSingleValue($nominal_rate); + $npery = (int) Functions::flattenSingleValue($npery); // Validate parameters if ($nominal_rate <= 0 || $npery < 1) { @@ -1158,7 +1135,6 @@ class Financial return pow((1 + $nominal_rate / $npery), $npery) - 1; } - /** * FV * @@ -1167,7 +1143,6 @@ class Financial * Excel Function: * FV(rate,nper,pmt[,pv[,type]]) * - * @access public * @category Financial Functions * @param float $rate The interest rate per period * @param int $nper Total number of payment periods in an annuity @@ -1176,18 +1151,18 @@ class Financial * and interest but no other fees or taxes. * @param float $pv Present Value, or the lump-sum amount that a series of * future payments is worth right now. - * @param integer $type A number 0 or 1 and indicates when payments are due: + * @param int $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @return float */ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $type = Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $nper = Functions::flattenSingleValue($nper); + $pmt = Functions::flattenSingleValue($pmt); + $pv = Functions::flattenSingleValue($pv); + $type = Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -1198,10 +1173,10 @@ class Financial if (!is_null($rate) && $rate != 0) { return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate; } + return -$pv - $pmt * $nper; } - /** * FVSCHEDULE * @@ -1217,8 +1192,8 @@ class Financial */ public static function FVSCHEDULE($principal, $schedule) { - $principal = Functions::flattenSingleValue($principal); - $schedule = Functions::flattenArray($schedule); + $principal = Functions::flattenSingleValue($principal); + $schedule = Functions::flattenArray($schedule); foreach ($schedule as $rate) { $principal *= 1 + $rate; @@ -1227,7 +1202,6 @@ class Financial return $principal; } - /** * INTRATE * @@ -1240,9 +1214,9 @@ class Financial * The security settlement date is the date after the issue date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. - * @param integer $investment The amount invested in the security. - * @param integer $redemption The amount to be received at maturity. - * @param integer $basis The type of day count to use. + * @param int $investment The amount invested in the security. + * @param int $redemption The amount to be received at maturity. + * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 @@ -1252,17 +1226,17 @@ class Financial */ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $investment = Functions::flattenSingleValue($investment); - $redemption = Functions::flattenSingleValue($redemption); - $basis = Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $investment = Functions::flattenSingleValue($investment); + $redemption = Functions::flattenSingleValue($redemption); + $basis = Functions::flattenSingleValue($basis); // Validate if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) { - $investment = (float) $investment; - $redemption = (float) $redemption; - $basis = (int) $basis; + $investment = (float) $investment; + $redemption = (float) $redemption; + $basis = (int) $basis; if (($investment <= 0) || ($redemption <= 0)) { return Functions::NAN(); } @@ -1274,10 +1248,10 @@ class Financial return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); } + return Functions::VALUE(); } - /** * IPMT * @@ -1296,12 +1270,12 @@ class Financial */ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $per = (int) Functions::flattenSingleValue($per); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = (int) Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $per = (int) Functions::flattenSingleValue($per); + $nper = (int) Functions::flattenSingleValue($nper); + $pv = Functions::flattenSingleValue($pv); + $fv = Functions::flattenSingleValue($fv); + $type = (int) Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -1313,6 +1287,7 @@ class Financial // Calculate $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); + return $interestAndPrincipal[0]; } @@ -1382,10 +1357,10 @@ class Financial return $x_mid; } } + return Functions::VALUE(); } - /** * ISPMT * @@ -1416,7 +1391,7 @@ class Financial // Calculate $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0); - for ($i=0; $i <= $period; ++$i) { + for ($i = 0; $i <= $period; ++$i) { $returnValue = $interestRate * $principleRemaining * -1; $principleRemaining -= $principlePayment; // principle needs to be 0 after the last payment, don't let floating point screw it up @@ -1424,9 +1399,9 @@ class Financial $returnValue = 0; } } - return($returnValue); - } + return $returnValue; + } /** * MIRR @@ -1449,9 +1424,9 @@ class Financial if (!is_array($values)) { return Functions::VALUE(); } - $values = Functions::flattenArray($values); - $finance_rate = Functions::flattenSingleValue($finance_rate); - $reinvestment_rate = Functions::flattenSingleValue($reinvestment_rate); + $values = Functions::flattenArray($values); + $finance_rate = Functions::flattenSingleValue($finance_rate); + $reinvestment_rate = Functions::flattenSingleValue($reinvestment_rate); $n = count($values); $rr = 1.0 + $reinvestment_rate; @@ -1473,10 +1448,9 @@ class Financial $mirr = pow((-$npv_pos * pow($rr, $n)) / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0; - return (is_finite($mirr) ? $mirr : Functions::VALUE()); + return is_finite($mirr) ? $mirr : Functions::VALUE(); } - /** * NOMINAL * @@ -1488,8 +1462,8 @@ class Financial */ public static function NOMINAL($effect_rate = 0, $npery = 0) { - $effect_rate = Functions::flattenSingleValue($effect_rate); - $npery = (int)Functions::flattenSingleValue($npery); + $effect_rate = Functions::flattenSingleValue($effect_rate); + $npery = (int) Functions::flattenSingleValue($npery); // Validate parameters if ($effect_rate <= 0 || $npery < 1) { @@ -1500,7 +1474,6 @@ class Financial return $npery * (pow($effect_rate + 1, 1 / $npery) - 1); } - /** * NPER * @@ -1515,11 +1488,11 @@ class Financial */ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $pmt = Functions::flattenSingleValue($pmt); + $pv = Functions::flattenSingleValue($pv); + $fv = Functions::flattenSingleValue($fv); + $type = Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -1531,12 +1504,14 @@ class Financial if ($pmt == 0 && $pv == 0) { return Functions::NAN(); } + return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate); } if ($pmt == 0) { return Functions::NAN(); } - return (-$pv -$fv) / $pmt; + + return (-$pv - $fv) / $pmt; } /** @@ -1581,11 +1556,11 @@ class Financial */ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $nper = Functions::flattenSingleValue($nper); + $pv = Functions::flattenSingleValue($pv); + $fv = Functions::flattenSingleValue($fv); + $type = Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -1596,10 +1571,10 @@ class Financial if (!is_null($rate) && $rate != 0) { return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate); } + return (-$pv - $fv) / $nper; } - /** * PPMT * @@ -1615,12 +1590,12 @@ class Financial */ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $per = (int) Functions::flattenSingleValue($per); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = (int) Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $per = (int) Functions::flattenSingleValue($per); + $nper = (int) Functions::flattenSingleValue($nper); + $pv = Functions::flattenSingleValue($pv); + $fv = Functions::flattenSingleValue($fv); + $type = (int) Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -1632,19 +1607,19 @@ class Financial // Calculate $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); + return $interestAndPrincipal[1]; } - public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $rate = (float) Functions::flattenSingleValue($rate); - $yield = (float) Functions::flattenSingleValue($yield); - $redemption = (float) Functions::flattenSingleValue($redemption); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $rate = (float) Functions::flattenSingleValue($rate); + $yield = (float) Functions::flattenSingleValue($yield); + $redemption = (float) Functions::flattenSingleValue($redemption); + $frequency = (int) Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) Functions::flattenSingleValue($basis); if (is_string($settlement = DateTime::getDateValue($settlement))) { return Functions::VALUE(); @@ -1664,9 +1639,9 @@ class Financial $n = self::COUPNUM($settlement, $maturity, $frequency, $basis); $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis); - $baseYF = 1.0 + ($yield / $frequency); - $rfp = 100 * ($rate / $frequency); - $de = $dsc / $e; + $baseYF = 1.0 + ($yield / $frequency); + $rfp = 100 * ($rate / $frequency); + $de = $dsc / $e; $result = $redemption / pow($baseYF, (--$n + $de)); for ($k = 0; $k <= $n; ++$k) { @@ -1677,7 +1652,6 @@ class Financial return $result; } - /** * PRICEDISC * @@ -1699,11 +1673,11 @@ class Financial */ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = (float) Functions::flattenSingleValue($discount); - $redemption = (float) Functions::flattenSingleValue($redemption); - $basis = (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $discount = (float) Functions::flattenSingleValue($discount); + $redemption = (float) Functions::flattenSingleValue($redemption); + $basis = (int) Functions::flattenSingleValue($basis); // Validate if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) { @@ -1718,10 +1692,10 @@ class Financial return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); } + return Functions::VALUE(); } - /** * PRICEMAT * @@ -1744,12 +1718,12 @@ class Financial */ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $issue = Functions::flattenSingleValue($issue); - $rate = Functions::flattenSingleValue($rate); - $yield = Functions::flattenSingleValue($yield); - $basis = (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $issue = Functions::flattenSingleValue($issue); + $rate = Functions::flattenSingleValue($rate); + $yield = Functions::flattenSingleValue($yield); + $basis = (int) Functions::flattenSingleValue($basis); // Validate if (is_numeric($rate) && is_numeric($yield)) { @@ -1779,14 +1753,14 @@ class Financial } $daysBetweenSettlementAndMaturity *= $daysPerYear; - return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / + return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - - (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100)); + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); } + return Functions::VALUE(); } - /** * PV * @@ -1801,11 +1775,11 @@ class Financial */ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); + $rate = Functions::flattenSingleValue($rate); + $nper = Functions::flattenSingleValue($nper); + $pmt = Functions::flattenSingleValue($pmt); + $fv = Functions::flattenSingleValue($fv); + $type = Functions::flattenSingleValue($type); // Validate parameters if ($type != 0 && $type != 1) { @@ -1816,10 +1790,10 @@ class Financial if (!is_null($rate) && $rate != 0) { return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper); } + return -$fv - $pmt * $nper; } - /** * RATE * @@ -1831,7 +1805,6 @@ class Financial * Excel Function: * RATE(nper,pmt,pv[,fv[,type[,guess]]]) * - * @access public * @category Financial Functions * @param float nper The total number of payment periods in an annuity. * @param float pmt The payment made each period and cannot change over the life @@ -1843,7 +1816,7 @@ class Financial * @param float fv The future value, or a cash balance you want to attain after * the last payment is made. If fv is omitted, it is assumed * to be 0 (the future value of a loan, for example, is 0). - * @param integer type A number 0 or 1 and indicates when payments are due: + * @param int type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @param float guess Your guess for what the rate will be. @@ -1852,12 +1825,12 @@ class Financial **/ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) { - $nper = (int) Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $fv = (is_null($fv)) ? 0.0 : Functions::flattenSingleValue($fv); - $type = (is_null($type)) ? 0 : (int) Functions::flattenSingleValue($type); - $guess = (is_null($guess)) ? 0.1 : Functions::flattenSingleValue($guess); + $nper = (int) Functions::flattenSingleValue($nper); + $pmt = Functions::flattenSingleValue($pmt); + $pv = Functions::flattenSingleValue($pv); + $fv = (is_null($fv)) ? 0.0 : Functions::flattenSingleValue($fv); + $type = (is_null($type)) ? 0 : (int) Functions::flattenSingleValue($type); + $guess = (is_null($guess)) ? 0.1 : Functions::flattenSingleValue($guess); $rate = $guess; if (abs($rate) < FINANCIAL_PRECISION) { @@ -1870,7 +1843,7 @@ class Financial $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; // find root by secant method - $i = $x0 = 0.0; + $i = $x0 = 0.0; $x1 = $rate; while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) { $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0); @@ -1890,10 +1863,10 @@ class Financial $y1 = $y; ++$i; } + return $rate; } - /** * RECEIVED * @@ -1915,11 +1888,11 @@ class Financial */ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $investment = (float) Functions::flattenSingleValue($investment); - $discount = (float) Functions::flattenSingleValue($discount); - $basis = (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $investment = (float) Functions::flattenSingleValue($investment); + $discount = (float) Functions::flattenSingleValue($discount); + $basis = (int) Functions::flattenSingleValue($basis); // Validate if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) { @@ -1932,12 +1905,12 @@ class Financial return $daysBetweenSettlementAndMaturity; } - return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity)); + return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); } + return Functions::VALUE(); } - /** * SLN * @@ -1950,21 +1923,22 @@ class Financial */ public static function SLN($cost, $salvage, $life) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); // Calculate if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) { if ($life < 0) { return Functions::NAN(); } + return ($cost - $salvage) / $life; } + return Functions::VALUE(); } - /** * SYD * @@ -1978,22 +1952,23 @@ class Financial */ public static function SYD($cost, $salvage, $life, $period) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + $period = Functions::flattenSingleValue($period); // Calculate if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) { if (($life < 1) || ($period > $life)) { return Functions::NAN(); } + return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); } + return Functions::VALUE(); } - /** * TBILLEQ * @@ -2008,9 +1983,9 @@ class Financial */ public static function TBILLEQ($settlement, $maturity, $discount) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = Functions::flattenSingleValue($discount); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $discount = Functions::flattenSingleValue($discount); // Use TBILLPRICE for validation $testValue = self::TBILLPRICE($settlement, $maturity, $discount); @@ -2032,7 +2007,6 @@ class Financial return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); } - /** * TBILLPRICE * @@ -2047,9 +2021,9 @@ class Financial */ public static function TBILLPRICE($settlement, $maturity, $discount) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = Functions::flattenSingleValue($discount); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $discount = Functions::flattenSingleValue($discount); if (is_string($maturity = DateTime::getDateValue($maturity))) { return Functions::VALUE(); @@ -2080,12 +2054,13 @@ class Financial if ($price <= 0) { return Functions::NAN(); } + return $price; } + return Functions::VALUE(); } - /** * TBILLYIELD * @@ -2100,9 +2075,9 @@ class Financial */ public static function TBILLYIELD($settlement, $maturity, $price) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $price = Functions::flattenSingleValue($price); // Validate if (is_numeric($price)) { @@ -2127,10 +2102,10 @@ class Financial return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); } + return Functions::VALUE(); } - public static function XIRR($values, $dates, $guess = 0.1) { if ((!is_array($values)) && (!is_array($dates))) { @@ -2181,10 +2156,10 @@ class Financial return $x_mid; } } + return Functions::VALUE(); } - /** * XNPV * @@ -2213,8 +2188,8 @@ class Financial if ((!is_array($values)) || (!is_array($dates))) { return Functions::VALUE(); } - $values = Functions::flattenArray($values); - $dates = Functions::flattenArray($dates); + $values = Functions::flattenArray($values); + $dates = Functions::flattenArray($dates); $valCount = count($values); if ($valCount != count($dates)) { return Functions::NAN(); @@ -2230,10 +2205,10 @@ class Financial } $xnpv += $values[$i] / pow(1 + $rate, DateTime::DATEDIF($dates[0], $dates[$i], 'd') / 365); } + return (is_finite($xnpv)) ? $xnpv : Functions::VALUE(); } - /** * YIELDDISC * @@ -2255,11 +2230,11 @@ class Financial */ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - $redemption = Functions::flattenSingleValue($redemption); - $basis = (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $price = Functions::flattenSingleValue($price); + $redemption = Functions::flattenSingleValue($redemption); + $basis = (int) Functions::flattenSingleValue($basis); // Validate if (is_numeric($price) && is_numeric($redemption)) { @@ -2279,10 +2254,10 @@ class Financial return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } + return Functions::VALUE(); } - /** * YIELDMAT * @@ -2305,12 +2280,12 @@ class Financial */ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $issue = Functions::flattenSingleValue($issue); - $rate = Functions::flattenSingleValue($rate); - $price = Functions::flattenSingleValue($price); - $basis = (int) Functions::flattenSingleValue($basis); + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $issue = Functions::flattenSingleValue($issue); + $rate = Functions::flattenSingleValue($rate); + $price = Functions::flattenSingleValue($price); + $basis = (int) Functions::flattenSingleValue($basis); // Validate if (is_numeric($rate) && is_numeric($price)) { @@ -2344,6 +2319,7 @@ class Financial (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } + return Functions::VALUE(); } } diff --git a/src/PhpSpreadsheet/Calculation/FormulaParser.php b/src/PhpSpreadsheet/Calculation/FormulaParser.php index 784333c8..f3c15b2d 100644 --- a/src/PhpSpreadsheet/Calculation/FormulaParser.php +++ b/src/PhpSpreadsheet/Calculation/FormulaParser.php @@ -49,22 +49,22 @@ PARTLY BASED ON: class FormulaParser { /* Character constants */ - const QUOTE_DOUBLE = '"'; - const QUOTE_SINGLE = '\''; + const QUOTE_DOUBLE = '"'; + const QUOTE_SINGLE = '\''; const BRACKET_CLOSE = ']'; - const BRACKET_OPEN = '['; - const BRACE_OPEN = '{'; - const BRACE_CLOSE = '}'; - const PAREN_OPEN = '('; - const PAREN_CLOSE = ')'; - const SEMICOLON = ';'; - const WHITESPACE = ' '; - const COMMA = ','; - const ERROR_START = '#'; + const BRACKET_OPEN = '['; + const BRACE_OPEN = '{'; + const BRACE_CLOSE = '}'; + const PAREN_OPEN = '('; + const PAREN_CLOSE = ')'; + const SEMICOLON = ';'; + const WHITESPACE = ' '; + const COMMA = ','; + const ERROR_START = '#'; - const OPERATORS_SN = "+-"; - const OPERATORS_INFIX = "+-*/^&=><"; - const OPERATORS_POSTFIX = "%"; + const OPERATORS_SN = '+-'; + const OPERATORS_INFIX = '+-*/^&=><'; + const OPERATORS_POSTFIX = '%'; /** * Formula @@ -78,7 +78,7 @@ class FormulaParser * * @var FormulaToken[] */ - private $tokens = array(); + private $tokens = []; /** * Create a new FormulaParser @@ -90,7 +90,7 @@ class FormulaParser { // Check parameters if (is_null($pFormula)) { - throw new Exception("Invalid parameter passed: formula"); + throw new Exception('Invalid parameter passed: formula'); } // Initialise values @@ -113,8 +113,8 @@ class FormulaParser * Get Token * * @param int $pId Token id - * @return string * @throws Exception + * @return string */ public function getToken($pId = 0) { @@ -160,15 +160,15 @@ class FormulaParser } // Helper variables - $tokens1 = $tokens2 = $stack = array(); - $inString = $inPath = $inRange = $inError = false; - $token = $previousToken = $nextToken = null; + $tokens1 = $tokens2 = $stack = []; + $inString = $inPath = $inRange = $inError = false; + $token = $previousToken = $nextToken = null; - $index = 1; - $value = ''; + $index = 1; + $value = ''; - $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"); - $COMPARATORS_MULTI = array(">=", "<=", "<>"); + $ERRORS = ['#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A']; + $COMPARATORS_MULTI = ['>=', '<=', '<>']; while ($index < $formulaLength) { // state-dependent character evaluation (order is important) @@ -184,7 +184,7 @@ class FormulaParser } else { $inString = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_TEXT); - $value = ""; + $value = ''; } } else { $value .= $this->formula{$index}; @@ -231,7 +231,7 @@ class FormulaParser if (in_array($value, $ERRORS)) { $inError = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_ERROR); - $value = ""; + $value = ''; } continue; } @@ -254,7 +254,7 @@ class FormulaParser if (strlen($value > 0)) { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); - $value = ""; + $value = ''; } $inString = true; ++$index; @@ -265,7 +265,7 @@ class FormulaParser if (strlen($value) > 0) { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); - $value = ""; + $value = ''; } $inPath = true; ++$index; @@ -283,7 +283,7 @@ class FormulaParser if (strlen($value) > 0) { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); - $value = ""; + $value = ''; } $inError = true; $value .= self::ERROR_START; @@ -296,14 +296,14 @@ class FormulaParser if (strlen($value) > 0) { // unexpected $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; $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; $stack[] = clone $tmp; @@ -314,18 +314,18 @@ class FormulaParser if ($this->formula{$index} == self::SEMICOLON) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); - $value = ""; + $value = ''; } $tmp = array_pop($stack); - $tmp->setValue(""); + $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; - $tmp = new FormulaToken(",", FormulaToken::TOKEN_TYPE_ARGUMENT); + $tmp = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); $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; $stack[] = clone $tmp; @@ -336,16 +336,16 @@ class FormulaParser if ($this->formula{$index} == self::BRACE_CLOSE) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); - $value = ""; + $value = ''; } $tmp = array_pop($stack); - $tmp->setValue(""); + $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; $tmp = array_pop($stack); - $tmp->setValue(""); + $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; @@ -357,9 +357,9 @@ class FormulaParser if ($this->formula{$index} == self::WHITESPACE) { if (strlen($value) > 0) { $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; while (($this->formula{$index} == self::WHITESPACE) && ($index < $formulaLength)) { ++$index; @@ -372,7 +372,7 @@ class FormulaParser if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) { if (strlen($value) > 0) { $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); $index += 2; @@ -383,8 +383,8 @@ class FormulaParser // standard infix operators if (strpos(self::OPERATORS_INFIX, $this->formula{$index}) !== false) { if (strlen($value) > 0) { - $tokens1[] =new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); - $value = ""; + $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); + $value = ''; } $tokens1[] = new FormulaToken($this->formula{$index}, FormulaToken::TOKEN_TYPE_OPERATORINFIX); ++$index; @@ -395,7 +395,7 @@ class FormulaParser if (strpos(self::OPERATORS_POSTFIX, $this->formula{$index}) !== false) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); - $value = ""; + $value = ''; } $tokens1[] = new FormulaToken($this->formula{$index}, FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); ++$index; @@ -408,9 +408,9 @@ class FormulaParser $tmp = new FormulaToken($value, FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; - $value = ""; + $value = ''; } 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; $stack[] = clone $tmp; } @@ -422,18 +422,18 @@ class FormulaParser if ($this->formula{$index} == self::COMMA) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); - $value = ""; + $value = ''; } $tmp = array_pop($stack); - $tmp->setValue(""); + $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $stack[] = $tmp; 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 { - $tokens1[] = new FormulaToken(",", FormulaToken::TOKEN_TYPE_ARGUMENT); + $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); } ++$index; continue; @@ -443,11 +443,11 @@ class FormulaParser if ($this->formula{$index} == self::PAREN_CLOSE) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); - $value = ""; + $value = ''; } $tmp = array_pop($stack); - $tmp->setValue(""); + $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; @@ -493,11 +493,11 @@ class FormulaParser continue; } - if (! ( + if (!( (($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_OPERAND) - ) ) { + )) { continue; } @@ -505,11 +505,11 @@ class FormulaParser continue; } - if (! ( + if (!( (($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_OPERAND) - ) ) { + )) { continue; } @@ -518,7 +518,7 @@ class FormulaParser // 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 - $this->tokens = array(); + $this->tokens = []; $tokenCount = count($tokens2); for ($i = 0; $i < $tokenCount; ++$i) { @@ -538,7 +538,7 @@ class FormulaParser continue; } - if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") { + if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '-') { if ($i == 0) { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && @@ -556,7 +556,7 @@ class FormulaParser continue; } - if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") { + if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '+') { if ($i == 0) { continue; } elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && @@ -576,9 +576,9 @@ class FormulaParser if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $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); - } elseif ($token->getValue() == "&") { + } elseif ($token->getValue() == '&') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_CONCATENATION); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); @@ -591,7 +591,7 @@ class FormulaParser if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING) { 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); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_RANGE); @@ -606,7 +606,7 @@ class FormulaParser if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { if (strlen($token->getValue() > 0)) { - if (substr($token->getValue(), 0, 1) == "@") { + if (substr($token->getValue(), 0, 1) == '@') { $token->setValue(substr($token->getValue(), 1)); } } diff --git a/src/PhpSpreadsheet/Calculation/FormulaToken.php b/src/PhpSpreadsheet/Calculation/FormulaToken.php index 445b9a87..a62385c2 100644 --- a/src/PhpSpreadsheet/Calculation/FormulaToken.php +++ b/src/PhpSpreadsheet/Calculation/FormulaToken.php @@ -50,30 +50,30 @@ PARTLY BASED ON: class FormulaToken { /* Token types */ - const TOKEN_TYPE_NOOP = 'Noop'; - const TOKEN_TYPE_OPERAND = 'Operand'; - const TOKEN_TYPE_FUNCTION = 'Function'; - const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression'; - const TOKEN_TYPE_ARGUMENT = 'Argument'; - const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix'; - const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix'; + const TOKEN_TYPE_NOOP = 'Noop'; + const TOKEN_TYPE_OPERAND = 'Operand'; + const TOKEN_TYPE_FUNCTION = 'Function'; + const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression'; + const TOKEN_TYPE_ARGUMENT = 'Argument'; + const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix'; + const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix'; const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix'; - const TOKEN_TYPE_WHITESPACE = 'Whitespace'; - const TOKEN_TYPE_UNKNOWN = 'Unknown'; + const TOKEN_TYPE_WHITESPACE = 'Whitespace'; + const TOKEN_TYPE_UNKNOWN = 'Unknown'; /* Token subtypes */ - const TOKEN_SUBTYPE_NOTHING = 'Nothing'; - const TOKEN_SUBTYPE_START = 'Start'; - const TOKEN_SUBTYPE_STOP = 'Stop'; - const TOKEN_SUBTYPE_TEXT = 'Text'; - const TOKEN_SUBTYPE_NUMBER = 'Number'; - const TOKEN_SUBTYPE_LOGICAL = 'Logical'; - const TOKEN_SUBTYPE_ERROR = 'Error'; - const TOKEN_SUBTYPE_RANGE = 'Range'; - const TOKEN_SUBTYPE_MATH = 'Math'; + const TOKEN_SUBTYPE_NOTHING = 'Nothing'; + const TOKEN_SUBTYPE_START = 'Start'; + const TOKEN_SUBTYPE_STOP = 'Stop'; + const TOKEN_SUBTYPE_TEXT = 'Text'; + const TOKEN_SUBTYPE_NUMBER = 'Number'; + const TOKEN_SUBTYPE_LOGICAL = 'Logical'; + const TOKEN_SUBTYPE_ERROR = 'Error'; + const TOKEN_SUBTYPE_RANGE = 'Range'; + const TOKEN_SUBTYPE_MATH = 'Math'; const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation'; - const TOKEN_SUBTYPE_INTERSECTION = 'Intersection'; - const TOKEN_SUBTYPE_UNION = 'Union'; + const TOKEN_SUBTYPE_INTERSECTION = 'Intersection'; + const TOKEN_SUBTYPE_UNION = 'Union'; /** * Value @@ -106,8 +106,8 @@ class FormulaToken public function __construct($pValue, $pTokenType = self::TOKEN_TYPE_UNKNOWN, $pTokenSubType = self::TOKEN_SUBTYPE_NOTHING) { // Initialise values - $this->value = $pValue; - $this->tokenType = $pTokenType; + $this->value = $pValue; + $this->tokenType = $pTokenType; $this->tokenSubType = $pTokenSubType; } diff --git a/src/PhpSpreadsheet/Calculation/Functions.php b/src/PhpSpreadsheet/Calculation/Functions.php index 528f544a..9cc4f3c0 100644 --- a/src/PhpSpreadsheet/Calculation/Functions.php +++ b/src/PhpSpreadsheet/Calculation/Functions.php @@ -2,19 +2,18 @@ namespace PhpSpreadsheet\Calculation; -/** MAX_VALUE */ +/* MAX_VALUE */ define('MAX_VALUE', 1.2e308); -/** 2 / PI */ +/* 2 / PI */ define('M_2DIVPI', 0.63661977236758134307553505349006); -/** MAX_ITERATIONS */ +/* MAX_ITERATIONS */ define('MAX_ITERATIONS', 256); -/** PRECISION */ +/* PRECISION */ define('PRECISION', 8.88E-016); - /** * Copyright (c) 2006 - 2016 PhpSpreadsheet * @@ -48,11 +47,9 @@ class Functions const RETURNDATE_PHP_OBJECT = 'O'; const RETURNDATE_EXCEL = 'E'; - /** * Compatibility mode to use for error checking and responses * - * @access private * @var string */ protected static $compatibilityMode = self::COMPATIBILITY_EXCEL; @@ -60,7 +57,6 @@ class Functions /** * Data Type to use when returning date values * - * @access private * @var string */ protected static $returnDateType = self::RETURNDATE_EXCEL; @@ -68,10 +64,9 @@ class Functions /** * List of error codes * - * @access private * @var array */ - protected static $errorCodes = array( + protected static $errorCodes = [ 'null' => '#NULL!', 'divisionbyzero' => '#DIV/0!', 'value' => '#VALUE!', @@ -79,21 +74,19 @@ class Functions 'name' => '#NAME?', 'num' => '#NUM!', 'na' => '#N/A', - 'gettingdata' => '#GETTING_DATA' - ); - + 'gettingdata' => '#GETTING_DATA', + ]; /** * Set the Compatibility Mode * - * @access public * @category Function Configuration * @param string $compatibilityMode Compatibility Mode * Permitted values are: * Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' - * @return boolean (Success or Failure) + * @return bool (Success or Failure) */ public static function setCompatibilityMode($compatibilityMode) { @@ -102,16 +95,16 @@ class Functions ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE) ) { self::$compatibilityMode = $compatibilityMode; + return true; } + return false; } - /** * Return the current Compatibility Mode * - * @access public * @category Function Configuration * @return string Compatibility Mode * Possible Return values are: @@ -124,18 +117,16 @@ class Functions return self::$compatibilityMode; } - /** * 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 * @param string $returnDateType Return Date Format * Permitted values are: * Functions::RETURNDATE_PHP_NUMERIC 'P' * Functions::RETURNDATE_PHP_OBJECT 'O' * Functions::RETURNDATE_EXCEL 'E' - * @return boolean Success or failure + * @return bool Success or failure */ public static function setReturnDateType($returnDateType) { @@ -144,16 +135,16 @@ class Functions ($returnDateType == self::RETURNDATE_EXCEL) ) { self::$returnDateType = $returnDateType; + return true; } + return false; } - /** * 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 * @return string Return Date Format * Possible Return values are: @@ -166,11 +157,9 @@ class Functions return self::$returnDateType; } - /** * DUMMY * - * @access public * @category Error Returns * @return string #Not Yet Implemented */ @@ -179,11 +168,9 @@ class Functions return '#Not Yet Implemented'; } - /** * DIV0 * - * @access public * @category Error Returns * @return string #Not Yet Implemented */ @@ -192,7 +179,6 @@ class Functions return self::$errorCodes['divisionbyzero']; } - /** * NA * @@ -202,7 +188,6 @@ class Functions * Returns the error value #N/A * #N/A is the error value that means "no value is available." * - * @access public * @category Logical Functions * @return string #N/A! */ @@ -211,13 +196,11 @@ class Functions return self::$errorCodes['na']; } - /** * NaN * * Returns the error value #NUM! * - * @access public * @category Error Returns * @return string #NUM! */ @@ -226,13 +209,11 @@ class Functions return self::$errorCodes['num']; } - /** * NAME * * Returns the error value #NAME? * - * @access public * @category Error Returns * @return string #NAME? */ @@ -241,13 +222,11 @@ class Functions return self::$errorCodes['name']; } - /** * REF * * Returns the error value #REF! * - * @access public * @category Error Returns * @return string #REF! */ @@ -256,28 +235,24 @@ class Functions return self::$errorCodes['reference']; } - /** * NULL * * Returns the error value #NULL! * - * @access public * @category Error Returns * @return string #NULL! */ - public static function NULL() + public static function null() { return self::$errorCodes['null']; } - /** * VALUE * * Returns the error value #VALUE! * - * @access public * @category Error Returns * @return string #VALUE! */ @@ -286,35 +261,32 @@ class Functions return self::$errorCodes['value']; } - 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) { - return (substr_count($idx, '.') == 0); + return substr_count($idx, '.') == 0; } - public static function isCellValue($idx) { - return (substr_count($idx, '.') > 1); + return substr_count($idx, '.') > 1; } - public static function ifCondition($condition) { - $condition = Functions::flattenSingleValue($condition); + $condition = self::flattenSingleValue($condition); if (!isset($condition{0})) { $condition = '=""'; } - if (!in_array($condition{0}, array('>', '<', '='))) { + if (!in_array($condition{0}, ['>', '<', '='])) { if (!is_numeric($condition)) { $condition = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($condition)); } + return '=' . $condition; } else { preg_match('/([<>=]+)(.*)/', $condition, $matches); @@ -333,7 +305,7 @@ class Functions * ERROR_TYPE * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function errorType($value = '') { @@ -346,15 +318,15 @@ class Functions } ++$i; } + return self::NA(); } - /** * IS_BLANK * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isBlank($value = null) { @@ -365,12 +337,11 @@ class Functions return is_null($value); } - /** * IS_ERR * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isErr($value = '') { @@ -379,12 +350,11 @@ class Functions return self::isError($value) && (!self::isNa(($value))); } - /** * IS_ERROR * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isError($value = '') { @@ -393,29 +363,28 @@ class Functions if (!is_string($value)) { return false; } + return in_array($value, array_values(self::$errorCodes)); } - /** * IS_NA * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isNa($value = '') { $value = self::flattenSingleValue($value); - return ($value === self::NA()); + return $value === self::NA(); } - /** * IS_EVEN * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isEven($value = null) { @@ -427,15 +396,14 @@ class Functions return self::VALUE(); } - return ($value % 2 == 0); + return $value % 2 == 0; } - /** * IS_ODD * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isOdd($value = null) { @@ -447,15 +415,14 @@ class Functions return self::VALUE(); } - return (abs($value) % 2 == 1); + return abs($value) % 2 == 1; } - /** * IS_NUMBER * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isNumber($value = null) { @@ -464,15 +431,15 @@ class Functions if (is_string($value)) { return false; } + return is_numeric($value); } - /** * IS_LOGICAL * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isLogical($value = null) { @@ -481,33 +448,30 @@ class Functions return is_bool($value); } - /** * IS_TEXT * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isText($value = null) { $value = self::flattenSingleValue($value); - return (is_string($value) && !self::isError($value)); + return is_string($value) && !self::isError($value); } - /** * IS_NONTEXT * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function isNonText($value = null) { return !self::isText($value); } - /** * VERSION * @@ -518,7 +482,6 @@ class Functions return 'PhpSpreadsheet ##VERSION##, ##DATE##'; } - /** * N * @@ -546,7 +509,7 @@ class Functions case 'integer': return $value; case 'boolean': - return (integer)$value; + return (integer) $value; case 'string': // Errors if ((strlen($value) > 0) && ($value{0} == '#')) { @@ -554,10 +517,10 @@ class Functions } break; } + return 0; } - /** * TYPE * @@ -602,12 +565,13 @@ class Functions if ((strlen($value) > 0) && ($value{0} == '#')) { return 16; } + return 2; } + return 0; } - /** * Convert a multi-dimensional array to a simple 1-dimensional array * @@ -617,10 +581,10 @@ class Functions public static function flattenArray($array) { if (!is_array($array)) { - return (array)$array; + return (array) $array; } - $arrayValues = array(); + $arrayValues = []; foreach ($array as $value) { if (is_array($value)) { foreach ($value as $val) { @@ -640,7 +604,6 @@ class Functions return $arrayValues; } - /** * 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) { if (!is_array($array)) { - return (array)$array; + return (array) $array; } - $arrayValues = array(); + $arrayValues = []; foreach ($array as $k1 => $value) { if (is_array($value)) { foreach ($value as $k2 => $val) { @@ -673,7 +636,6 @@ class Functions return $arrayValues; } - /** * 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 // 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() } - // // 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 @@ -728,14 +688,15 @@ if ((!function_exists('mb_str_replace')) && function mb_str_replace($search, $replace, $subject) { if (is_array($subject)) { - $ret = array(); + $ret = []; foreach ($subject as $key => $val) { $ret[$key] = mb_str_replace($search, $replace, $val); } + return $ret; } - foreach ((array)$search as $key => $s) { + foreach ((array) $search as $key => $s) { if ($s == '' && $s !== 0) { continue; } @@ -746,6 +707,7 @@ if ((!function_exists('mb_str_replace')) && $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8'); } } + return $subject; } } diff --git a/src/PhpSpreadsheet/Calculation/Logical.php b/src/PhpSpreadsheet/Calculation/Logical.php index 47985fc8..166dbf11 100644 --- a/src/PhpSpreadsheet/Calculation/Logical.php +++ b/src/PhpSpreadsheet/Calculation/Logical.php @@ -34,16 +34,14 @@ class Logical * Excel Function: * =TRUE() * - * @access public * @category Logical Functions - * @return boolean True + * @return bool True */ - public static function TRUE() + public static function true() { return true; } - /** * FALSE * @@ -52,16 +50,14 @@ class Logical * Excel Function: * =FALSE() * - * @access public * @category Logical Functions - * @return boolean False + * @return bool False */ - public static function FALSE() + public static function false() { return false; } - /** * 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 * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * - * @access public * @category Logical Functions * @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() { @@ -114,10 +109,10 @@ class Logical if ($argCount < 0) { return Functions::VALUE(); } + return $returnValue; } - /** * 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 * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * - * @access public * @category Logical Functions * @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() { @@ -170,10 +164,10 @@ class Logical if ($argCount < 0) { return Functions::VALUE(); } + return $returnValue; } - /** * 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 * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * - * @access public * @category Logical Functions * @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) { @@ -236,7 +229,6 @@ class Logical * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. * ReturnIfFalse can be another formula. * - * @access public * @category Logical Functions * @param mixed $condition Condition to evaluate * @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) { - $condition = (is_null($condition)) ? true : (boolean) Functions::flattenSingleValue($condition); - $returnIfTrue = (is_null($returnIfTrue)) ? 0 : Functions::flattenSingleValue($returnIfTrue); + $condition = (is_null($condition)) ? true : (boolean) Functions::flattenSingleValue($condition); + $returnIfTrue = (is_null($returnIfTrue)) ? 0 : Functions::flattenSingleValue($returnIfTrue); $returnIfFalse = (is_null($returnIfFalse)) ? false : Functions::flattenSingleValue($returnIfFalse); return ($condition) ? $returnIfTrue : $returnIfFalse; } - /** * IFERROR * * Excel Function: * =IFERROR(testValue,errorpart) * - * @access public * @category Logical Functions * @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 diff --git a/src/PhpSpreadsheet/Calculation/LookupRef.php b/src/PhpSpreadsheet/Calculation/LookupRef.php index 81c1c4b8..4c9ac7bf 100644 --- a/src/PhpSpreadsheet/Calculation/LookupRef.php +++ b/src/PhpSpreadsheet/Calculation/LookupRef.php @@ -49,10 +49,10 @@ class LookupRef */ public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '') { - $row = Functions::flattenSingleValue($row); - $column = Functions::flattenSingleValue($column); + $row = Functions::flattenSingleValue($row); + $column = Functions::flattenSingleValue($column); $relativity = Functions::flattenSingleValue($relativity); - $sheetText = Functions::flattenSingleValue($sheetText); + $sheetText = Functions::flattenSingleValue($sheetText); if (($row < 1) || ($column < 1)) { return Functions::VALUE(); @@ -60,32 +60,33 @@ class LookupRef if ($sheetText > '') { if (strpos($sheetText, ' ') !== false) { - $sheetText = "'".$sheetText."'"; + $sheetText = "'" . $sheetText . "'"; } - $sheetText .='!'; + $sheetText .= '!'; } if ((!is_bool($referenceStyle)) || $referenceStyle) { $rowRelative = $columnRelative = '$'; - $column = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); + $column = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1); if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; } if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; } - return $sheetText.$columnRelative.$column.$rowRelative.$row; + + return $sheetText . $columnRelative . $column . $rowRelative . $row; } else { if (($relativity == 2) || ($relativity == 4)) { - $column = '['.$column.']'; + $column = '[' . $column . ']'; } if (($relativity == 3) || ($relativity == 4)) { - $row = '['.$row.']'; + $row = '[' . $row . ']'; } - return $sheetText.'R'.$row.'C'.$column; + + return $sheetText . 'R' . $row . 'C' . $column; } } - /** * COLUMN * @@ -98,7 +99,7 @@ class LookupRef * =COLUMN([cellAddress]) * * @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) { @@ -109,6 +110,7 @@ class LookupRef if (is_array($cellAddress)) { foreach ($cellAddress as $columnKey => $value) { $columnKey = preg_replace('/[^a-z]/i', '', $columnKey); + return (integer) \PhpSpreadsheet\Cell::columnIndexFromString($columnKey); } } else { @@ -119,19 +121,20 @@ class LookupRef list($startAddress, $endAddress) = explode(':', $cellAddress); $startAddress = preg_replace('/[^a-z]/i', '', $startAddress); $endAddress = preg_replace('/[^a-z]/i', '', $endAddress); - $returnValue = array(); + $returnValue = []; do { $returnValue[] = (integer) \PhpSpreadsheet\Cell::columnIndexFromString($startAddress); } while ($startAddress++ != $endAddress); + return $returnValue; } else { $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress); + return (integer) \PhpSpreadsheet\Cell::columnIndexFromString($cellAddress); } } } - /** * COLUMNS * @@ -141,7 +144,7 @@ class LookupRef * =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 - * @return integer The number of columns in cellAddress + * @return int The number of columns in cellAddress */ public static function COLUMNS($cellAddress = null) { @@ -162,7 +165,6 @@ class LookupRef } } - /** * ROW * @@ -175,7 +177,7 @@ class LookupRef * =ROW([cellAddress]) * * @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) { @@ -197,19 +199,20 @@ class LookupRef list($startAddress, $endAddress) = explode(':', $cellAddress); $startAddress = preg_replace('/[^0-9]/', '', $startAddress); $endAddress = preg_replace('/[^0-9]/', '', $endAddress); - $returnValue = array(); + $returnValue = []; do { $returnValue[][] = (integer) $startAddress; } while ($startAddress++ != $endAddress); + return $returnValue; } else { list($cellAddress) = explode(':', $cellAddress); + return (integer) preg_replace('/[^0-9]/', '', $cellAddress); } } } - /** * ROWS * @@ -219,7 +222,7 @@ class LookupRef * =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 - * @return integer The number of rows in cellAddress + * @return int The number of rows in cellAddress */ public static function ROWS($cellAddress = null) { @@ -240,14 +243,12 @@ class LookupRef } } - /** * HYPERLINK * * Excel Function: * =HYPERLINK(linkURL,displayName) * - * @access public * @category Logical Functions * @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 @@ -259,7 +260,7 @@ class LookupRef $args = func_get_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); if ((!is_object($pCell)) || (trim($linkURL) == '')) { @@ -276,7 +277,6 @@ class LookupRef return $displayName; } - /** * INDIRECT * @@ -293,11 +293,10 @@ class LookupRef * @return mixed The cells referenced by cellAddress * * @todo Support for the optional a1 parameter introduced in Excel 2010 - * */ public static function INDIRECT($cellAddress = null, \PhpSpreadsheet\Cell $pCell = null) { - $cellAddress = Functions::flattenSingleValue($cellAddress); + $cellAddress = Functions::flattenSingleValue($cellAddress); if (is_null($cellAddress) || $cellAddress === '') { return Functions::REF(); } @@ -308,9 +307,9 @@ class LookupRef list($cellAddress1, $cellAddress2) = explode(':', $cellAddress); } - if ((!preg_match('/^'.\PhpSpreadsheet\Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $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_CELLREF . '$/i', $cellAddress1, $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)) { return Functions::REF(); } @@ -336,7 +335,6 @@ class LookupRef return \PhpSpreadsheet\Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); } - /** * OFFSET * @@ -364,10 +362,10 @@ class LookupRef */ 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); - $height = Functions::flattenSingleValue($height); - $width = Functions::flattenSingleValue($width); + $height = Functions::flattenSingleValue($height); + $width = Functions::flattenSingleValue($width); if ($cellAddress == null) { return 0; } @@ -379,12 +377,12 @@ class LookupRef } $sheetName = null; - if (strpos($cellAddress, "!")) { - list($sheetName, $cellAddress) = explode("!", $cellAddress); + if (strpos($cellAddress, '!')) { + list($sheetName, $cellAddress) = explode('!', $cellAddress); $sheetName = trim($sheetName, "'"); } - if (strpos($cellAddress, ":")) { - list($startCell, $endCell) = explode(":", $cellAddress); + if (strpos($cellAddress, ':')) { + list($startCell, $endCell) = explode(':', $cellAddress); } else { $startCell = $endCell = $cellAddress; } @@ -417,9 +415,9 @@ class LookupRef } $endCellColumn = \PhpSpreadsheet\Cell::stringFromColumnIndex($endCellColumn); - $cellAddress = $startCellColumn.$startCellRow; + $cellAddress = $startCellColumn . $startCellRow; if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { - $cellAddress .= ':'.$endCellColumn.$endCellRow; + $cellAddress .= ':' . $endCellColumn . $endCellRow; } if ($sheetName !== null) { @@ -431,7 +429,6 @@ class LookupRef return \PhpSpreadsheet\Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); } - /** * CHOOSE * @@ -476,7 +473,6 @@ class LookupRef } } - /** * MATCH * @@ -488,13 +484,13 @@ class LookupRef * @param lookup_value The value that you want to match in lookup_array * @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. - * @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) { $lookup_array = Functions::flattenArray($lookup_array); $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 $lookup_value = strtolower($lookup_value); @@ -526,7 +522,7 @@ class LookupRef $lookup_array[$i] = strtolower($lookupArrayValue); } 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; } else { // the previous cell was the match - return $keySet[$i-1]+1; + return $keySet[$i - 1] + 1; } } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) { $i = array_search($i, $keySet); @@ -564,7 +560,7 @@ class LookupRef break; } else { // 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(); } - /** * INDEX * @@ -607,7 +602,7 @@ class LookupRef return $arrayValues; } $rowNum = $rowKeys[--$rowNum]; - $returnArray = array(); + $returnArray = []; foreach ($arrayValues as $arrayColumn) { if (is_array($arrayColumn)) { if (isset($arrayColumn[$rowNum])) { @@ -619,6 +614,7 @@ class LookupRef return $arrayValues[$rowNum]; } } + return $returnArray; } $columnNum = $columnKeys[--$columnNum]; @@ -632,7 +628,6 @@ class LookupRef return $arrayValues[$rowNum][$columnNum]; } - /** * TRANSPOSE * @@ -643,9 +638,9 @@ class LookupRef */ public static function TRANSPOSE($matrixData) { - $returnMatrix = array(); + $returnMatrix = []; if (!is_array($matrixData)) { - $matrixData = array(array($matrixData)); + $matrixData = [[$matrixData]]; } $column = 0; @@ -657,10 +652,10 @@ class LookupRef } ++$column; } + return $returnMatrix; } - private static function vlookupSort($a, $b) { reset($a); @@ -668,10 +663,10 @@ class LookupRef if (($aLower = strtolower($a[$firstColumn])) == ($bLower = strtolower($b[$firstColumn]))) { return 0; } + return ($aLower < $bLower) ? -1 : 1; } - /** * 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. @@ -683,8 +678,8 @@ class LookupRef */ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - $index_number = Functions::flattenSingleValue($index_number); + $lookup_value = Functions::flattenSingleValue($lookup_value); + $index_number = Functions::flattenSingleValue($index_number); $not_exact_match = Functions::flattenSingleValue($not_exact_match); // index_number must be greater than or equal to 1 @@ -708,7 +703,7 @@ class LookupRef } if (!$not_exact_match) { - uasort($lookup_array, array('self', 'vlookupSort')); + uasort($lookup_array, ['self', 'vlookupSort']); } $rowNumber = $rowValue = false; @@ -738,7 +733,6 @@ class LookupRef return Functions::NA(); } - /** * 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. @@ -750,9 +744,9 @@ class LookupRef */ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - $index_number = Functions::flattenSingleValue($index_number); - $not_exact_match = Functions::flattenSingleValue($not_exact_match); + $lookup_value = Functions::flattenSingleValue($lookup_value); + $index_number = Functions::flattenSingleValue($index_number); + $not_exact_match = Functions::flattenSingleValue($not_exact_match); // index_number must be greater than or equal to 1 if ($index_number < 1) { @@ -769,7 +763,7 @@ class LookupRef return Functions::REF(); } else { $columnKeys = array_keys($lookup_array[$firstRow]); - $firstkey = $f[0] - 1; + $firstkey = $f[0] - 1; $returnColumn = $firstkey + $index_number; $firstColumn = array_shift($f); } @@ -801,7 +795,6 @@ class LookupRef return Functions::NA(); } - /** * LOOKUP * 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)) { $k = array_keys($value); $key1 = $key2 = array_shift($k); - $key2++; + ++$key2; $dataValue1 = $value[$key1]; } else { $key1 = 0; @@ -862,7 +855,7 @@ class LookupRef if (is_array($dataValue2)) { $dataValue2 = array_shift($dataValue2); } - $value = array($key1 => $dataValue1, $key2 => $dataValue2); + $value = [$key1 => $dataValue1, $key2 => $dataValue2]; } unset($value); } diff --git a/src/PhpSpreadsheet/Calculation/MathTrig.php b/src/PhpSpreadsheet/Calculation/MathTrig.php index 99be5539..e9fe621d 100644 --- a/src/PhpSpreadsheet/Calculation/MathTrig.php +++ b/src/PhpSpreadsheet/Calculation/MathTrig.php @@ -33,7 +33,7 @@ class MathTrig { $startVal = floor(sqrt($value)); - $factorArray = array(); + $factorArray = []; for ($i = $startVal; $i > 1; --$i) { if (($value % $i) == 0) { $factorArray = array_merge($factorArray, self::factors($value / $i)); @@ -45,19 +45,18 @@ class MathTrig } if (!empty($factorArray)) { rsort($factorArray); + return $factorArray; } else { - return array((integer) $value); + return [(integer) $value]; } } - private static function romanCut($num, $n) { - return ($num - ($num % $n ) ) / $n; + return ($num - ($num % $n)) / $n; } - /** * ATAN2 * @@ -74,7 +73,6 @@ class MathTrig * Excel Function: * ATAN2(xCoordinate,yCoordinate) * - * @access public * @category Mathematical and Trigonometric Functions * @param float $xCoordinate The x-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; if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) && - ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) { - $xCoordinate = (float) $xCoordinate; - $yCoordinate = (float) $yCoordinate; + ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) { + $xCoordinate = (float) $xCoordinate; + $yCoordinate = (float) $yCoordinate; if (($xCoordinate == 0) && ($yCoordinate == 0)) { return Functions::DIV0(); @@ -99,10 +97,10 @@ class MathTrig return atan2($yCoordinate, $xCoordinate); } + return Functions::VALUE(); } - /** * CEILING * @@ -114,7 +112,6 @@ class MathTrig * Excel Function: * CEILING(number[,significance]) * - * @access public * @category Mathematical and Trigonometric Functions * @param float $number The number 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) { - $number = Functions::flattenSingleValue($number); + $number = Functions::flattenSingleValue($number); $significance = Functions::flattenSingleValue($significance); if ((is_null($significance)) && @@ -131,7 +128,7 @@ class MathTrig } if ((is_numeric($number)) && (is_numeric($significance))) { - if (($number == 0.0 ) || ($significance == 0.0)) { + if (($number == 0.0) || ($significance == 0.0)) { return 0.0; } elseif (self::SIGN($number) == self::SIGN($significance)) { return ceil($number / $significance) * $significance; @@ -139,10 +136,10 @@ class MathTrig return Functions::NAN(); } } + return Functions::VALUE(); } - /** * COMBIN * @@ -152,7 +149,6 @@ class MathTrig * Excel Function: * COMBIN(numObjs,numInSet) * - * @access public * @category Mathematical and Trigonometric Functions * @param int $numObjs Number of different objects * @param int $numInSet Number of objects in each combination @@ -160,8 +156,8 @@ class MathTrig */ public static function COMBIN($numObjs, $numInSet) { - $numObjs = Functions::flattenSingleValue($numObjs); - $numInSet = Functions::flattenSingleValue($numInSet); + $numObjs = Functions::flattenSingleValue($numObjs); + $numInSet = Functions::flattenSingleValue($numInSet); if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { if ($numObjs < $numInSet) { @@ -169,12 +165,13 @@ class MathTrig } elseif ($numInSet < 0) { return Functions::NAN(); } + return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet); } + return Functions::VALUE(); } - /** * EVEN * @@ -187,7 +184,6 @@ class MathTrig * Excel Function: * EVEN(number) * - * @access public * @category Mathematical and Trigonometric Functions * @param float $number Number to round * @return int Rounded Number @@ -204,12 +200,13 @@ class MathTrig if (is_numeric($number)) { $significance = 2 * self::SIGN($number); + return (int) self::CEILING($number, $significance); } + return Functions::VALUE(); } - /** * FACT * @@ -219,14 +216,13 @@ class MathTrig * Excel Function: * FACT(factVal) * - * @access public * @category Mathematical and Trigonometric Functions * @param float $factVal Factorial Value * @return int Factorial */ public static function FACT($factVal) { - $factVal = Functions::flattenSingleValue($factVal); + $factVal = Functions::flattenSingleValue($factVal); if (is_numeric($factVal)) { if ($factVal < 0) { @@ -243,12 +239,13 @@ class MathTrig while ($factLoop > 1) { $factorial *= $factLoop--; } - return $factorial ; + + return $factorial; } + return Functions::VALUE(); } - /** * FACTDOUBLE * @@ -257,17 +254,16 @@ class MathTrig * Excel Function: * FACTDOUBLE(factVal) * - * @access public * @category Mathematical and Trigonometric Functions * @param float $factVal Factorial Value * @return int Double Factorial */ public static function FACTDOUBLE($factVal) { - $factLoop = Functions::flattenSingleValue($factVal); + $factLoop = Functions::flattenSingleValue($factVal); if (is_numeric($factLoop)) { - $factLoop = floor($factLoop); + $factLoop = floor($factLoop); if ($factVal < 0) { return Functions::NAN(); } @@ -276,12 +272,13 @@ class MathTrig $factorial *= $factLoop--; --$factLoop; } - return $factorial ; + + return $factorial; } + return Functions::VALUE(); } - /** * FLOOR * @@ -290,7 +287,6 @@ class MathTrig * Excel Function: * FLOOR(number[,significance]) * - * @access public * @category Mathematical and Trigonometric Functions * @param float $number Number to round * @param float $significance Significance @@ -298,12 +294,12 @@ class MathTrig */ public static function FLOOR($number, $significance = null) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); + $number = Functions::flattenSingleValue($number); + $significance = Functions::flattenSingleValue($significance); if ((is_null($significance)) && (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)) { - $significance = $number/abs($number); + $significance = $number / abs($number); } if ((is_numeric($number)) && (is_numeric($significance))) { @@ -321,7 +317,6 @@ class MathTrig return Functions::VALUE(); } - /** * GCD * @@ -332,15 +327,14 @@ class MathTrig * Excel Function: * GCD(number1[,number2[, ...]]) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values - * @return integer Greatest Common Divisor + * @return int Greatest Common Divisor */ public static function GCD() { $returnValue = 1; - $allValuesFactors = array(); + $allValuesFactors = []; // Loop through arguments foreach (Functions::flattenArray(func_get_args()) as $value) { if (!is_numeric($value)) { @@ -360,7 +354,7 @@ class MathTrig } $mergedArray = $allValuesFactors[0]; - for ($i=1; $i < $allValuesCount; ++$i) { + for ($i = 1; $i < $allValuesCount; ++$i) { $mergedArray = array_intersect_key($mergedArray, $allValuesFactors[$i]); } $mergedArrayValues = count($mergedArray); @@ -382,6 +376,7 @@ class MathTrig foreach ($mergedArray as $key => $value) { $returnValue *= pow($key, $value); } + return $returnValue; } else { $keys = array_keys($mergedArray); @@ -394,11 +389,11 @@ class MathTrig } } } + return pow($key, $value); } } - /** * INT * @@ -407,14 +402,13 @@ class MathTrig * Excel Function: * INT(number) * - * @access public * @category Mathematical and Trigonometric Functions * @param float $number Number to cast to an integer - * @return integer Integer value + * @return int Integer value */ public static function INT($number) { - $number = Functions::flattenSingleValue($number); + $number = Functions::flattenSingleValue($number); if (is_null($number)) { return 0; @@ -424,10 +418,10 @@ class MathTrig if (is_numeric($number)) { return (int) floor($number); } + return Functions::VALUE(); } - /** * LCM * @@ -439,7 +433,6 @@ class MathTrig * Excel Function: * LCM(number1[,number2[, ...]]) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @return int Lowest Common Multiplier @@ -447,7 +440,7 @@ class MathTrig public static function LCM() { $returnValue = 1; - $allPoweredFactors = array(); + $allPoweredFactors = []; // Loop through arguments foreach (Functions::flattenArray(func_get_args()) as $value) { if (!is_numeric($value)) { @@ -460,7 +453,7 @@ class MathTrig } $myFactors = self::factors(floor($value)); $myCountedFactors = array_count_values($myFactors); - $myPoweredFactors = array(); + $myPoweredFactors = []; foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor, $myCountedPower); } @@ -477,10 +470,10 @@ class MathTrig foreach ($allPoweredFactors as $allPoweredFactor) { $returnValue *= (integer) $allPoweredFactor; } + return $returnValue; } - /** * LOG_BASE * @@ -489,7 +482,6 @@ class MathTrig * Excel Function: * LOG(number[,base]) * - * @access public * @category Mathematical and Trigonometric Functions * @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. @@ -497,8 +489,8 @@ class MathTrig */ public static function logBase($number = null, $base = 10) { - $number = Functions::flattenSingleValue($number); - $base = (is_null($base)) ? 10 : (float) Functions::flattenSingleValue($base); + $number = Functions::flattenSingleValue($number); + $base = (is_null($base)) ? 10 : (float) Functions::flattenSingleValue($base); if ((!is_numeric($base)) || (!is_numeric($number))) { return Functions::VALUE(); @@ -506,10 +498,10 @@ class MathTrig if (($base <= 0) || ($number <= 0)) { return Functions::NAN(); } + return log($number, $base); } - /** * MDETERM * @@ -518,22 +510,21 @@ class MathTrig * Excel Function: * MDETERM(array) * - * @access public * @category Mathematical and Trigonometric Functions * @param array $matrixValues A matrix of values * @return float */ public static function MDETERM($matrixValues) { - $matrixData = array(); + $matrixData = []; if (!is_array($matrixValues)) { - $matrixValues = array(array($matrixValues)); + $matrixValues = [[$matrixValues]]; } $row = $maxColumn = 0; foreach ($matrixValues as $matrixRow) { if (!is_array($matrixRow)) { - $matrixRow = array($matrixRow); + $matrixRow = [$matrixRow]; } $column = 0; foreach ($matrixRow as $matrixCell) { @@ -554,13 +545,13 @@ class MathTrig try { $matrix = new \PhpSpreadsheet\Shared\JAMA\Matrix($matrixData); + return $matrix->det(); } catch (\PhpSpreadsheet\Exception $ex) { return Functions::VALUE(); } } - /** * MINVERSE * @@ -569,22 +560,21 @@ class MathTrig * Excel Function: * MINVERSE(array) * - * @access public * @category Mathematical and Trigonometric Functions * @param array $matrixValues A matrix of values * @return array */ public static function MINVERSE($matrixValues) { - $matrixData = array(); + $matrixData = []; if (!is_array($matrixValues)) { - $matrixValues = array(array($matrixValues)); + $matrixValues = [[$matrixValues]]; } $row = $maxColumn = 0; foreach ($matrixValues as $matrixRow) { if (!is_array($matrixRow)) { - $matrixRow = array($matrixRow); + $matrixRow = [$matrixRow]; } $column = 0; foreach ($matrixRow as $matrixCell) { @@ -607,13 +597,13 @@ class MathTrig try { $matrix = new \PhpSpreadsheet\Shared\JAMA\Matrix($matrixData); + return $matrix->inverse()->getArray(); } catch (\PhpSpreadsheet\Exception $ex) { return Functions::VALUE(); } } - /** * MMULT * @@ -623,19 +613,19 @@ class MathTrig */ public static function MMULT($matrixData1, $matrixData2) { - $matrixAData = $matrixBData = array(); + $matrixAData = $matrixBData = []; if (!is_array($matrixData1)) { - $matrixData1 = array(array($matrixData1)); + $matrixData1 = [[$matrixData1]]; } if (!is_array($matrixData2)) { - $matrixData2 = array(array($matrixData2)); + $matrixData2 = [[$matrixData2]]; } try { $rowA = 0; foreach ($matrixData1 as $matrixRow) { if (!is_array($matrixRow)) { - $matrixRow = array($matrixRow); + $matrixRow = [$matrixRow]; } $columnA = 0; foreach ($matrixRow as $matrixCell) { @@ -651,7 +641,7 @@ class MathTrig $rowB = 0; foreach ($matrixData2 as $matrixRow) { if (!is_array($matrixRow)) { - $matrixRow = array($matrixRow); + $matrixRow = [$matrixRow]; } $columnB = 0; foreach ($matrixRow as $matrixCell) { @@ -672,11 +662,11 @@ class MathTrig return $matrixA->times($matrixB)->getArray(); } catch (\PhpSpreadsheet\Exception $ex) { var_dump($ex->getMessage()); + return Functions::VALUE(); } } - /** * MOD * @@ -700,7 +690,6 @@ class MathTrig return fmod($a, $b); } - /** * MROUND * @@ -712,7 +701,7 @@ class MathTrig */ public static function MROUND($number, $multiple) { - $number = Functions::flattenSingleValue($number); + $number = Functions::flattenSingleValue($number); $multiple = Functions::flattenSingleValue($multiple); if ((is_numeric($number)) && (is_numeric($multiple))) { @@ -721,14 +710,16 @@ class MathTrig } if ((self::SIGN($number)) == (self::SIGN($multiple))) { $multiplier = 1 / $multiple; + return round($number * $multiplier) / $multiplier; } + return Functions::NAN(); } + return Functions::VALUE(); } - /** * MULTINOMIAL * @@ -758,12 +749,13 @@ class MathTrig // Return if ($summer > 0) { $summer = self::FACT($summer); + return $summer / $divisor; } + return 0; } - /** * ODD * @@ -793,10 +785,10 @@ class MathTrig return (int) $result; } + return Functions::VALUE(); } - /** * POWER * @@ -808,8 +800,8 @@ class MathTrig */ public static function POWER($x = 0, $y = 2) { - $x = Functions::flattenSingleValue($x); - $y = Functions::flattenSingleValue($y); + $x = Functions::flattenSingleValue($x); + $y = Functions::flattenSingleValue($y); // Validate parameters if ($x == 0.0 && $y == 0.0) { @@ -820,10 +812,10 @@ class MathTrig // Return $result = pow($x, $y); + return (!is_nan($result) && !is_infinite($result)) ? $result : Functions::NAN(); } - /** * PRODUCT * @@ -832,7 +824,6 @@ class MathTrig * Excel Function: * PRODUCT(value1[,value2[, ...]]) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @return float @@ -858,10 +849,10 @@ class MathTrig if (is_null($returnValue)) { return 0; } + return $returnValue; } - /** * QUOTIENT * @@ -871,7 +862,6 @@ class MathTrig * Excel Function: * QUOTIENT(value1[,value2[, ...]]) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @return float @@ -901,7 +891,6 @@ class MathTrig return intval($returnValue); } - /** * RAND * @@ -921,11 +910,10 @@ class MathTrig } } - public static function ROMAN($aValue, $style = 0) { - $aValue = Functions::flattenSingleValue($aValue); - $style = (is_null($style)) ? 0 : (integer) Functions::flattenSingleValue($style); + $aValue = Functions::flattenSingleValue($aValue); + $style = (is_null($style)) ? 0 : (integer) Functions::flattenSingleValue($style); if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) { return Functions::VALUE(); } @@ -934,10 +922,10 @@ class MathTrig return ''; } - $mill = array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM'); - $cent = array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'); - $tens = array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'); - $ones = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'); + $mill = ['', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM']; + $cent = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; + $tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; + $ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; $roman = ''; while ($aValue > 5999) { @@ -951,10 +939,9 @@ class MathTrig $t = self::romanCut($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 * @@ -966,8 +953,8 @@ class MathTrig */ public static function ROUNDUP($number, $digits) { - $number = Functions::flattenSingleValue($number); - $digits = Functions::flattenSingleValue($digits); + $number = Functions::flattenSingleValue($number); + $digits = Functions::flattenSingleValue($digits); if ((is_numeric($number)) && (is_numeric($digits))) { $significance = pow(10, (int) $digits); @@ -977,10 +964,10 @@ class MathTrig return ceil($number * $significance) / $significance; } } + return Functions::VALUE(); } - /** * ROUNDDOWN * @@ -992,8 +979,8 @@ class MathTrig */ public static function ROUNDDOWN($number, $digits) { - $number = Functions::flattenSingleValue($number); - $digits = Functions::flattenSingleValue($digits); + $number = Functions::flattenSingleValue($number); + $digits = Functions::flattenSingleValue($digits); if ((is_numeric($number)) && (is_numeric($digits))) { $significance = pow(10, (int) $digits); @@ -1003,10 +990,10 @@ class MathTrig return floor($number * $significance) / $significance; } } + return Functions::VALUE(); } - /** * SERIESSUM * @@ -1040,12 +1027,13 @@ class MathTrig return Functions::VALUE(); } } + return $returnValue; } + return Functions::VALUE(); } - /** * SIGN * @@ -1057,7 +1045,7 @@ class MathTrig */ public static function SIGN($number) { - $number = Functions::flattenSingleValue($number); + $number = Functions::flattenSingleValue($number); if (is_bool($number)) { return (int) $number; @@ -1066,12 +1054,13 @@ class MathTrig if ($number == 0.0) { return 0; } + return $number / abs($number); } + return Functions::VALUE(); } - /** * SQRTPI * @@ -1082,18 +1071,19 @@ class MathTrig */ public static function SQRTPI($number) { - $number = Functions::flattenSingleValue($number); + $number = Functions::flattenSingleValue($number); if (is_numeric($number)) { if ($number < 0) { return Functions::NAN(); } - return sqrt($number * M_PI) ; + + return sqrt($number * M_PI); } + return Functions::VALUE(); } - /** * SUBTOTAL * @@ -1137,10 +1127,10 @@ class MathTrig return Statistical::VARP($aArgs); } } + return Functions::VALUE(); } - /** * SUM * @@ -1149,7 +1139,6 @@ class MathTrig * Excel Function: * SUM(value1[,value2[, ...]]) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @return float @@ -1169,7 +1158,6 @@ class MathTrig return $returnValue; } - /** * SUMIF * @@ -1178,13 +1166,12 @@ class MathTrig * Excel Function: * SUMIF(value1[,value2[, ...]],condition) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @param string $condition The criteria that defines which cells will be summed. * @return float */ - public static function SUMIF($aArgs, $condition, $sumArgs = array()) + public static function SUMIF($aArgs, $condition, $sumArgs = []) { $returnValue = 0; @@ -1201,7 +1188,7 @@ class MathTrig $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); } - $testCondition = '='.$arg.$condition; + $testCondition = '=' . $arg . $condition; if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { // Is it a value within our criteria $returnValue += $sumArgs[$key]; @@ -1211,7 +1198,7 @@ class MathTrig return $returnValue; } - /** + /** * SUMIFS * * Counts the number of cells that contain numbers within the list of arguments @@ -1219,7 +1206,6 @@ class MathTrig * Excel Function: * SUMIFS(value1[,value2[, ...]],condition) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @param string $condition The criteria that defines which cells will be summed. @@ -1248,7 +1234,7 @@ class MathTrig if (!is_numeric($arg)) { $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); } - $testCondition = '='.$arg.$condition; + $testCondition = '=' . $arg . $condition; if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { // Is it a value within our criteria $returnValue += $sumArgs[$key]; @@ -1266,7 +1252,6 @@ class MathTrig * Excel Function: * SUMPRODUCT(value1[,value2[, ...]]) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @return float @@ -1278,7 +1263,7 @@ class MathTrig $wrkArray = Functions::flattenArray(array_shift($arrayList)); $wrkCellCount = count($wrkArray); - for ($i=0; $i< $wrkCellCount; ++$i) { + for ($i = 0; $i < $wrkCellCount; ++$i) { if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { $wrkArray[$i] = 0; } @@ -1302,7 +1287,6 @@ class MathTrig return array_sum($wrkArray); } - /** * SUMSQ * @@ -1311,7 +1295,6 @@ class MathTrig * Excel Function: * SUMSQ(value1[,value2[, ...]]) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @return float @@ -1331,7 +1314,6 @@ class MathTrig return $returnValue; } - /** * SUMX2MY2 * @@ -1356,7 +1338,6 @@ class MathTrig return $result; } - /** * SUMX2PY2 * @@ -1381,7 +1362,6 @@ class MathTrig return $result; } - /** * SUMXMY2 * @@ -1406,7 +1386,6 @@ class MathTrig return $result; } - /** * TRUNC * @@ -1418,8 +1397,8 @@ class MathTrig */ public static function TRUNC($value = 0, $digits = 0) { - $value = Functions::flattenSingleValue($value); - $digits = Functions::flattenSingleValue($digits); + $value = Functions::flattenSingleValue($value); + $digits = Functions::flattenSingleValue($digits); // Validate parameters if ((!is_numeric($value)) || (!is_numeric($digits))) { @@ -1430,7 +1409,7 @@ class MathTrig // Truncate $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; } diff --git a/src/PhpSpreadsheet/Calculation/Statistical.php b/src/PhpSpreadsheet/Calculation/Statistical.php index ac3cc739..7bb2cd8c 100644 --- a/src/PhpSpreadsheet/Calculation/Statistical.php +++ b/src/PhpSpreadsheet/Calculation/Statistical.php @@ -2,16 +2,16 @@ namespace PhpSpreadsheet\Calculation; -/** LOG_GAMMA_X_MAX_VALUE */ +/* LOG_GAMMA_X_MAX_VALUE */ define('LOG_GAMMA_X_MAX_VALUE', 2.55e305); -/** XMININ */ +/* XMININ */ define('XMININ', 2.23e-308); -/** EPS */ +/* EPS */ define('EPS', 2.22e-16); -/** SQRT2PI */ +/* SQRT2PI */ define('SQRT2PI', 2.5066282746310005024157652848110452530069867406099); /** @@ -41,10 +41,10 @@ class Statistical private static function checkTrendArrays(&$array1, &$array2) { if (!is_array($array1)) { - $array1 = array($array1); + $array1 = [$array1]; } if (!is_array($array2)) { - $array2 = array($array2); + $array2 = [$array2]; } $array1 = Functions::flattenArray($array1); @@ -67,7 +67,6 @@ class Statistical return true; } - /** * Beta function. * @@ -86,7 +85,6 @@ class Statistical } } - /** * Incomplete beta function * @@ -116,10 +114,9 @@ class Statistical } } - // Function cache for logBeta function - private static $logBetaCacheP = 0.0; - private static $logBetaCacheQ = 0.0; + private static $logBetaCacheP = 0.0; + private static $logBetaCacheQ = 0.0; private static $logBetaCacheResult = 0.0; /** @@ -141,10 +138,10 @@ class Statistical self::$logBetaCacheResult = self::logGamma($p) + self::logGamma($q) - self::logGamma($p + $q); } } + return self::$logBetaCacheResult; } - /** * Evaluates of continued fraction part of incomplete beta function. * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). @@ -162,12 +159,12 @@ class Statistical } $h = 1.0 / $h; $frac = $h; - $m = 1; + $m = 1; $delta = 0.0; - while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION) { + while ($m <= MAX_ITERATIONS && abs($delta - 1.0) > PRECISION) { $m2 = 2 * $m; // even index for d - $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2)); + $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2)); $h = 1.0 + $d * $h; if (abs($h) < XMININ) { $h = XMININ; @@ -193,56 +190,56 @@ class Statistical $frac *= $delta; ++$m; } + return $frac; } - - /** - * logGamma function - * - * @version 1.1 - * @author Jaco van Kooten - * - * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. - * - * The natural logarithm of the gamma function.
- * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
- * Applied Mathematics Division
- * Argonne National Laboratory
- * Argonne, IL 60439
- *

- * References: - *

    - *
  1. W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural - * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
  2. - *
  3. K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
  4. - *
  5. Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
  6. - *
- *

- *

- * From the original documentation: - *

- *

- * This routine calculates the LOG(GAMMA) function for a positive real argument X. - * Computation is based on an algorithm outlined in references 1 and 2. - * The program uses rational functions that theoretically approximate LOG(GAMMA) - * to at least 18 significant decimal digits. The approximation for X > 12 is from - * reference 3, while approximations for X < 12.0 are similar to those in reference - * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, - * the compiler, the intrinsic functions, and proper selection of the - * machine-dependent constants. - *

- *

- * Error returns:
- * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. - * The computation is believed to be free of underflow and overflow. - *

- * @return MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 - */ +/** + * logGamma function + * + * @version 1.1 + * @author Jaco van Kooten + * + * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. + * + * The natural logarithm of the gamma function.
+ * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
+ * Applied Mathematics Division
+ * Argonne National Laboratory
+ * Argonne, IL 60439
+ *

+ * References: + *

    + *
  1. W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural + * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
  2. + *
  3. K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
  4. + *
  5. Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
  6. + *
+ *

+ *

+ * From the original documentation: + *

+ *

+ * This routine calculates the LOG(GAMMA) function for a positive real argument X. + * Computation is based on an algorithm outlined in references 1 and 2. + * The program uses rational functions that theoretically approximate LOG(GAMMA) + * to at least 18 significant decimal digits. The approximation for X > 12 is from + * reference 3, while approximations for X < 12.0 are similar to those in reference + * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, + * the compiler, the intrinsic functions, and proper selection of the + * machine-dependent constants. + *

+ *

+ * Error returns:
+ * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. + * The computation is believed to be free of underflow and overflow. + *

+ * @return MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 + */ // Function cache for logGamma private static $logGammaCacheResult = 0.0; - private static $logGammaCacheX = 0.0; + private static $logGammaCacheX = 0.0; private static function logGamma($x) { @@ -251,7 +248,7 @@ class Statistical static $lg_d2 = 0.4227843350984671393993777; static $lg_d4 = 1.791759469228055000094023; - static $lg_p1 = array( + static $lg_p1 = [ 4.945235359296727046734888, 201.8112620856775083915565, 2290.838373831346393026739, @@ -259,9 +256,9 @@ class Statistical 28557.24635671635335736389, 38484.96228443793359990269, 26377.48787624195437963534, - 7225.813979700288197698961 - ); - static $lg_p2 = array( + 7225.813979700288197698961, + ]; + static $lg_p2 = [ 4.974607845568932035012064, 542.4138599891070494101986, 15506.93864978364947665077, @@ -269,9 +266,9 @@ class Statistical 1088204.76946882876749847, 3338152.967987029735917223, 5106661.678927352456275255, - 3074109.054850539556250927 - ); - static $lg_p4 = array( + 3074109.054850539556250927, + ]; + static $lg_p4 = [ 14745.02166059939948905062, 2426813.369486704502836312, 121475557.4045093227939592, @@ -279,9 +276,9 @@ class Statistical 29403789566.34553899906876, 170266573776.5398868392998, 492612579337.743088758812, - 560625185622.3951465078242 - ); - static $lg_q1 = array( + 560625185622.3951465078242, + ]; + static $lg_q1 = [ 67.48212550303777196073036, 1113.332393857199323513008, 7738.757056935398733233834, @@ -289,9 +286,9 @@ class Statistical 54993.10206226157329794414, 61611.22180066002127833352, 36351.27591501940507276287, - 8785.536302431013170870835 - ); - static $lg_q2 = array( + 8785.536302431013170870835, + ]; + static $lg_q2 = [ 183.0328399370592604055942, 7765.049321445005871323047, 133190.3827966074194402448, @@ -299,9 +296,9 @@ class Statistical 5267964.117437946917577538, 13467014.54311101692290052, 17827365.30353274213975932, - 9533095.591844353613395747 - ); - static $lg_q4 = array( + 9533095.591844353613395747, + ]; + static $lg_q4 = [ 2690.530175870899333379843, 639388.5654300092398984238, 41355999.30241388052042842, @@ -309,22 +306,21 @@ class Statistical 14886137286.78813811542398, 101680358627.2438228077304, 341747634550.7377132798597, - 446315818741.9713286462081 - ); - static $lg_c = array( + 446315818741.9713286462081, + ]; + static $lg_c = [ -0.001910444077728, 8.4171387781295e-4, -5.952379913043012e-4, 7.93650793500350248e-4, -0.002777777777777681622553, 0.08333333333333333331554247, - 0.0057083835261 - ); + 0.0057083835261, + ]; // Rough estimate of the fourth root of logGamma_xBig static $lg_frtbig = 2.25e76; - static $pnt68 = 0.6796875; - + static $pnt68 = 0.6796875; if ($x == self::$logGammaCacheX) { return self::$logGammaCacheResult; @@ -414,10 +410,10 @@ class Statistical // ------------------------------ self::$logGammaCacheX = $x; self::$logGammaCacheResult = $res; + return $res; } - // // Private implementation of the incomplete Gamma function // @@ -425,16 +421,16 @@ class Statistical { static $max = 32; $summer = 0; - for ($n=0; $n<=$max; ++$n) { + for ($n = 0; $n <= $max; ++$n) { $divisor = $a; - for ($i=1; $i<=$n; ++$i) { + for ($i = 1; $i <= $n; ++$i) { $divisor *= ($a + $i); } $summer += (pow($x, $n) / $divisor); } - return pow($x, $a) * exp(0-$x) * $summer; - } + return pow($x, $a) * exp(0 - $x) * $summer; + } // // Private implementation of the Gamma function @@ -446,27 +442,27 @@ class Statistical } static $p0 = 1.000000000190015; - static $p = array( + static $p = [ 1 => 76.18009172947146, 2 => -86.50532032941677, 3 => 24.01409824083091, 4 => -1.231739572450155, 5 => 1.208650973866179e-3, - 6 => -5.395239384953e-6 - ); + 6 => -5.395239384953e-6, + ]; $y = $x = $data; $tmp = $x + 5.5; $tmp -= ($x + 0.5) * log($tmp); $summer = $p0; - for ($j=1; $j<=6; ++$j) { + for ($j = 1; $j <= 6; ++$j) { $summer += ($p[$j] / ++$y); } + return exp(0 - $tmp + log(SQRT2PI * $summer / $x)); } - /*************************************************************************** * inverse_ncdf.php * ------------------- @@ -490,38 +486,38 @@ class Statistical // Input paramater is $p - probability - where 0 < p < 1. // Coefficients in rational approximations - static $a = array( + static $a = [ 1 => -3.969683028665376e+01, 2 => 2.209460984245205e+02, 3 => -2.759285104469687e+02, 4 => 1.383577518672690e+02, 5 => -3.066479806614716e+01, - 6 => 2.506628277459239e+00 - ); + 6 => 2.506628277459239e+00, + ]; - static $b = array( + static $b = [ 1 => -5.447609879822406e+01, 2 => 1.615858368580409e+02, 3 => -1.556989798598866e+02, 4 => 6.680131188771972e+01, - 5 => -1.328068155288572e+01 - ); + 5 => -1.328068155288572e+01, + ]; - static $c = array( + static $c = [ 1 => -7.784894002430293e-03, 2 => -3.223964580411365e-01, 3 => -2.400758277161838e+00, 4 => -2.549732539343734e+00, 5 => 4.374664141464968e+00, - 6 => 2.938163982698783e+00 - ); + 6 => 2.938163982698783e+00, + ]; - static $d = array( + static $d = [ 1 => 7.784695709041462e-03, 2 => 3.224671290700398e-01, 3 => 2.445134137142996e+00, - 4 => 3.754408661907416e+00 - ); + 4 => 3.754408661907416e+00, + ]; // Define lower and upper region break-points. $p_low = 0.02425; //Use lower region approx. below this @@ -530,17 +526,20 @@ class Statistical if (0 < $p && $p < $p_low) { // Rational approximation for lower region. $q = sqrt(-2 * log($p)); + return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } elseif ($p_low <= $p && $p <= $p_high) { // Rational approximation for central region. $q = $p - 0.5; $r = $q * $q; + return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); } elseif ($p_high < $p && $p < 1) { // Rational approximation for upper region. $q = sqrt(-2 * log(1 - $p)); + return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } @@ -548,7 +547,6 @@ class Statistical return Functions::NULL(); } - private static function inverseNcdf2($prob) { // Approximation of inverse standard normal CDF developed by @@ -589,10 +587,10 @@ class Statistical $z = -$z; } } + return $z; } // function inverseNcdf2() - private static function inverseNcdf3($p) { // ALGORITHM AS241 APPL. STATIST. (1988) VOL. 37, NO. 3. @@ -681,7 +679,7 @@ class Statistical $z = ((((((($c7 * $R + $c6) * $R + $c5) * $R + $c4) * $R + $c3) * $R + $c2) * $R + $c1) * $R + $c0) / ((((((($d7 * $R + $d6) * $R + $d5) * $R + $d4) * $R + $d3) * $R + $d2) * $R + $d1) * $R + 1); } else { - // computation for p near 0 or 1. + // computation for p near 0 or 1. $R = $R - $split2; $z = ((((((($e7 * $R + $e6) * $R + $e5) * $R + $e4) * $R + $e3) * $R + $e2) * $R + $e1) * $R + $e0) / ((((((($f7 * $R + $f6) * $R + $f5) * $R + $f4) * $R + $f3) * $R + $f2) * $R + $f1) * $R + 1); @@ -690,10 +688,10 @@ class Statistical $z = -$z; } } + return $z; } - /** * AVEDEV * @@ -703,7 +701,6 @@ class Statistical * Excel Function: * AVEDEV(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -738,12 +735,13 @@ class Statistical if ($aCount == 0) { return Functions::DIV0(); } + return $returnValue / $aCount; } + return Functions::NAN(); } - /** * AVERAGE * @@ -752,7 +750,6 @@ class Statistical * Excel Function: * AVERAGE(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -786,7 +783,6 @@ class Statistical } } - /** * AVERAGEA * @@ -795,7 +791,6 @@ class Statistical * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -833,7 +828,6 @@ class Statistical } } - /** * AVERAGEIF * @@ -842,14 +836,13 @@ class Statistical * Excel Function: * AVERAGEIF(value1[,value2[, ...]],condition) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @param string $condition The criteria that defines which cells will be checked. * @param mixed[] $averageArgs Data values * @return float */ - public static function AVERAGEIF($aArgs, $condition, $averageArgs = array()) + public static function AVERAGEIF($aArgs, $condition, $averageArgs = []) { $returnValue = 0; @@ -865,7 +858,7 @@ class Statistical if (!is_numeric($arg)) { $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); } - $testCondition = '='.$arg.$condition; + $testCondition = '=' . $arg . $condition; if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { if ((is_null($returnValue)) || ($arg > $returnValue)) { $returnValue += $arg; @@ -877,10 +870,10 @@ class Statistical if ($aCount > 0) { return $returnValue / $aCount; } + return Functions::DIV0(); } - /** * BETADIST * @@ -889,17 +882,16 @@ class Statistical * @param float $value Value at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution - * @param boolean $cumulative + * @param bool $cumulative * @return float - * */ public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1) { $value = Functions::flattenSingleValue($value); $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - $rMin = Functions::flattenSingleValue($rMin); - $rMax = Functions::flattenSingleValue($rMax); + $beta = Functions::flattenSingleValue($beta); + $rMin = Functions::flattenSingleValue($rMin); + $rMax = Functions::flattenSingleValue($rMax); if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { @@ -912,12 +904,13 @@ class Statistical } $value -= $rMin; $value /= ($rMax - $rMin); + return self::incompleteBeta($value, $alpha, $beta); } + return Functions::VALUE(); } - /** * BETAINV * @@ -928,17 +921,16 @@ class Statistical * @param float $beta Parameter to the distribution * @param float $rMin Minimum value * @param float $rMax Maximum value - * @param boolean $cumulative + * @param bool $cumulative * @return float - * */ public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1) { $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - $rMin = Functions::flattenSingleValue($rMin); - $rMax = Functions::flattenSingleValue($rMax); + $alpha = Functions::flattenSingleValue($alpha); + $beta = Functions::flattenSingleValue($beta); + $rMin = Functions::flattenSingleValue($rMin); + $rMax = Functions::flattenSingleValue($rMax); if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) { @@ -967,12 +959,13 @@ class Statistical if ($i == MAX_ITERATIONS) { return Functions::NA(); } + return round($rMin + $guess * ($rMax - $rMin), 12); } + return Functions::VALUE(); } - /** * BINOMDIST * @@ -985,16 +978,15 @@ class Statistical * @param float $value Number of successes in trials * @param float $trials Number of trials * @param float $probability Probability of success on each trial - * @param boolean $cumulative + * @param bool $cumulative * @return float * * @todo Cumulative distribution function - * */ public static function BINOMDIST($value, $trials, $probability, $cumulative) { - $value = floor(Functions::flattenSingleValue($value)); - $trials = floor(Functions::flattenSingleValue($trials)); + $value = floor(Functions::flattenSingleValue($value)); + $trials = floor(Functions::flattenSingleValue($trials)); $probability = Functions::flattenSingleValue($probability); if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) { @@ -1010,16 +1002,17 @@ class Statistical for ($i = 0; $i <= $value; ++$i) { $summer += MathTrig::COMBIN($trials, $i) * pow($probability, $i) * pow(1 - $probability, $trials - $i); } + return $summer; } else { - return MathTrig::COMBIN($trials, $value) * pow($probability, $value) * pow(1 - $probability, $trials - $value) ; + return MathTrig::COMBIN($trials, $value) * pow($probability, $value) * pow(1 - $probability, $trials - $value); } } } + return Functions::VALUE(); } - /** * CHIDIST * @@ -1031,7 +1024,7 @@ class Statistical */ public static function CHIDIST($value, $degrees) { - $value = Functions::flattenSingleValue($value); + $value = Functions::flattenSingleValue($value); $degrees = floor(Functions::flattenSingleValue($degrees)); if ((is_numeric($value)) && (is_numeric($degrees))) { @@ -1042,14 +1035,16 @@ class Statistical if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } + return Functions::NAN(); } - return 1 - (self::incompleteGamma($degrees/2, $value/2) / self::gamma($degrees/2)); + + return 1 - (self::incompleteGamma($degrees / 2, $value / 2) / self::gamma($degrees / 2)); } + return Functions::VALUE(); } - /** * CHIINV * @@ -1062,14 +1057,14 @@ class Statistical public static function CHIINV($probability, $degrees) { $probability = Functions::flattenSingleValue($probability); - $degrees = floor(Functions::flattenSingleValue($degrees)); + $degrees = floor(Functions::flattenSingleValue($degrees)); if ((is_numeric($probability)) && (is_numeric($degrees))) { $xLo = 100; $xHi = 0; $x = $xNew = 1; - $dx = 1; + $dx = 1; $i = 0; while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { @@ -1100,12 +1095,13 @@ class Statistical if ($i == MAX_ITERATIONS) { return Functions::NA(); } + return round($x, 12); } + return Functions::VALUE(); } - /** * CONFIDENCE * @@ -1115,13 +1111,12 @@ class Statistical * @param float $stdDev Standard Deviation * @param float $size * @return float - * */ public static function CONFIDENCE($alpha, $stdDev, $size) { - $alpha = Functions::flattenSingleValue($alpha); + $alpha = Functions::flattenSingleValue($alpha); $stdDev = Functions::flattenSingleValue($stdDev); - $size = floor(Functions::flattenSingleValue($size)); + $size = floor(Functions::flattenSingleValue($size)); if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) { if (($alpha <= 0) || ($alpha >= 1)) { @@ -1130,12 +1125,13 @@ class Statistical if (($stdDev <= 0) || ($size < 1)) { return Functions::NAN(); } + return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size); } + return Functions::VALUE(); } - /** * CORREL * @@ -1163,10 +1159,10 @@ class Statistical } $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getCorrelation(); } - /** * COUNT * @@ -1175,7 +1171,6 @@ class Statistical * Excel Function: * COUNT(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return int @@ -1200,7 +1195,6 @@ class Statistical return $returnValue; } - /** * COUNTA * @@ -1209,7 +1203,6 @@ class Statistical * Excel Function: * COUNTA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return int @@ -1230,7 +1223,6 @@ class Statistical return $returnValue; } - /** * COUNTBLANK * @@ -1239,7 +1231,6 @@ class Statistical * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return int @@ -1260,7 +1251,6 @@ class Statistical return $returnValue; } - /** * COUNTIF * @@ -1269,7 +1259,6 @@ class Statistical * Excel Function: * COUNTIF(value1[,value2[, ...]],condition) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @param string $condition The criteria that defines which cells will be counted. @@ -1286,7 +1275,7 @@ class Statistical if (!is_numeric($arg)) { $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); } - $testCondition = '='.$arg.$condition; + $testCondition = '=' . $arg . $condition; if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { // Is it a value within our criteria ++$returnValue; @@ -1296,7 +1285,6 @@ class Statistical return $returnValue; } - /** * COVAR * @@ -1321,10 +1309,10 @@ class Statistical } $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getCovariance(); } - /** * CRITBINOM * @@ -1342,13 +1330,12 @@ class Statistical * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess * This eliminates a potential endless loop error, but may have an adverse affect on the * accuracy of the function (although all my tests have so far returned correct results). - * */ public static function CRITBINOM($trials, $probability, $alpha) { - $trials = floor(Functions::flattenSingleValue($trials)); + $trials = floor(Functions::flattenSingleValue($trials)); $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); + $alpha = Functions::flattenSingleValue($alpha); if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) { if ($trials < 0) { @@ -1445,10 +1432,10 @@ class Statistical } } } + return Functions::VALUE(); } - /** * DEVSQ * @@ -1457,7 +1444,6 @@ class Statistical * Excel Function: * DEVSQ(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -1496,10 +1482,10 @@ class Statistical return $returnValue; } } + return self::NA(); } - /** * EXPONDIST * @@ -1509,14 +1495,14 @@ class Statistical * * @param float $value Value of the function * @param float $lambda The parameter value - * @param boolean $cumulative + * @param bool $cumulative * @return float */ public static function EXPONDIST($value, $lambda, $cumulative) { - $value = Functions::flattenSingleValue($value); - $lambda = Functions::flattenSingleValue($lambda); - $cumulative = Functions::flattenSingleValue($cumulative); + $value = Functions::flattenSingleValue($value); + $lambda = Functions::flattenSingleValue($lambda); + $cumulative = Functions::flattenSingleValue($cumulative); if ((is_numeric($value)) && (is_numeric($lambda))) { if (($value < 0) || ($lambda < 0)) { @@ -1524,16 +1510,16 @@ class Statistical } if ((is_numeric($cumulative)) || (is_bool($cumulative))) { if ($cumulative) { - return 1 - exp(0-$value*$lambda); + return 1 - exp(0 - $value * $lambda); } else { - return $lambda * exp(0-$value*$lambda); + return $lambda * exp(0 - $value * $lambda); } } } + return Functions::VALUE(); } - /** * FISHER * @@ -1546,18 +1532,19 @@ class Statistical */ public static function FISHER($value) { - $value = Functions::flattenSingleValue($value); + $value = Functions::flattenSingleValue($value); if (is_numeric($value)) { if (($value <= -1) || ($value >= 1)) { return Functions::NAN(); } - return 0.5 * log((1+$value)/(1-$value)); + + return 0.5 * log((1 + $value) / (1 - $value)); } + return Functions::VALUE(); } - /** * FISHERINV * @@ -1570,15 +1557,15 @@ class Statistical */ public static function FISHERINV($value) { - $value = Functions::flattenSingleValue($value); + $value = Functions::flattenSingleValue($value); if (is_numeric($value)) { return (exp(2 * $value) - 1) / (exp(2 * $value) + 1); } + return Functions::VALUE(); } - /** * FORECAST * @@ -1591,7 +1578,7 @@ class Statistical */ public static function FORECAST($xValue, $yValues, $xValues) { - $xValue = Functions::flattenSingleValue($xValue); + $xValue = Functions::flattenSingleValue($xValue); if (!is_numeric($xValue)) { return Functions::VALUE(); } elseif (!self::checkTrendArrays($yValues, $xValues)) { @@ -1607,10 +1594,10 @@ class Statistical } $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getValueOfYForX($xValue); } - /** * GAMMADIST * @@ -1619,15 +1606,14 @@ class Statistical * @param float $value Value at which you want to evaluate the distribution * @param float $a Parameter to the distribution * @param float $b Parameter to the distribution - * @param boolean $cumulative + * @param bool $cumulative * @return float - * */ public static function GAMMADIST($value, $a, $b, $cumulative) { $value = Functions::flattenSingleValue($value); - $a = Functions::flattenSingleValue($a); - $b = Functions::flattenSingleValue($b); + $a = Functions::flattenSingleValue($a); + $b = Functions::flattenSingleValue($b); if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) { if (($value < 0) || ($a <= 0) || ($b <= 0)) { @@ -1637,14 +1623,14 @@ class Statistical if ($cumulative) { return self::incompleteGamma($a, $value / $b) / self::gamma($a); } else { - return (1 / (pow($b, $a) * self::gamma($a))) * pow($value, $a-1) * exp(0-($value / $b)); + return (1 / (pow($b, $a) * self::gamma($a))) * pow($value, $a - 1) * exp(0 - ($value / $b)); } } } + return Functions::VALUE(); } - /** * GAMMAINV * @@ -1654,13 +1640,12 @@ class Statistical * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution * @return float - * */ public static function GAMMAINV($probability, $alpha, $beta) { $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); + $alpha = Functions::flattenSingleValue($alpha); + $beta = Functions::flattenSingleValue($beta); if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) { if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) { @@ -1672,7 +1657,7 @@ class Statistical $x = $xNew = 1; $error = $pdf = 0; - $dx = 1024; + $dx = 1024; $i = 0; while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { @@ -1701,12 +1686,13 @@ class Statistical if ($i == MAX_ITERATIONS) { return Functions::NA(); } + return $x; } + return Functions::VALUE(); } - /** * GAMMALN * @@ -1717,18 +1703,19 @@ class Statistical */ public static function GAMMALN($value) { - $value = Functions::flattenSingleValue($value); + $value = Functions::flattenSingleValue($value); if (is_numeric($value)) { if ($value <= 0) { return Functions::NAN(); } + return log(self::gamma($value)); } + return Functions::VALUE(); } - /** * GEOMEAN * @@ -1739,7 +1726,6 @@ class Statistical * Excel Function: * GEOMEAN(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -1750,15 +1736,15 @@ class Statistical $aMean = MathTrig::PRODUCT($aArgs); if (is_numeric($aMean) && ($aMean > 0)) { - $aCount = self::COUNT($aArgs) ; + $aCount = self::COUNT($aArgs); if (self::MIN($aArgs) > 0) { return pow($aMean, (1 / $aCount)); } } + return Functions::NAN(); } - /** * GROWTH * @@ -1767,10 +1753,10 @@ class Statistical * @param array of mixed Data Series Y * @param array of mixed Data Series X * @param array of mixed Values of X for which we want to find Y - * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @param bool A logical value specifying whether to force the intersect to equal 0. * @return array of float */ - public static function GROWTH($yValues, $xValues = array(), $newValues = array(), $const = true) + public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true) { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); @@ -1782,7 +1768,7 @@ class Statistical $newValues = $bestFitExponential->getXValues(); } - $returnArray = array(); + $returnArray = []; foreach ($newValues as $xValue) { $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue); } @@ -1790,7 +1776,6 @@ class Statistical return $returnArray; } - /** * HARMEAN * @@ -1800,7 +1785,6 @@ class Statistical * Excel Function: * HARMEAN(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -1839,7 +1823,6 @@ class Statistical } } - /** * HYPGEOMDIST * @@ -1851,14 +1834,13 @@ class Statistical * @param float $populationSuccesses Number of successes in the population * @param float $populationNumber Population size * @return float - * */ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) { - $sampleSuccesses = floor(Functions::flattenSingleValue($sampleSuccesses)); - $sampleNumber = floor(Functions::flattenSingleValue($sampleNumber)); + $sampleSuccesses = floor(Functions::flattenSingleValue($sampleSuccesses)); + $sampleNumber = floor(Functions::flattenSingleValue($sampleNumber)); $populationSuccesses = floor(Functions::flattenSingleValue($populationSuccesses)); - $populationNumber = floor(Functions::flattenSingleValue($populationNumber)); + $populationNumber = floor(Functions::flattenSingleValue($populationNumber)); if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) { if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { @@ -1870,14 +1852,15 @@ class Statistical if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { return Functions::NAN(); } + return MathTrig::COMBIN($populationSuccesses, $sampleSuccesses) * MathTrig::COMBIN($populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses) / MathTrig::COMBIN($populationNumber, $sampleNumber); } + return Functions::VALUE(); } - /** * INTERCEPT * @@ -1902,10 +1885,10 @@ class Statistical } $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getIntersect(); } - /** * KURT * @@ -1940,13 +1923,13 @@ class Statistical // Return if ($count > 3) { - return $summer * ($count * ($count+1) / (($count-1) * ($count-2) * ($count-3))) - (3 * pow($count-1, 2) / (($count-2) * ($count-3))); + return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * pow($count - 1, 2) / (($count - 2) * ($count - 3))); } } + return Functions::DIV0(); } - /** * LARGE * @@ -1956,12 +1939,10 @@ class Statistical * Excel Function: * LARGE(value1[,value2[, ...]],entry) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @param int $entry Position (ordered from the largest) in the array or range of data to return * @return float - * */ public static function LARGE() { @@ -1971,7 +1952,7 @@ class Statistical $entry = floor(array_pop($aArgs)); if ((is_numeric($entry)) && (!is_string($entry))) { - $mArgs = array(); + $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { @@ -1984,12 +1965,13 @@ class Statistical return Functions::NAN(); } rsort($mArgs); + return $mArgs[$entry]; } + return Functions::VALUE(); } - /** * LINEST * @@ -1998,8 +1980,8 @@ class Statistical * * @param array of mixed Data Series Y * @param array of mixed Data Series X - * @param boolean A logical value specifying whether to force the intersect to equal 0. - * @param boolean A logical value specifying whether to return additional regression statistics. + * @param bool A logical value specifying whether to force the intersect to equal 0. + * @param bool A logical value specifying whether to return additional regression statistics. * @return array */ public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) @@ -2016,7 +1998,6 @@ class Statistical $yValueCount = count($yValues); $xValueCount = count($xValues); - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { return Functions::NA(); } elseif ($yValueCount == 1) { @@ -2025,31 +2006,30 @@ class Statistical $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues, $const); if ($stats) { - return array( - array( + return [ + [ $bestFitLinear->getSlope(), $bestFitLinear->getSlopeSE(), $bestFitLinear->getGoodnessOfFit(), $bestFitLinear->getF(), $bestFitLinear->getSSRegression(), - ), - array( + ], + [ $bestFitLinear->getIntersect(), $bestFitLinear->getIntersectSE(), $bestFitLinear->getStdevOfResiduals(), $bestFitLinear->getDFResiduals(), - $bestFitLinear->getSSResiduals() - ) - ); + $bestFitLinear->getSSResiduals(), + ], + ]; } else { - return array( + return [ $bestFitLinear->getSlope(), - $bestFitLinear->getIntersect() - ); + $bestFitLinear->getIntersect(), + ]; } } - /** * LOGEST * @@ -2058,8 +2038,8 @@ class Statistical * * @param array of mixed Data Series Y * @param array of mixed Data Series X - * @param boolean A logical value specifying whether to force the intersect to equal 0. - * @param boolean A logical value specifying whether to return additional regression statistics. + * @param bool A logical value specifying whether to force the intersect to equal 0. + * @param bool A logical value specifying whether to return additional regression statistics. * @return array */ public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) @@ -2082,7 +2062,6 @@ class Statistical } } - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { return Functions::NA(); } elseif ($yValueCount == 1) { @@ -2091,31 +2070,30 @@ class Statistical $bestFitExponential = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if ($stats) { - return array( - array( + return [ + [ $bestFitExponential->getSlope(), $bestFitExponential->getSlopeSE(), $bestFitExponential->getGoodnessOfFit(), $bestFitExponential->getF(), $bestFitExponential->getSSRegression(), - ), - array( + ], + [ $bestFitExponential->getIntersect(), $bestFitExponential->getIntersectSE(), $bestFitExponential->getStdevOfResiduals(), $bestFitExponential->getDFResiduals(), - $bestFitExponential->getSSResiduals() - ) - ); + $bestFitExponential->getSSResiduals(), + ], + ]; } else { - return array( + return [ $bestFitExponential->getSlope(), - $bestFitExponential->getIntersect() - ); + $bestFitExponential->getIntersect(), + ]; } } - /** * LOGINV * @@ -2133,19 +2111,20 @@ class Statistical public static function LOGINV($probability, $mean, $stdDev) { $probability = Functions::flattenSingleValue($probability); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); + $mean = Functions::flattenSingleValue($mean); + $stdDev = Functions::flattenSingleValue($stdDev); if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) { return Functions::NAN(); } + return exp($mean + $stdDev * self::NORMSINV($probability)); } + return Functions::VALUE(); } - /** * LOGNORMDIST * @@ -2159,20 +2138,21 @@ class Statistical */ public static function LOGNORMDIST($value, $mean, $stdDev) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); + $value = Functions::flattenSingleValue($value); + $mean = Functions::flattenSingleValue($mean); $stdDev = Functions::flattenSingleValue($stdDev); if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { if (($value <= 0) || ($stdDev <= 0)) { return Functions::NAN(); } + return self::NORMSDIST((log($value) - $mean) / $stdDev); } + return Functions::VALUE(); } - /** * MAX * @@ -2182,7 +2162,6 @@ class Statistical * Excel Function: * MAX(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -2205,10 +2184,10 @@ class Statistical if (is_null($returnValue)) { return 0; } + return $returnValue; } - /** * MAXA * @@ -2217,7 +2196,6 @@ class Statistical * Excel Function: * MAXA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -2245,10 +2223,10 @@ class Statistical if (is_null($returnValue)) { return 0; } + return $returnValue; } - /** * MAXIF * @@ -2257,13 +2235,12 @@ class Statistical * Excel Function: * MAXIF(value1[,value2[, ...]],condition) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @param string $condition The criteria that defines which cells will be checked. * @return float */ - public static function MAXIF($aArgs, $condition, $sumArgs = array()) + public static function MAXIF($aArgs, $condition, $sumArgs = []) { $returnValue = null; @@ -2278,7 +2255,7 @@ class Statistical if (!is_numeric($arg)) { $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); } - $testCondition = '='.$arg.$condition; + $testCondition = '=' . $arg . $condition; if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { if ((is_null($returnValue)) || ($arg > $returnValue)) { $returnValue = $arg; @@ -2297,7 +2274,6 @@ class Statistical * Excel Function: * MEDIAN(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -2306,7 +2282,7 @@ class Statistical { $returnValue = Functions::NAN(); - $mArgs = array(); + $mArgs = []; // Loop through arguments $aArgs = Functions::flattenArray(func_get_args()); foreach ($aArgs as $arg) { @@ -2331,7 +2307,6 @@ class Statistical return $returnValue; } - /** * MIN * @@ -2341,7 +2316,6 @@ class Statistical * Excel Function: * MIN(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -2364,10 +2338,10 @@ class Statistical if (is_null($returnValue)) { return 0; } + return $returnValue; } - /** * MINA * @@ -2376,7 +2350,6 @@ class Statistical * Excel Function: * MINA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -2404,10 +2377,10 @@ class Statistical if (is_null($returnValue)) { return 0; } + return $returnValue; } - /** * MINIF * @@ -2416,13 +2389,12 @@ class Statistical * Excel Function: * MINIF(value1[,value2[, ...]],condition) * - * @access public * @category Mathematical and Trigonometric Functions * @param mixed $arg,... Data values * @param string $condition The criteria that defines which cells will be checked. * @return float */ - public static function MINIF($aArgs, $condition, $sumArgs = array()) + public static function MINIF($aArgs, $condition, $sumArgs = []) { $returnValue = null; @@ -2437,7 +2409,7 @@ class Statistical if (!is_numeric($arg)) { $arg = \PhpSpreadsheet\Calculation::wrapResult(strtoupper($arg)); } - $testCondition = '='.$arg.$condition; + $testCondition = '=' . $arg . $condition; if (\PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($testCondition)) { if ((is_null($returnValue)) || ($arg < $returnValue)) { $returnValue = $arg; @@ -2448,14 +2420,13 @@ class Statistical return $returnValue; } - // // Special variant of array_count_values that isn't limited to strings and integers, // but can work with floating point numbers as values // private static function modeCalc($data) { - $frequencyArray = array(); + $frequencyArray = []; foreach ($data as $datum) { $found = false; foreach ($frequencyArray as $key => $value) { @@ -2466,10 +2437,10 @@ class Statistical } } if (!$found) { - $frequencyArray[] = array( - 'value' => $datum, - 'frequency' => 1 - ); + $frequencyArray[] = [ + 'value' => $datum, + 'frequency' => 1, + ]; } } @@ -2482,10 +2453,10 @@ class Statistical if ($frequencyArray[0]['frequency'] == 1) { return Functions::NA(); } + return $frequencyArray[0]['value']; } - /** * MODE * @@ -2494,7 +2465,6 @@ class Statistical * Excel Function: * MODE(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -2506,7 +2476,7 @@ class Statistical // Loop through arguments $aArgs = Functions::flattenArray(func_get_args()); - $mArgs = array(); + $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { @@ -2521,7 +2491,6 @@ class Statistical return $returnValue; } - /** * NEGBINOMDIST * @@ -2535,12 +2504,11 @@ class Statistical * @param float $successes Threshold number of Successes * @param float $probability Probability of success on each trial * @return float - * */ public static function NEGBINOMDIST($failures, $successes, $probability) { - $failures = floor(Functions::flattenSingleValue($failures)); - $successes = floor(Functions::flattenSingleValue($successes)); + $failures = floor(Functions::flattenSingleValue($failures)); + $successes = floor(Functions::flattenSingleValue($successes)); $probability = Functions::flattenSingleValue($probability); if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) { @@ -2554,12 +2522,13 @@ class Statistical return Functions::NAN(); } } + return (MathTrig::COMBIN($failures + $successes - 1, $successes - 1)) * (pow($probability, $successes)) * (pow(1 - $probability, $failures)); } + return Functions::VALUE(); } - /** * NORMDIST * @@ -2570,14 +2539,13 @@ class Statistical * @param float $value * @param float $mean Mean Value * @param float $stdDev Standard Deviation - * @param boolean $cumulative + * @param bool $cumulative * @return float - * */ public static function NORMDIST($value, $mean, $stdDev, $cumulative) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); + $value = Functions::flattenSingleValue($value); + $mean = Functions::flattenSingleValue($mean); $stdDev = Functions::flattenSingleValue($stdDev); if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { @@ -2592,10 +2560,10 @@ class Statistical } } } + return Functions::VALUE(); } - /** * NORMINV * @@ -2605,13 +2573,12 @@ class Statistical * @param float $mean Mean Value * @param float $stdDev Standard Deviation * @return float - * */ public static function NORMINV($probability, $mean, $stdDev) { $probability = Functions::flattenSingleValue($probability); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); + $mean = Functions::flattenSingleValue($mean); + $stdDev = Functions::flattenSingleValue($stdDev); if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { if (($probability < 0) || ($probability > 1)) { @@ -2620,12 +2587,13 @@ class Statistical if ($stdDev < 0) { return Functions::NAN(); } + return (self::inverseNcdf($probability) * $stdDev) + $mean; } + return Functions::VALUE(); } - /** * NORMSDIST * @@ -2643,7 +2611,6 @@ class Statistical return self::NORMDIST($value, 0, 1, true); } - /** * NORMSINV * @@ -2657,7 +2624,6 @@ class Statistical return self::NORMINV($value, 0, 1); } - /** * PERCENTILE * @@ -2666,7 +2632,6 @@ class Statistical * Excel Function: * PERCENTILE(value1[,value2[, ...]],entry) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @param float $entry Percentile value in the range 0..1, inclusive. @@ -2683,7 +2648,7 @@ class Statistical if (($entry < 0) || ($entry > 1)) { return Functions::NAN(); } - $mArgs = array(); + $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { @@ -2694,21 +2659,22 @@ class Statistical if ($mValueCount > 0) { sort($mArgs); $count = self::COUNT($mArgs); - $index = $entry * ($count-1); + $index = $entry * ($count - 1); $iBase = floor($index); if ($index == $iBase) { return $mArgs[$index]; } else { $iNext = $iBase + 1; $iProportion = $index - $iBase; - return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion) ; + + return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); } } } + return Functions::VALUE(); } - /** * PERCENTRANK * @@ -2721,8 +2687,8 @@ class Statistical */ public static function PERCENTRANK($valueSet, $value, $significance = 3) { - $valueSet = Functions::flattenArray($valueSet); - $value = Functions::flattenSingleValue($value); + $valueSet = Functions::flattenArray($valueSet); + $value = Functions::flattenSingleValue($value); $significance = (is_null($significance)) ? 3 : (integer) Functions::flattenSingleValue($significance); foreach ($valueSet as $key => $valueEntry) { @@ -2755,7 +2721,6 @@ class Statistical return round($pos / $valueAdjustor, $significance); } - /** * PERMUT * @@ -2771,7 +2736,7 @@ class Statistical */ public static function PERMUT($numObjs, $numInSet) { - $numObjs = Functions::flattenSingleValue($numObjs); + $numObjs = Functions::flattenSingleValue($numObjs); $numInSet = Functions::flattenSingleValue($numInSet); if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { @@ -2779,12 +2744,13 @@ class Statistical if ($numObjs < $numInSet) { return Functions::NAN(); } + return round(MathTrig::FACT($numObjs) / MathTrig::FACT($numObjs - $numInSet)); } + return Functions::VALUE(); } - /** * POISSON * @@ -2794,14 +2760,13 @@ class Statistical * * @param float $value * @param float $mean Mean Value - * @param boolean $cumulative + * @param bool $cumulative * @return float - * */ public static function POISSON($value, $mean, $cumulative) { $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); + $mean = Functions::flattenSingleValue($mean); if ((is_numeric($value)) && (is_numeric($mean))) { if (($value < 0) || ($mean <= 0)) { @@ -2813,16 +2778,17 @@ class Statistical for ($i = 0; $i <= floor($value); ++$i) { $summer += pow($mean, $i) / MathTrig::FACT($i); } - return exp(0-$mean) * $summer; + + return exp(0 - $mean) * $summer; } else { - return (exp(0-$mean) * pow($mean, $value)) / MathTrig::FACT($value); + return (exp(0 - $mean) * pow($mean, $value)) / MathTrig::FACT($value); } } } + return Functions::VALUE(); } - /** * QUARTILE * @@ -2831,7 +2797,6 @@ class Statistical * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @param int $entry Quartile value in the range 1..3, inclusive. @@ -2849,12 +2814,13 @@ class Statistical if (($entry < 0) || ($entry > 1)) { return Functions::NAN(); } + return self::PERCENTILE($aArgs, $entry); } + return Functions::VALUE(); } - /** * RANK * @@ -2890,7 +2856,6 @@ class Statistical return ++$pos; } - /** * RSQ * @@ -2915,10 +2880,10 @@ class Statistical } $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getGoodnessOfFit(); } - /** * SKEW * @@ -2951,12 +2916,12 @@ class Statistical } if ($count > 2) { - return $summer * ($count / (($count-1) * ($count-2))); + return $summer * ($count / (($count - 1) * ($count - 2))); } + return Functions::DIV0(); } - /** * SLOPE * @@ -2981,10 +2946,10 @@ class Statistical } $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getSlope(); } - /** * SMALL * @@ -2994,7 +2959,6 @@ class Statistical * Excel Function: * SMALL(value1[,value2[, ...]],entry) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @param int $entry Position (ordered from the smallest) in the array or range of data to return @@ -3008,7 +2972,7 @@ class Statistical $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { - $mArgs = array(); + $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { @@ -3021,12 +2985,13 @@ class Statistical return Functions::NAN(); } sort($mArgs); + return $mArgs[$entry]; } + return Functions::VALUE(); } - /** * STANDARDIZE * @@ -3039,20 +3004,21 @@ class Statistical */ public static function STANDARDIZE($value, $mean, $stdDev) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); + $value = Functions::flattenSingleValue($value); + $mean = Functions::flattenSingleValue($mean); $stdDev = Functions::flattenSingleValue($stdDev); if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { if ($stdDev <= 0) { return Functions::NAN(); } - return ($value - $mean) / $stdDev ; + + return ($value - $mean) / $stdDev; } + return Functions::VALUE(); } - /** * STDEV * @@ -3062,7 +3028,6 @@ class Statistical * Excel Function: * STDEV(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3098,10 +3063,10 @@ class Statistical return sqrt($returnValue / $aCount); } } + return Functions::DIV0(); } - /** * STDEVA * @@ -3110,7 +3075,6 @@ class Statistical * Excel Function: * STDEVA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3149,10 +3113,10 @@ class Statistical return sqrt($returnValue / $aCount); } } + return Functions::DIV0(); } - /** * STDEVP * @@ -3161,7 +3125,6 @@ class Statistical * Excel Function: * STDEVP(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3195,10 +3158,10 @@ class Statistical return sqrt($returnValue / $aCount); } } + return Functions::DIV0(); } - /** * STDEVPA * @@ -3207,7 +3170,6 @@ class Statistical * Excel Function: * STDEVPA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3246,10 +3208,10 @@ class Statistical return sqrt($returnValue / $aCount); } } + return Functions::DIV0(); } - /** * STEYX * @@ -3274,10 +3236,10 @@ class Statistical } $bestFitLinear = \PhpSpreadsheet\Shared\trend\trend::calculate(\PhpSpreadsheet\Shared\trend\trend::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getStdevOfResiduals(); } - /** * TDIST * @@ -3290,9 +3252,9 @@ class Statistical */ public static function TDIST($value, $degrees, $tails) { - $value = Functions::flattenSingleValue($value); - $degrees = floor(Functions::flattenSingleValue($degrees)); - $tails = floor(Functions::flattenSingleValue($tails)); + $value = Functions::flattenSingleValue($value); + $degrees = floor(Functions::flattenSingleValue($degrees)); + $tails = floor(Functions::flattenSingleValue($tails)); if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) { if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { @@ -3338,10 +3300,10 @@ class Statistical return 1 - abs((1 - $tValue) - $tValue); } } + return Functions::VALUE(); } - /** * TINV * @@ -3354,14 +3316,14 @@ class Statistical public static function TINV($probability, $degrees) { $probability = Functions::flattenSingleValue($probability); - $degrees = floor(Functions::flattenSingleValue($degrees)); + $degrees = floor(Functions::flattenSingleValue($degrees)); if ((is_numeric($probability)) && (is_numeric($degrees))) { $xLo = 100; $xHi = 0; $x = $xNew = 1; - $dx = 1; + $dx = 1; $i = 0; while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { @@ -3392,12 +3354,13 @@ class Statistical if ($i == MAX_ITERATIONS) { return Functions::NA(); } + return round($x, 12); } + return Functions::VALUE(); } - /** * TREND * @@ -3406,10 +3369,10 @@ class Statistical * @param array of mixed Data Series Y * @param array of mixed Data Series X * @param array of mixed Values of X for which we want to find Y - * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @param bool A logical value specifying whether to force the intersect to equal 0. * @return array of float */ - public static function TREND($yValues, $xValues = array(), $newValues = array(), $const = true) + public static function TREND($yValues, $xValues = [], $newValues = [], $const = true) { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); @@ -3421,7 +3384,7 @@ class Statistical $newValues = $bestFitLinear->getXValues(); } - $returnArray = array(); + $returnArray = []; foreach ($newValues as $xValue) { $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue); } @@ -3429,7 +3392,6 @@ class Statistical return $returnArray; } - /** * TRIMMEAN * @@ -3440,7 +3402,6 @@ class Statistical * Excel Function: * TRIMEAN(value1[,value2[, ...]], $discard) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @param float $discard Percentage to discard @@ -3457,7 +3418,7 @@ class Statistical if (($percent < 0) || ($percent > 1)) { return Functions::NAN(); } - $mArgs = array(); + $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { @@ -3466,16 +3427,17 @@ class Statistical } $discard = floor(self::COUNT($mArgs) * $percent / 2); sort($mArgs); - for ($i=0; $i < $discard; ++$i) { + for ($i = 0; $i < $discard; ++$i) { array_pop($mArgs); array_shift($mArgs); } + return self::AVERAGE($mArgs); } + return Functions::VALUE(); } - /** * VARFunc * @@ -3484,7 +3446,6 @@ class Statistical * Excel Function: * VAR(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3515,10 +3476,10 @@ class Statistical $summerB *= $summerB; $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); } + return $returnValue; } - /** * VARA * @@ -3527,7 +3488,6 @@ class Statistical * Excel Function: * VARA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3567,10 +3527,10 @@ class Statistical $summerB *= $summerB; $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); } + return $returnValue; } - /** * VARP * @@ -3579,7 +3539,6 @@ class Statistical * Excel Function: * VARP(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3611,10 +3570,10 @@ class Statistical $summerB *= $summerB; $returnValue = ($summerA - $summerB) / ($aCount * $aCount); } + return $returnValue; } - /** * VARPA * @@ -3623,7 +3582,6 @@ class Statistical * Excel Function: * VARPA(value1[,value2[, ...]]) * - * @access public * @category Statistical Functions * @param mixed $arg,... Data values * @return float @@ -3663,10 +3621,10 @@ class Statistical $summerB *= $summerB; $returnValue = ($summerA - $summerB) / ($aCount * $aCount); } + return $returnValue; } - /** * WEIBULL * @@ -3676,15 +3634,14 @@ class Statistical * @param float $value * @param float $alpha Alpha Parameter * @param float $beta Beta Parameter - * @param boolean $cumulative + * @param bool $cumulative * @return float - * */ public static function WEIBULL($value, $alpha, $beta, $cumulative) { $value = Functions::flattenSingleValue($value); $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); + $beta = Functions::flattenSingleValue($beta); if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) { if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { @@ -3698,10 +3655,10 @@ class Statistical } } } + return Functions::VALUE(); } - /** * ZTEST * @@ -3711,15 +3668,14 @@ class Statistical * @param float $dataSet * @param float $m0 Alpha Parameter * @param float $sigma Beta Parameter - * @param boolean $cumulative + * @param bool $cumulative * @return float - * */ public static function ZTEST($dataSet, $m0, $sigma = null) { $dataSet = Functions::flattenArrayIndexed($dataSet); - $m0 = Functions::flattenSingleValue($m0); - $sigma = Functions::flattenSingleValue($sigma); + $m0 = Functions::flattenSingleValue($m0); + $sigma = Functions::flattenSingleValue($sigma); if (is_null($sigma)) { $sigma = self::STDEV($dataSet); diff --git a/src/PhpSpreadsheet/Calculation/TextData.php b/src/PhpSpreadsheet/Calculation/TextData.php index 1a77ac28..9aa7f13d 100644 --- a/src/PhpSpreadsheet/Calculation/TextData.php +++ b/src/PhpSpreadsheet/Calculation/TextData.php @@ -30,22 +30,23 @@ class TextData 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}); } 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) { - 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) { - 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) { - 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) { - 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) { // error return Functions::VALUE(); } + return 0; } @@ -64,13 +65,12 @@ class TextData } 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 { return chr(intval($character)); } } - /** * TRIMNONPRINTABLE * @@ -79,7 +79,7 @@ class TextData */ public static function TRIMNONPRINTABLE($stringValue = '') { - $stringValue = Functions::flattenSingleValue($stringValue); + $stringValue = Functions::flattenSingleValue($stringValue); if (is_bool($stringValue)) { return ($stringValue) ? \PhpSpreadsheet\Calculation::getTRUE() : \PhpSpreadsheet\Calculation::getFALSE(); @@ -92,10 +92,10 @@ class TextData if (is_string($stringValue) || is_numeric($stringValue)) { return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F")); } + return null; } - /** * TRIMSPACES * @@ -112,10 +112,10 @@ class TextData if (is_string($stringValue) || is_numeric($stringValue)) { return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' '); } + return null; } - /** * ASCIICODE * @@ -127,7 +127,7 @@ class TextData if (($characters === null) || ($characters === '')) { return Functions::VALUE(); } - $characters = Functions::flattenSingleValue($characters); + $characters = Functions::flattenSingleValue($characters); if (is_bool($characters)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { $characters = (int) $characters; @@ -141,16 +141,17 @@ class TextData if (mb_strlen($characters, 'UTF-8') > 1) { $character = mb_substr($characters, 0, 1, 'UTF-8'); } + return self::unicodeToOrd($character); } else { if (strlen($characters) > 0) { $character = substr($characters, 0, 1); } + return ord($character); } } - /** * CONCATENATE * @@ -176,7 +177,6 @@ class TextData return $returnValue; } - /** * DOLLAR * @@ -191,8 +191,8 @@ class TextData */ public static function DOLLAR($value = 0, $decimals = 2) { - $value = Functions::flattenSingleValue($value); - $decimals = is_null($decimals) ? 0 : Functions::flattenSingleValue($decimals); + $value = Functions::flattenSingleValue($value); + $decimals = is_null($decimals) ? 0 : Functions::flattenSingleValue($decimals); // Validate parameters if (!is_numeric($value) || !is_numeric($decimals)) { @@ -206,7 +206,7 @@ class TextData } else { $round = pow(10, abs($decimals)); if ($value < 0) { - $round = 0-$round; + $round = 0 - $round; } $value = MathTrig::MROUND($value, $round); } @@ -214,7 +214,6 @@ class TextData return \PhpSpreadsheet\Style\NumberFormat::toFormattedString($value, $mask); } - /** * SEARCHSENSITIVE * @@ -225,9 +224,9 @@ class TextData */ public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1) { - $needle = Functions::flattenSingleValue($needle); + $needle = Functions::flattenSingleValue($needle); $haystack = Functions::flattenSingleValue($haystack); - $offset = Functions::flattenSingleValue($offset); + $offset = Functions::flattenSingleValue($offset); if (!is_bool($needle)) { if (is_bool($haystack)) { @@ -248,10 +247,10 @@ class TextData } } } + return Functions::VALUE(); } - /** * SEARCHINSENSITIVE * @@ -262,9 +261,9 @@ class TextData */ public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1) { - $needle = Functions::flattenSingleValue($needle); + $needle = Functions::flattenSingleValue($needle); $haystack = Functions::flattenSingleValue($haystack); - $offset = Functions::flattenSingleValue($offset); + $offset = Functions::flattenSingleValue($offset); if (!is_bool($needle)) { if (is_bool($haystack)) { @@ -285,22 +284,22 @@ class TextData } } } + return Functions::VALUE(); } - /** * FIXEDFORMAT * * @param mixed $value Value to check - * @param integer $decimals - * @param boolean $no_commas - * @return boolean + * @param int $decimals + * @param bool $no_commas + * @return bool */ public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false) { - $value = Functions::flattenSingleValue($value); - $decimals = Functions::flattenSingleValue($decimals); + $value = Functions::flattenSingleValue($value); + $decimals = Functions::flattenSingleValue($decimals); $no_commas = Functions::flattenSingleValue($no_commas); // Validate parameters @@ -320,7 +319,6 @@ class TextData return (string) $valueResult; } - /** * LEFT * @@ -348,7 +346,6 @@ class TextData } } - /** * MID * @@ -381,7 +378,6 @@ class TextData } } - /** * RIGHT * @@ -409,7 +405,6 @@ class TextData } } - /** * STRINGLENGTH * @@ -431,7 +426,6 @@ class TextData } } - /** * LOWERCASE * @@ -451,7 +445,6 @@ class TextData return \PhpSpreadsheet\Shared\StringHelper::strToLower($mixedCaseString); } - /** * UPPERCASE * @@ -471,7 +464,6 @@ class TextData return \PhpSpreadsheet\Shared\StringHelper::strToUpper($mixedCaseString); } - /** * PROPERCASE * @@ -491,7 +483,6 @@ class TextData return \PhpSpreadsheet\Shared\StringHelper::strToTitle($mixedCaseString); } - /** * REPLACE * @@ -504,31 +495,30 @@ class TextData public static function REPLACE($oldText, $start, $chars, $newText) { $oldText = Functions::flattenSingleValue($oldText); - $start = Functions::flattenSingleValue($start); - $chars = Functions::flattenSingleValue($chars); + $start = Functions::flattenSingleValue($start); + $chars = Functions::flattenSingleValue($chars); $newText = Functions::flattenSingleValue($newText); - $left = self::LEFT($oldText, $start-1); - $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText)-($start+$chars)+1); + $left = self::LEFT($oldText, $start - 1); + $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText) - ($start + $chars) + 1); - return $left.$newText.$right; + return $left . $newText . $right; } - /** * SUBSTITUTE * * @param string $text Value * @param string $fromText From Value * @param string $toText To Value - * @param integer $instance Instance Number + * @param int $instance Instance Number * @return string */ public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) { - $text = Functions::flattenSingleValue($text); + $text = Functions::flattenSingleValue($text); $fromText = Functions::flattenSingleValue($fromText); - $toText = Functions::flattenSingleValue($toText); + $toText = Functions::flattenSingleValue($toText); $instance = floor(Functions::flattenSingleValue($instance)); if ($instance == 0) { @@ -541,9 +531,9 @@ class TextData $pos = -1; while ($instance > 0) { if (function_exists('mb_strpos')) { - $pos = mb_strpos($text, $fromText, $pos+1, 'UTF-8'); + $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); } else { - $pos = strpos($text, $fromText, $pos+1); + $pos = strpos($text, $fromText, $pos + 1); } if ($pos === false) { break; @@ -562,12 +552,11 @@ class TextData return $text; } - /** * RETURNSTRING * * @param mixed $testValue Value to check - * @return boolean + * @return bool */ public static function RETURNSTRING($testValue = '') { @@ -576,20 +565,20 @@ class TextData if (is_string($testValue)) { return $testValue; } + return null; } - /** * TEXTFORMAT * * @param mixed $value Value to check * @param string $format Format mask to use - * @return boolean + * @return bool */ public static function TEXTFORMAT($value, $format) { - $value = Functions::flattenSingleValue($value); + $value = Functions::flattenSingleValue($value); $format = Functions::flattenSingleValue($format); if ((is_string($value)) && (!is_numeric($value)) && \PhpSpreadsheet\Shared\Date::isDateTimeFormatCode($format)) { @@ -603,7 +592,7 @@ class TextData * VALUE * * @param mixed $value Value to check - * @return boolean + * @return bool */ public static function VALUE($value = '') { @@ -626,18 +615,21 @@ class TextData $timeValue = DateTime::TIMEVALUE($value); if ($timeValue !== Functions::VALUE()) { Functions::setReturnDateType($dateSetting); + return $timeValue; } } $dateValue = DateTime::DATEVALUE($value); if ($dateValue !== Functions::VALUE()) { Functions::setReturnDateType($dateSetting); + return $dateValue; } Functions::setReturnDateType($dateSetting); return Functions::VALUE(); } + return (float) $value; } } diff --git a/src/PhpSpreadsheet/Calculation/Token/Stack.php b/src/PhpSpreadsheet/Calculation/Token/Stack.php index 5b61c048..4385b64f 100644 --- a/src/PhpSpreadsheet/Calculation/Token/Stack.php +++ b/src/PhpSpreadsheet/Calculation/Token/Stack.php @@ -31,19 +31,19 @@ class Stack * * @var mixed[] */ - private $stack = array(); + private $stack = []; /** * Count of entries in the parser stack * - * @var integer + * @var int */ private $count = 0; /** * Return the number of entries on the stack * - * @return integer + * @return int */ public function count() { @@ -59,11 +59,11 @@ class Stack */ public function push($type, $value, $reference = null) { - $this->stack[$this->count++] = array( - 'type' => $type, - 'value' => $value, - 'reference' => $reference - ); + $this->stack[$this->count++] = [ + 'type' => $type, + 'value' => $value, + 'reference' => $reference, + ]; if ($type == 'Function') { $localeFunction = \PhpSpreadsheet\Calculation::localeFunc($value); if ($localeFunction != $value) { @@ -82,13 +82,14 @@ class Stack if ($this->count > 0) { return $this->stack[--$this->count]; } + return null; } /** * 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 */ public function last($n = 1) @@ -96,6 +97,7 @@ class Stack if ($this->count - $n < 0) { return null; } + return $this->stack[$this->count - $n]; } @@ -104,7 +106,7 @@ class Stack */ public function clear() { - $this->stack = array(); + $this->stack = []; $this->count = 0; } } diff --git a/src/PhpSpreadsheet/Cell.php b/src/PhpSpreadsheet/Cell.php index a3a2956f..3a22d18f 100644 --- a/src/PhpSpreadsheet/Cell.php +++ b/src/PhpSpreadsheet/Cell.php @@ -82,15 +82,11 @@ class Cell /** * Attributes of the formula - * */ private $formulaAttributes; - /** * Send notification to the cache controller - * - * @return void **/ public function notifyCacheController() { @@ -109,7 +105,6 @@ class Cell $this->parent = $parent; } - /** * Create a new Cell * @@ -133,7 +128,7 @@ class Cell } $this->dataType = $pDataType; } 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 * * @param mixed $pValue Value - * @return Cell * @throws Exception + * @return Cell */ public function setValue($pValue = null) { 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; } @@ -213,8 +209,8 @@ class Cell * * @param mixed $pValue Value * @param string $pDataType Explicit data type - * @return Cell * @throws Exception + * @return Cell */ 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 * - * @param boolean $resetLog Whether the calculation engine logger should be reset or not - * @return mixed + * @param bool $resetLog Whether the calculation engine logger should be reset or not * @throws Exception + * @return mixed */ 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) { 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( $this->getWorksheet()->getParent() )->calculateCellValue($this, $resetLog); @@ -282,24 +278,24 @@ class Cell } } catch (Exception $ex) { 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. } //echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL; $result = '#N/A'; throw new Calculation\Exception( - $this->getWorksheet()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage() + $this->getWorksheet()->getTitle() . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage() ); } 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. } //echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL; return $result; } elseif ($this->value instanceof RichText) { -// echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->value.'
'; + // echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->value.'
'; return $this->value->getPlainText(); } // echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->value.'
'; @@ -365,7 +361,7 @@ class Cell /** * Identify if the cell contains a formula * - * @return boolean + * @return bool */ public function isFormula() { @@ -375,8 +371,8 @@ class Cell /** * Does this cell contain Data validation rules? * - * @return boolean * @throws Exception + * @return bool */ public function hasDataValidation() { @@ -390,8 +386,8 @@ class Cell /** * Get Data validation rules * - * @return Cell\DataValidation * @throws Exception + * @return Cell\DataValidation */ public function getDataValidation() { @@ -406,8 +402,8 @@ class Cell * Set Data validation rules * * @param Cell\DataValidation $pDataValidation - * @return Cell * @throws Exception + * @return Cell */ public function setDataValidation(Cell\DataValidation $pDataValidation = null) { @@ -423,8 +419,8 @@ class Cell /** * Does this cell contain a Hyperlink? * - * @return boolean * @throws Exception + * @return bool */ public function hasHyperlink() { @@ -438,8 +434,8 @@ class Cell /** * Get Hyperlink * - * @return Cell\Hyperlink * @throws Exception + * @return Cell\Hyperlink */ public function getHyperlink() { @@ -454,8 +450,8 @@ class Cell * Set Hyperlink * * @param Cell\Hyperlink $pHyperlink - * @return Cell * @throws Exception + * @return Cell */ public function setHyperlink(Cell\Hyperlink $pHyperlink = null) { @@ -491,7 +487,7 @@ class Cell /** * Is this cell in a merge range * - * @return boolean + * @return bool */ 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) * - * @return boolean + * @return bool */ public function isMergeRangeValueCell() { if ($mergeRange = $this->getMergeRange()) { - $mergeRange = Cell::splitRange($mergeRange); + $mergeRange = self::splitRange($mergeRange); list($startCell) = $mergeRange[0]; if ($this->getCoordinate() === $startCell) { return true; } } + return false; } @@ -527,6 +524,7 @@ class Cell return $mergeRange; } } + return false; } @@ -557,7 +555,7 @@ class Cell * Is cell in a specific range? * * @param string $pRange Cell range (e.g. A1:A1) - * @return boolean + * @return bool */ public function isInRange($pRange = 'A1:A1') { @@ -565,32 +563,31 @@ class Cell // Translate properties $myColumn = self::columnIndexFromString($this->getColumn()); - $myRow = $this->getRow(); + $myRow = $this->getRow(); // Verify if cell is in range - return (($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && - ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow) - ); + return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && + ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow); } /** * Coordinate from string * * @param string $pCoordinateString - * @return array Array containing column and row (indexes 0 and 1) * @throws Exception + * @return array Array containing column and row (indexes 0 and 1) */ public static function coordinateFromString($pCoordinateString = 'A1') { 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)) { throw new Exception('Cell coordinate string can not be a range of cells'); } elseif ($pCoordinateString == '') { 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' * 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 + * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' */ public static function absoluteReference($pCoordinateString = 'A1') { @@ -620,6 +617,7 @@ class Cell } elseif (ctype_alpha($pCoordinateString)) { return $worksheet . '$' . strtoupper($pCoordinateString); } + return $worksheet . self::absoluteCoordinate($pCoordinateString); } @@ -630,8 +628,8 @@ class Cell * Make string coordinate absolute * * @param string $pCoordinateString e.g. 'A1' - * @return string Absolute coordinate e.g. '$A$1' * @throws Exception + * @return string Absolute coordinate e.g. '$A$1' */ public static function absoluteCoordinate($pCoordinateString = 'A1') { @@ -650,6 +648,7 @@ class Cell list($column, $row) = self::coordinateFromString($pCoordinateString); $column = ltrim($column, '$'); $row = ltrim($row, '$'); + return $worksheet . '$' . $column . '$' . $row; } @@ -676,6 +675,7 @@ class Cell for ($i = 0; $i < $counter; ++$i) { $exploded[$i] = explode(':', $exploded[$i]); } + return $exploded; } @@ -683,8 +683,8 @@ class Cell * Build range from 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 + * @return string String representation of $pRange */ public static function buildRange($pRange) { @@ -694,7 +694,7 @@ class Cell } // Build range - $imploded = array(); + $imploded = []; $counter = count($pRange); for ($i = 0; $i < $counter; ++$i) { $pRange[$i] = implode(':', $pRange[$i]); @@ -730,13 +730,13 @@ class Cell // Calculate range outer borders $rangeStart = self::coordinateFromString($rangeA); - $rangeEnd = self::coordinateFromString($rangeB); + $rangeEnd = self::coordinateFromString($rangeB); // Translate column into index - $rangeStart[0] = self::columnIndexFromString($rangeStart[0]); - $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); + $rangeStart[0] = self::columnIndexFromString($rangeStart[0]); + $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); - return array($rangeStart, $rangeEnd); + return [$rangeStart, $rangeEnd]; } /** @@ -750,7 +750,7 @@ class Cell // Calculate range outer borders 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); } - 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 // caching using a static within the method is faster than a class static, // though it's additional memory overhead - static $_indexCache = array(); + static $_indexCache = []; if (isset($_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() // 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 - 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, '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, - '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 // for improved performance if (isset($pString{0})) { if (!isset($pString{1})) { $_indexCache[$pString] = $_columnLookup[$pString]; + return $_indexCache[$pString]; } elseif (!isset($pString{2})) { $_indexCache[$pString] = $_columnLookup[$pString{0}] * 26 + $_columnLookup[$pString{1}]; + return $_indexCache[$pString]; } elseif (!isset($pString{3})) { $_indexCache[$pString] = $_columnLookup[$pString{0}] * 676 + $_columnLookup[$pString{1}] * 26 + $_columnLookup[$pString{2}]; + 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 // caching using a static within the method is faster than a class static, // though it's additional memory overhead - static $_indexCache = array(); + static $_indexCache = []; if (!isset($_indexCache[$pColumnIndex])) { // Determine column string @@ -849,6 +852,7 @@ class Cell chr(65 + $pColumnIndex % 26); } } + return $_indexCache[$pColumnIndex]; } @@ -861,7 +865,7 @@ class Cell public static function extractAllCellReferencesInRange($pRange = 'A1') { // Returnvalue - $returnValue = array(); + $returnValue = []; // Explode spaces $cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange))); @@ -882,7 +886,7 @@ class Cell } // Range... - list($rangeStart, $rangeEnd) = $range; + list($rangeStart, $rangeEnd) = $range; sscanf($rangeStart, '%[A-Z]%d', $startCol, $startRow); sscanf($rangeEnd, '%[A-Z]%d', $endCol, $endRow); ++$endCol; @@ -894,7 +898,7 @@ class Cell // Loop cells while ($currentCol != $endCol) { while ($currentRow <= $endRow) { - $returnValue[] = $currentCol.$currentRow; + $returnValue[] = $currentCol . $currentRow; ++$currentRow; } ++$currentCol; @@ -904,7 +908,7 @@ class Cell } // Sort the result by column and row - $sortKeys = array(); + $sortKeys = []; foreach (array_unique($returnValue) as $coord) { sscanf($coord, '%[A-Z]%d', $column, $row); $sortKeys[sprintf('%3s%09d', $column, $row)] = $coord; @@ -958,7 +962,7 @@ class Cell public static function setValueBinder(Cell\IValueBinder $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; @@ -1008,6 +1012,7 @@ class Cell public function setFormulaAttributes($pAttributes) { $this->formulaAttributes = $pAttributes; + return $this; } diff --git a/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php b/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php index 940671e1..6bdb2e22 100644 --- a/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php +++ b/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php @@ -31,7 +31,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder * * @param \PhpSpreadsheet\Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell - * @return boolean + * @return bool */ public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null) { @@ -48,15 +48,18 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Test for booleans using locale-setting if ($value == \PhpSpreadsheet\Calculation::getTRUE()) { $cell->setValueExplicit(true, DataType::TYPE_BOOL); + return true; } elseif ($value == \PhpSpreadsheet\Calculation::getFALSE()) { $cell->setValueExplicit(false, DataType::TYPE_BOOL); + return true; } // 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); + return true; } @@ -71,6 +74,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode('??/??'); + return true; } elseif (preg_match('/^([+-]?)([0-9]*) +([0-9]*)\s?\/\s*([0-9]*)$/', $value, $matches)) { // Convert value to number @@ -82,6 +86,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode('# ??/??'); + return true; } @@ -93,6 +98,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00); + return true; } @@ -100,23 +106,25 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder $currencyCode = \PhpSpreadsheet\Shared\StringHelper::getCurrencyCode(); $decimalSeparator = \PhpSpreadsheet\Shared\StringHelper::getDecimalSeparator(); $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 - $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); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode( str_replace('$', $currencyCode, \PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE) ); + return true; } elseif (preg_match('/^\$ *(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/', $value)) { // Convert value to number - $value = (float) trim(str_replace(array('$',','), '', $value)); + $value = (float) trim(str_replace(['$', ','], '', $value)); $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE); + return true; } @@ -129,6 +137,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME3); + return true; } @@ -142,6 +151,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4); + return true; } @@ -157,6 +167,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder } $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($formatCode); + return true; } @@ -167,6 +178,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getAlignment()->setWrapText(true); + return true; } } diff --git a/src/PhpSpreadsheet/Cell/DataType.php b/src/PhpSpreadsheet/Cell/DataType.php index 7641805d..ab9dfb99 100644 --- a/src/PhpSpreadsheet/Cell/DataType.php +++ b/src/PhpSpreadsheet/Cell/DataType.php @@ -27,29 +27,29 @@ namespace PhpSpreadsheet\Cell; class DataType { /* Data types */ - const TYPE_STRING2 = 'str'; - const TYPE_STRING = 's'; - const TYPE_FORMULA = 'f'; - const TYPE_NUMERIC = 'n'; - const TYPE_BOOL = 'b'; - const TYPE_NULL = 'null'; - const TYPE_INLINE = 'inlineStr'; - const TYPE_ERROR = 'e'; + const TYPE_STRING2 = 'str'; + const TYPE_STRING = 's'; + const TYPE_FORMULA = 'f'; + const TYPE_NUMERIC = 'n'; + const TYPE_BOOL = 'b'; + const TYPE_NULL = 'null'; + const TYPE_INLINE = 'inlineStr'; + const TYPE_ERROR = 'e'; /** * List of error codes * * @var array */ - private static $errorCodes = array( - '#NULL!' => 0, + private static $errorCodes = [ + '#NULL!' => 0, '#DIV/0!' => 1, '#VALUE!' => 2, - '#REF!' => 3, - '#NAME?' => 4, - '#NUM!' => 5, - '#N/A' => 6 - ); + '#REF!' => 3, + '#NAME?' => 4, + '#NUM!' => 5, + '#N/A' => 6, + ]; /** * Get list of error codes @@ -90,7 +90,7 @@ class DataType $pValue = \PhpSpreadsheet\Shared\StringHelper::substring($pValue, 0, 32767); // 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; } diff --git a/src/PhpSpreadsheet/Cell/DataValidation.php b/src/PhpSpreadsheet/Cell/DataValidation.php index 6bc87697..417ad976 100644 --- a/src/PhpSpreadsheet/Cell/DataValidation.php +++ b/src/PhpSpreadsheet/Cell/DataValidation.php @@ -27,29 +27,29 @@ namespace PhpSpreadsheet\Cell; class DataValidation { /* Data validation types */ - const TYPE_NONE = 'none'; - const TYPE_CUSTOM = 'custom'; - const TYPE_DATE = 'date'; - const TYPE_DECIMAL = 'decimal'; - const TYPE_LIST = 'list'; - const TYPE_TEXTLENGTH = 'textLength'; - const TYPE_TIME = 'time'; - const TYPE_WHOLE = 'whole'; + const TYPE_NONE = 'none'; + const TYPE_CUSTOM = 'custom'; + const TYPE_DATE = 'date'; + const TYPE_DECIMAL = 'decimal'; + const TYPE_LIST = 'list'; + const TYPE_TEXTLENGTH = 'textLength'; + const TYPE_TIME = 'time'; + const TYPE_WHOLE = 'whole'; /* Data validation error styles */ - const STYLE_STOP = 'stop'; - const STYLE_WARNING = 'warning'; - const STYLE_INFORMATION = 'information'; + const STYLE_STOP = 'stop'; + const STYLE_WARNING = 'warning'; + const STYLE_INFORMATION = 'information'; /* Data validation operators */ - const OPERATOR_BETWEEN = 'between'; - const OPERATOR_EQUAL = 'equal'; - const OPERATOR_GREATERTHAN = 'greaterThan'; - const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; - const OPERATOR_LESSTHAN = 'lessThan'; - const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; - const OPERATOR_NOTBETWEEN = 'notBetween'; - const OPERATOR_NOTEQUAL = 'notEqual'; + const OPERATOR_BETWEEN = 'between'; + const OPERATOR_EQUAL = 'equal'; + const OPERATOR_GREATERTHAN = 'greaterThan'; + const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; + const OPERATOR_LESSTHAN = 'lessThan'; + const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; + const OPERATOR_NOTBETWEEN = 'notBetween'; + const OPERATOR_NOTEQUAL = 'notEqual'; /** * Formula 1 @@ -70,14 +70,14 @@ class DataValidation * * @var string */ - private $type = DataValidation::TYPE_NONE; + private $type = self::TYPE_NONE; /** * Error style * * @var string */ - private $errorStyle = DataValidation::STYLE_STOP; + private $errorStyle = self::STYLE_STOP; /** * Operator @@ -89,28 +89,28 @@ class DataValidation /** * Allow Blank * - * @var boolean + * @var bool */ private $allowBlank = false; /** * Show DropDown * - * @var boolean + * @var bool */ private $showDropDown = false; /** * Show InputMessage * - * @var boolean + * @var bool */ private $showInputMessage = false; /** * Show ErrorMessage * - * @var boolean + * @var bool */ private $showErrorMessage = false; @@ -168,6 +168,7 @@ class DataValidation public function setFormula1($value = '') { $this->formula1 = $value; + return $this; } @@ -190,6 +191,7 @@ class DataValidation public function setFormula2($value = '') { $this->formula2 = $value; + return $this; } @@ -212,6 +214,7 @@ class DataValidation public function setType($value = self::TYPE_NONE) { $this->type = $value; + return $this; } @@ -234,6 +237,7 @@ class DataValidation public function setErrorStyle($value = self::STYLE_STOP) { $this->errorStyle = $value; + return $this; } @@ -256,13 +260,14 @@ class DataValidation public function setOperator($value = '') { $this->operator = $value; + return $this; } /** * Get Allow Blank * - * @return boolean + * @return bool */ public function getAllowBlank() { @@ -272,19 +277,20 @@ class DataValidation /** * Set Allow Blank * - * @param boolean $value + * @param bool $value * @return DataValidation */ public function setAllowBlank($value = false) { $this->allowBlank = $value; + return $this; } /** * Get Show DropDown * - * @return boolean + * @return bool */ public function getShowDropDown() { @@ -294,19 +300,20 @@ class DataValidation /** * Set Show DropDown * - * @param boolean $value + * @param bool $value * @return DataValidation */ public function setShowDropDown($value = false) { $this->showDropDown = $value; + return $this; } /** * Get Show InputMessage * - * @return boolean + * @return bool */ public function getShowInputMessage() { @@ -316,19 +323,20 @@ class DataValidation /** * Set Show InputMessage * - * @param boolean $value + * @param bool $value * @return DataValidation */ public function setShowInputMessage($value = false) { $this->showInputMessage = $value; + return $this; } /** * Get Show ErrorMessage * - * @return boolean + * @return bool */ public function getShowErrorMessage() { @@ -338,12 +346,13 @@ class DataValidation /** * Set Show ErrorMessage * - * @param boolean $value + * @param bool $value * @return DataValidation */ public function setShowErrorMessage($value = false) { $this->showErrorMessage = $value; + return $this; } @@ -366,6 +375,7 @@ class DataValidation public function setErrorTitle($value = '') { $this->errorTitle = $value; + return $this; } @@ -388,6 +398,7 @@ class DataValidation public function setError($value = '') { $this->error = $value; + return $this; } @@ -410,6 +421,7 @@ class DataValidation public function setPromptTitle($value = '') { $this->promptTitle = $value; + return $this; } @@ -432,6 +444,7 @@ class DataValidation public function setPrompt($value = '') { $this->prompt = $value; + return $this; } diff --git a/src/PhpSpreadsheet/Cell/DefaultValueBinder.php b/src/PhpSpreadsheet/Cell/DefaultValueBinder.php index 6db191ef..74d5c4d4 100644 --- a/src/PhpSpreadsheet/Cell/DefaultValueBinder.php +++ b/src/PhpSpreadsheet/Cell/DefaultValueBinder.php @@ -31,7 +31,7 @@ class DefaultValueBinder implements IValueBinder * * @param \PhpSpreadsheet\Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell - * @return boolean + * @return bool */ public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null) { @@ -82,6 +82,7 @@ class DefaultValueBinder implements IValueBinder } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) { return DataType::TYPE_STRING; } + return DataType::TYPE_NUMERIC; } elseif (is_string($pValue) && array_key_exists($pValue, DataType::getErrorCodes())) { return DataType::TYPE_ERROR; diff --git a/src/PhpSpreadsheet/Cell/Hyperlink.php b/src/PhpSpreadsheet/Cell/Hyperlink.php index b9f7d155..e6cd58ae 100644 --- a/src/PhpSpreadsheet/Cell/Hyperlink.php +++ b/src/PhpSpreadsheet/Cell/Hyperlink.php @@ -49,7 +49,7 @@ class Hyperlink public function __construct($pUrl = '', $pTooltip = '') { // Initialise member variables - $this->url = $pUrl; + $this->url = $pUrl; $this->tooltip = $pTooltip; } @@ -72,6 +72,7 @@ class Hyperlink public function setUrl($value = '') { $this->url = $value; + return $this; } @@ -94,13 +95,14 @@ class Hyperlink public function setTooltip($value = '') { $this->tooltip = $value; + return $this; } /** * Is this hyperlink internal? (to another worksheet) * - * @return boolean + * @return bool */ public function isInternal() { diff --git a/src/PhpSpreadsheet/Cell/IValueBinder.php b/src/PhpSpreadsheet/Cell/IValueBinder.php index 42fc166c..9e04b9b8 100644 --- a/src/PhpSpreadsheet/Cell/IValueBinder.php +++ b/src/PhpSpreadsheet/Cell/IValueBinder.php @@ -31,7 +31,7 @@ interface IValueBinder * * @param \PhpSpreadsheet\Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell - * @return boolean + * @return bool */ public function bindValue(\PhpSpreadsheet\Cell $cell, $value = null); } diff --git a/src/PhpSpreadsheet/Chart.php b/src/PhpSpreadsheet/Chart.php index e2988982..f3594b66 100644 --- a/src/PhpSpreadsheet/Chart.php +++ b/src/PhpSpreadsheet/Chart.php @@ -78,7 +78,7 @@ class Chart /** * Plot Visible Only * - * @var boolean + * @var bool */ private $plotVisibleOnly = true; @@ -124,23 +124,20 @@ class Chart */ private $topLeftCellRef = 'A1'; - /** * Top-Left X-Offset * - * @var integer + * @var int */ private $topLeftXOffset = 0; - /** * Top-Left Y-Offset * - * @var integer + * @var int */ private $topLeftYOffset = 0; - /** * Bottom-Right Cell Position * @@ -148,23 +145,20 @@ class Chart */ private $bottomRightCellRef = 'A1'; - /** * Bottom-Right X-Offset * - * @var integer + * @var int */ private $bottomRightXOffset = 10; - /** * Bottom-Right Y-Offset * - * @var integer + * @var int */ private $bottomRightYOffset = 10; - /** * Create a new Chart */ @@ -323,7 +317,7 @@ class Chart /** * Get Plot Visible Only * - * @return boolean + * @return bool */ public function getPlotVisibleOnly() { @@ -333,7 +327,7 @@ class Chart /** * Set Plot Visible Only * - * @param boolean $plotVisibleOnly + * @param bool $plotVisibleOnly * @return Chart */ public function setPlotVisibleOnly($plotVisibleOnly = true) @@ -364,7 +358,6 @@ class Chart $this->displayBlanksAs = $displayBlanksAs; } - /** * Get yAxis * @@ -421,13 +414,12 @@ class Chart return new Chart\GridLines(); } - /** * Set the Top Left position for the chart * * @param string $cell - * @param integer $xOffset - * @param integer $yOffset + * @param int $xOffset + * @param int $yOffset * @return Chart */ public function setTopLeftPosition($cell, $xOffset = null, $yOffset = null) @@ -450,11 +442,11 @@ class Chart */ public function getTopLeftPosition() { - return array( - 'cell' => $this->topLeftCellRef, + return [ + 'cell' => $this->topLeftCellRef, '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 * - * @param integer $xOffset - * @param integer $yOffset + * @param int $xOffset + * @param int $yOffset * @return Chart */ 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 * - * @return integer[] + * @return int[] */ public function getTopLeftOffset() { - return array( + return [ 'X' => $this->topLeftXOffset, - 'Y' => $this->topLeftYOffset - ); + 'Y' => $this->topLeftYOffset, + ]; } public function setTopLeftXOffset($xOffset) @@ -540,8 +532,8 @@ class Chart * Set the Bottom Right position of the chart * * @param string $cell - * @param integer $xOffset - * @param integer $yOffset + * @param int $xOffset + * @param int $yOffset * @return Chart */ public function setBottomRightPosition($cell, $xOffset = null, $yOffset = null) @@ -564,11 +556,11 @@ class Chart */ public function getBottomRightPosition() { - return array( - 'cell' => $this->bottomRightCellRef, + return [ + 'cell' => $this->bottomRightCellRef, 'xOffset' => $this->bottomRightXOffset, - 'yOffset' => $this->bottomRightYOffset - ); + 'yOffset' => $this->bottomRightYOffset, + ]; } public function setBottomRightCell($cell) @@ -591,8 +583,8 @@ class Chart /** * Set the offset position within the Bottom Right cell for the chart * - * @param integer $xOffset - * @param integer $yOffset + * @param int $xOffset + * @param int $yOffset * @return Chart */ 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 * - * @return integer[] + * @return int[] */ public function getBottomRightOffset() { - return array( + return [ 'X' => $this->bottomRightXOffset, - 'Y' => $this->bottomRightYOffset - ); + 'Y' => $this->bottomRightYOffset, + ]; } public function setBottomRightXOffset($xOffset) @@ -644,7 +636,6 @@ class Chart return $this->bottomRightYOffset; } - public function refresh() { if ($this->worksheet !== null) { @@ -668,12 +659,13 @@ class Chart set_include_path(get_include_path() . PATH_SEPARATOR . $libraryPath); } - $rendererName = '\\PhpSpreadsheet\\Chart\\Renderer\\'.$libraryName; + $rendererName = '\\PhpSpreadsheet\\Chart\\Renderer\\' . $libraryName; $renderer = new $rendererName($this); if ($outputDestination == 'php://output') { $outputDestination = null; } + return $renderer->render($outputDestination); } } diff --git a/src/PhpSpreadsheet/Chart/Axis.php b/src/PhpSpreadsheet/Chart/Axis.php index 07bccc89..53fc3919 100644 --- a/src/PhpSpreadsheet/Chart/Axis.php +++ b/src/PhpSpreadsheet/Chart/Axis.php @@ -8,7 +8,6 @@ namespace PhpSpreadsheet\Chart; * Date: 6/17/14 * Time: 12:11 PM */ - class Axis extends Properties { /** @@ -16,17 +15,17 @@ class Axis extends Properties * * @var array of mixed */ - private $axisNumber = array( + private $axisNumber = [ 'format' => self::FORMAT_CODE_GENERAL, - 'source_linked' => 1 - ); + 'source_linked' => 1, + ]; /** * Axis Options * * @var array of mixed */ - private $axisOptions = array( + private $axisOptions = [ 'minimum' => null, 'maximum' => null, 'major_unit' => null, @@ -36,101 +35,101 @@ class Axis extends Properties 'major_tick_mark' => self::TICK_MARK_NONE, 'axis_labels' => self::AXIS_LABELS_NEXT_TO, 'horizontal_crosses' => self::HORIZONTAL_CROSSES_AUTOZERO, - 'horizontal_crosses_value' => null - ); + 'horizontal_crosses_value' => null, + ]; /** * Fill Properties * * @var array of mixed */ - private $fillProperties = array( + private $fillProperties = [ 'type' => self::EXCEL_COLOR_TYPE_ARGB, 'value' => null, - 'alpha' => 0 - ); + 'alpha' => 0, + ]; /** * Line Properties * * @var array of mixed */ - private $lineProperties = array( + private $lineProperties = [ 'type' => self::EXCEL_COLOR_TYPE_ARGB, 'value' => null, - 'alpha' => 0 - ); + 'alpha' => 0, + ]; /** * Line Style Properties * * @var array of mixed */ - private $lineStyleProperties = array( + private $lineStyleProperties = [ 'width' => '9525', 'compound' => self::LINE_STYLE_COMPOUND_SIMPLE, 'dash' => self::LINE_STYLE_DASH_SOLID, 'cap' => self::LINE_STYLE_CAP_FLAT, 'join' => self::LINE_STYLE_JOIN_BEVEL, - 'arrow' => array( - 'head' => array( + 'arrow' => [ + 'head' => [ 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, - 'size' => self::LINE_STYLE_ARROW_SIZE_5 - ), - 'end' => array( + 'size' => self::LINE_STYLE_ARROW_SIZE_5, + ], + 'end' => [ 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, - 'size' => self::LINE_STYLE_ARROW_SIZE_8 - ), - ) - ); + 'size' => self::LINE_STYLE_ARROW_SIZE_8, + ], + ], + ]; /** * Shadow Properties * * @var array of mixed */ - private $shadowProperties = array( + private $shadowProperties = [ 'presets' => self::SHADOW_PRESETS_NOSHADOW, 'effect' => null, - 'color' => array( + 'color' => [ 'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'value' => 'black', 'alpha' => 40, - ), - 'size' => array( + ], + 'size' => [ 'sx' => null, 'sy' => null, - 'kx' => null - ), + 'kx' => null, + ], 'blur' => null, 'direction' => null, 'distance' => null, 'algn' => null, - 'rotWithShape' => null - ); + 'rotWithShape' => null, + ]; /** * Glow Properties * * @var array of mixed */ - private $glowProperties = array( + private $glowProperties = [ 'size' => null, - 'color' => array( + 'color' => [ 'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'value' => 'black', - 'alpha' => 40 - ) - ); + 'alpha' => 40, + ], + ]; /** * Soft Edge Properties * * @var array of mixed */ - private $softEdges = array( - 'size' => null - ); + private $softEdges = [ + 'size' => null, + ]; /** * Get Series Data Type @@ -176,7 +175,6 @@ class Axis extends Properties * @param string $maximum * @param string $major_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) { @@ -209,7 +207,6 @@ class Axis extends Properties * Set Axis Orientation Property * * @param string $orientation - * */ public function setAxisOrientation($orientation) { @@ -222,7 +219,6 @@ class Axis extends Properties * @param string $color * @param int $alpha * @param string $type - * */ public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) { @@ -235,7 +231,6 @@ class Axis extends Properties * @param string $color * @param int $alpha * @param string $type - * */ 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 $end_arrow_type * @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) { @@ -339,7 +333,6 @@ class Axis extends Properties * @param float $sh_blur * @param int $sh_angle * @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) { @@ -383,9 +376,9 @@ class Axis extends Properties foreach ($properties_map as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { - $reference = & $this->shadowProperties[$property_key]; + $reference = &$this->shadowProperties[$property_key]; } else { - $reference = & $reference[$property_key]; + $reference = &$reference[$property_key]; } $this->setShadowProperiesMapValues($property_val, $reference); } else { diff --git a/src/PhpSpreadsheet/Chart/DataSeries.php b/src/PhpSpreadsheet/Chart/DataSeries.php index 940b3295..109a0c7b 100644 --- a/src/PhpSpreadsheet/Chart/DataSeries.php +++ b/src/PhpSpreadsheet/Chart/DataSeries.php @@ -26,40 +26,39 @@ namespace PhpSpreadsheet\Chart; */ class DataSeries { - const TYPE_BARCHART = 'barChart'; - const TYPE_BARCHART_3D = 'bar3DChart'; - const TYPE_LINECHART = 'lineChart'; - const TYPE_LINECHART_3D = 'line3DChart'; - const TYPE_AREACHART = 'areaChart'; - const TYPE_AREACHART_3D = 'area3DChart'; - const TYPE_PIECHART = 'pieChart'; - const TYPE_PIECHART_3D = 'pie3DChart'; - const TYPE_DOUGHTNUTCHART = 'doughnutChart'; - const TYPE_DONUTCHART = self::TYPE_DOUGHTNUTCHART; // Synonym - const TYPE_SCATTERCHART = 'scatterChart'; - const TYPE_SURFACECHART = 'surfaceChart'; + const TYPE_BARCHART = 'barChart'; + const TYPE_BARCHART_3D = 'bar3DChart'; + const TYPE_LINECHART = 'lineChart'; + const TYPE_LINECHART_3D = 'line3DChart'; + const TYPE_AREACHART = 'areaChart'; + const TYPE_AREACHART_3D = 'area3DChart'; + const TYPE_PIECHART = 'pieChart'; + const TYPE_PIECHART_3D = 'pie3DChart'; + const TYPE_DOUGHTNUTCHART = 'doughnutChart'; + const TYPE_DONUTCHART = self::TYPE_DOUGHTNUTCHART; // Synonym + const TYPE_SCATTERCHART = 'scatterChart'; + const TYPE_SURFACECHART = 'surfaceChart'; const TYPE_SURFACECHART_3D = 'surface3DChart'; - const TYPE_RADARCHART = 'radarChart'; - const TYPE_BUBBLECHART = 'bubbleChart'; - const TYPE_STOCKCHART = 'stockChart'; - const TYPE_CANDLECHART = self::TYPE_STOCKCHART; // Synonym + const TYPE_RADARCHART = 'radarChart'; + const TYPE_BUBBLECHART = 'bubbleChart'; + const TYPE_STOCKCHART = 'stockChart'; + const TYPE_CANDLECHART = self::TYPE_STOCKCHART; // Synonym - const GROUPING_CLUSTERED = 'clustered'; - const GROUPING_STACKED = 'stacked'; + const GROUPING_CLUSTERED = 'clustered'; + const GROUPING_STACKED = 'stacked'; 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_COL = 'col'; - const DIRECTION_COLUMN = self::DIRECTION_COL; - const DIRECTION_VERTICAL = self::DIRECTION_COL; + const DIRECTION_COL = 'col'; + const DIRECTION_COLUMN = self::DIRECTION_COL; + const DIRECTION_VERTICAL = self::DIRECTION_COL; - const STYLE_LINEMARKER = 'lineMarker'; + const STYLE_LINEMARKER = 'lineMarker'; const STYLE_SMOOTHMARKER = 'smoothMarker'; - const STYLE_MARKER = 'marker'; - const STYLE_FILLED = 'filled'; - + const STYLE_MARKER = 'marker'; + const STYLE_FILLED = 'filled'; /** * Series Plot Type @@ -71,14 +70,14 @@ class DataSeries /** * Plot Grouping Type * - * @var boolean + * @var bool */ private $plotGrouping; /** * Plot Direction * - * @var boolean + * @var bool */ private $plotDirection; @@ -94,21 +93,21 @@ class DataSeries * * @var array of integer */ - private $plotOrder = array(); + private $plotOrder = []; /** * Plot Label * * @var array of DataSeriesValues */ - private $plotLabel = array(); + private $plotLabel = []; /** * Plot Category * * @var array of DataSeriesValues */ - private $plotCategory = array(); + private $plotCategory = []; /** * Smooth Line @@ -122,12 +121,12 @@ class DataSeries * * @var array of DataSeriesValues */ - private $plotValues = array(); + private $plotValues = []; /** * 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->plotGrouping = $plotGrouping; @@ -171,6 +170,7 @@ class DataSeries public function setPlotType($plotType = '') { $this->plotType = $plotType; + return $this; } @@ -193,6 +193,7 @@ class DataSeries public function setPlotGrouping($groupingType = null) { $this->plotGrouping = $groupingType; + return $this; } @@ -215,6 +216,7 @@ class DataSeries public function setPlotDirection($plotDirection = null) { $this->plotDirection = $plotDirection; + return $this; } @@ -251,6 +253,7 @@ class DataSeries } elseif (isset($keys[$index])) { return $this->plotLabel[$keys[$index]]; } + return false; } @@ -277,6 +280,7 @@ class DataSeries } elseif (isset($keys[$index])) { return $this->plotCategory[$keys[$index]]; } + return false; } @@ -299,6 +303,7 @@ class DataSeries public function setPlotStyle($plotStyle = null) { $this->plotStyle = $plotStyle; + return $this; } @@ -325,13 +330,14 @@ class DataSeries } elseif (isset($keys[$index])) { return $this->plotValues[$keys[$index]]; } + return false; } /** * Get Number of Plot Series * - * @return integer + * @return int */ public function getPlotSeriesCount() { @@ -341,7 +347,7 @@ class DataSeries /** * Get Smooth Line * - * @return boolean + * @return bool */ public function getSmoothLine() { @@ -351,12 +357,13 @@ class DataSeries /** * Set Smooth Line * - * @param boolean $smoothLine + * @param bool $smoothLine * @return DataSeries */ public function setSmoothLine($smoothLine = true) { $this->smoothLine = $smoothLine; + return $this; } diff --git a/src/PhpSpreadsheet/Chart/DataSeriesValues.php b/src/PhpSpreadsheet/Chart/DataSeriesValues.php index 3b1f505c..be4140a8 100644 --- a/src/PhpSpreadsheet/Chart/DataSeriesValues.php +++ b/src/PhpSpreadsheet/Chart/DataSeriesValues.php @@ -28,14 +28,13 @@ namespace PhpSpreadsheet\Chart; */ class DataSeriesValues { + const DATASERIES_TYPE_STRING = 'String'; + const DATASERIES_TYPE_NUMBER = 'Number'; - const DATASERIES_TYPE_STRING = 'String'; - const DATASERIES_TYPE_NUMBER = 'Number'; - - private static $dataTypeValues = array( + private static $dataTypeValues = [ self::DATASERIES_TYPE_STRING, self::DATASERIES_TYPE_NUMBER, - ); + ]; /** * Series Data Type @@ -68,7 +67,7 @@ class DataSeriesValues /** * Point Count (The number of datapoints in the dataseries) * - * @var integer + * @var int */ private $pointCount = 0; @@ -77,12 +76,12 @@ class DataSeriesValues * * @var array of mixed */ - private $dataValues = array(); + private $dataValues = []; /** * 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->dataSource = $dataSource; @@ -111,8 +110,8 @@ class DataSeriesValues * Normally used for axis point values * \PhpSpreadsheet\Chart\DataSeriesValues::DATASERIES_TYPE_NUMBER * Normally used for chart data values - * @return DataSeriesValues * @throws Exception + * @return DataSeriesValues */ public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER) { @@ -200,7 +199,7 @@ class DataSeriesValues /** * Get Series Point Count * - * @return integer + * @return int */ public function getPointCount() { @@ -210,20 +209,21 @@ class DataSeriesValues /** * Identify if the Data Series is a multi-level or a simple series * - * @return boolean + * @return bool */ public function isMultiLevelSeries() { if (count($this->dataValues) > 0) { return is_array($this->dataValues[0]); } + return null; } /** * Return the level count of a multi-level Data Series * - * @return boolean + * @return bool */ public function multiLevelCount() { @@ -231,6 +231,7 @@ class DataSeriesValues foreach ($this->dataValues as $dataValueSet) { $levelCount = max($levelCount, count($dataValueSet)); } + return $levelCount; } @@ -257,6 +258,7 @@ class DataSeriesValues } elseif ($count == 1) { return $this->dataValues[0]; } + return $this->dataValues; } @@ -264,12 +266,12 @@ class DataSeriesValues * Set Series Data Values * * @param array $dataValues - * @param boolean $refreshDataSource + * @param bool $refreshDataSource * TRUE - refresh the value of dataSource based on the values of $dataValues * FALSE - don't change the value of dataSource * @return DataSeriesValues */ - public function setDataValues($dataValues = array(), $refreshDataSource = true) + public function setDataValues($dataValues = [], $refreshDataSource = true) { $this->dataValues = \PhpSpreadsheet\Calculation\Functions::flattenArray($dataValues); $this->pointCount = count($dataValues); @@ -292,7 +294,7 @@ class DataSeriesValues $calcEngine = \PhpSpreadsheet\Calculation::getInstance($worksheet->getParent()); $newDataValues = \PhpSpreadsheet\Calculation::unwrapResult( $calcEngine->_calculateFormulaValue( - '='.$this->dataSource, + '=' . $this->dataSource, null, $worksheet->getCell('A1') ) @@ -317,7 +319,7 @@ class DataSeriesValues } else { $newArray = array_values(array_shift($newDataValues)); foreach ($newArray as $i => $newDataSet) { - $newArray[$i] = array($newDataSet); + $newArray[$i] = [$newDataSet]; } foreach ($newDataValues as $newDataSet) { diff --git a/src/PhpSpreadsheet/Chart/GridLines.php b/src/PhpSpreadsheet/Chart/GridLines.php index 76f65cb5..57bdc219 100644 --- a/src/PhpSpreadsheet/Chart/GridLines.php +++ b/src/PhpSpreadsheet/Chart/GridLines.php @@ -8,86 +8,81 @@ namespace PhpSpreadsheet\Chart; * Date: 7/2/14 * Time: 2:36 PM */ - class GridLines extends Properties { - - /** - * Properties of Class: - * Object State (State for Minor Tick Mark) @var bool - * Line Properties @var array of mixed - * Shadow Properties @var array of mixed - * Glow Properties @var array of mixed - * Soft Properties @var array of mixed - * - */ - + /** + * Properties of Class: + * Object State (State for Minor Tick Mark) @var bool + * Line Properties @var array of mixed + * Shadow Properties @var array of mixed + * Glow Properties @var array of mixed + * Soft Properties @var array of mixed + */ private $objectState = false; - private $lineProperties = array( - 'color' => array( + private $lineProperties = [ + 'color' => [ 'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'value' => null, - 'alpha' => 0 - ), - 'style' => array( + 'alpha' => 0, + ], + 'style' => [ 'width' => '9525', 'compound' => self::LINE_STYLE_COMPOUND_SIMPLE, 'dash' => self::LINE_STYLE_DASH_SOLID, 'cap' => self::LINE_STYLE_CAP_FLAT, 'join' => self::LINE_STYLE_JOIN_BEVEL, - 'arrow' => array( - 'head' => array( + 'arrow' => [ + 'head' => [ 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, - 'size' => self::LINE_STYLE_ARROW_SIZE_5 - ), - 'end' => array( + 'size' => self::LINE_STYLE_ARROW_SIZE_5, + ], + 'end' => [ '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, 'effect' => null, - 'color' => array( + 'color' => [ 'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'value' => 'black', 'alpha' => 85, - ), - 'size' => array( + ], + 'size' => [ 'sx' => null, 'sy' => null, - 'kx' => null - ), + 'kx' => null, + ], 'blur' => null, 'direction' => null, 'distance' => null, 'algn' => null, - 'rotWithShape' => null - ); + 'rotWithShape' => null, + ]; - private $glowProperties = array( + private $glowProperties = [ 'size' => null, - 'color' => array( + 'color' => [ 'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'value' => 'black', - 'alpha' => 40 - ) - ); + 'alpha' => 40, + ], + ]; - private $softEdges = array( - 'size' => null - ); + private $softEdges = [ + 'size' => null, + ]; /** * Get Object State * * @return bool */ - public function getObjectState() { return $this->objectState; @@ -98,7 +93,6 @@ class GridLines extends Properties * * @return GridLines */ - private function activateObject() { $this->objectState = true; @@ -113,7 +107,6 @@ class GridLines extends Properties * @param int $alpha * @param string $type */ - public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD) { $this->activateObject() @@ -137,7 +130,6 @@ class GridLines extends Properties * @param string $end_arrow_type * @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) { $this->activateObject(); @@ -177,7 +169,6 @@ class GridLines extends Properties * * @return string */ - public function getLineColorProperty($parameter) { return $this->lineProperties['color'][$parameter]; @@ -190,7 +181,6 @@ class GridLines extends Properties * * @return string */ - public function getLineStyleProperty($elements) { return $this->getArrayElementsValue($this->lineProperties['style'], $elements); @@ -203,9 +193,7 @@ class GridLines extends Properties * @param string $color_value * @param int $color_alpha * @param string $color_type - * */ - public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) { $this @@ -221,7 +209,6 @@ class GridLines extends Properties * * @return string */ - public function getGlowColor($property) { return $this->glowProperties['color'][$property]; @@ -232,7 +219,6 @@ class GridLines extends Properties * * @return string */ - public function getGlowSize() { return $this->glowProperties['size']; @@ -245,7 +231,6 @@ class GridLines extends Properties * * @return GridLines */ - private function setGlowSize($size) { $this->glowProperties['size'] = $this->getExcelPointsWidth((float) $size); @@ -262,7 +247,6 @@ class GridLines extends Properties * * @return GridLines */ - private function setGlowColor($color, $alpha, $type) { if (!is_null($color)) { @@ -286,7 +270,6 @@ class GridLines extends Properties * * @return string */ - public function getLineStyleArrowParameters($arrow_selector, $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 int $sh_angle * @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) { $this->activateObject() @@ -326,7 +307,6 @@ class GridLines extends Properties * * @return GridLines */ - private function setShadowPresetsProperties($shadow_presets) { $this->shadowProperties['presets'] = $shadow_presets; @@ -343,16 +323,15 @@ class GridLines extends Properties * * @return GridLines */ - private function setShadowProperiesMapValues(array $properties_map, &$reference = null) { $base_reference = $reference; foreach ($properties_map as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { - $reference = & $this->shadowProperties[$property_key]; + $reference = &$this->shadowProperties[$property_key]; } else { - $reference = & $reference[$property_key]; + $reference = &$reference[$property_key]; } $this->setShadowProperiesMapValues($property_val, $reference); } else { @@ -412,7 +391,6 @@ class GridLines extends Properties * @param int $angle * @return GridLines */ - private function setShadowAngle($angle) { if ($angle !== null) { diff --git a/src/PhpSpreadsheet/Chart/Layout.php b/src/PhpSpreadsheet/Chart/Layout.php index e6434065..d33b861f 100644 --- a/src/PhpSpreadsheet/Chart/Layout.php +++ b/src/PhpSpreadsheet/Chart/Layout.php @@ -81,7 +81,7 @@ class Layout * show legend key * Specifies that legend keys should be shown in data labels * - * @var boolean + * @var bool */ private $showLegendKey; @@ -89,7 +89,7 @@ class Layout * show value * Specifies that the value should be shown in a data label. * - * @var boolean + * @var bool */ private $showVal; @@ -97,7 +97,7 @@ class Layout * show category name * Specifies that the category name should be shown in the data label. * - * @var boolean + * @var bool */ private $showCatName; @@ -105,7 +105,7 @@ class Layout * show data series name * Specifies that the series name should be shown in the data label. * - * @var boolean + * @var bool */ private $showSerName; @@ -113,14 +113,14 @@ class Layout * show percentage * Specifies that the percentage should be shown in the data label. * - * @var boolean + * @var bool */ private $showPercent; /** * show bubble size * - * @var boolean + * @var bool */ private $showBubbleSize; @@ -128,15 +128,14 @@ class Layout * show leader lines * Specifies that leader lines should be shown for the data label. * - * @var boolean + * @var bool */ private $showLeaderLines; - /** * Create a new Layout */ - public function __construct($layout = array()) + public function __construct($layout = []) { if (isset($layout['layoutTarget'])) { $this->layoutTarget = $layout['layoutTarget']; @@ -180,6 +179,7 @@ class Layout public function setLayoutTarget($value) { $this->layoutTarget = $value; + return $this; } @@ -202,6 +202,7 @@ class Layout public function setXMode($value) { $this->xMode = $value; + return $this; } @@ -224,6 +225,7 @@ class Layout public function setYMode($value) { $this->yMode = $value; + return $this; } @@ -246,6 +248,7 @@ class Layout public function setXPosition($value) { $this->xPos = $value; + return $this; } @@ -268,6 +271,7 @@ class Layout public function setYPosition($value) { $this->yPos = $value; + return $this; } @@ -290,6 +294,7 @@ class Layout public function setWidth($value) { $this->width = $value; + return $this; } @@ -312,14 +317,14 @@ class Layout public function setHeight($value) { $this->height = $value; + return $this; } - /** * Get show legend key * - * @return boolean + * @return bool */ public function getShowLegendKey() { @@ -330,19 +335,20 @@ class Layout * Set show legend key * Specifies that legend keys should be shown in data labels. * - * @param boolean $value Show legend key + * @param bool $value Show legend key * @return Layout */ public function setShowLegendKey($value) { $this->showLegendKey = $value; + return $this; } /** * Get show value * - * @return boolean + * @return bool */ public function getShowVal() { @@ -353,19 +359,20 @@ class Layout * Set show val * Specifies that the value should be shown in data labels. * - * @param boolean $value Show val + * @param bool $value Show val * @return Layout */ public function setShowVal($value) { $this->showVal = $value; + return $this; } /** * Get show category name * - * @return boolean + * @return bool */ public function getShowCatName() { @@ -376,19 +383,20 @@ class Layout * Set show cat name * 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 */ public function setShowCatName($value) { $this->showCatName = $value; + return $this; } /** * Get show data series name * - * @return boolean + * @return bool */ public function getShowSerName() { @@ -399,19 +407,20 @@ class Layout * Set show ser name * 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 */ public function setShowSerName($value) { $this->showSerName = $value; + return $this; } /** * Get show percentage * - * @return boolean + * @return bool */ public function getShowPercent() { @@ -422,19 +431,20 @@ class Layout * Set show percentage * Specifies that the percentage should be shown in data labels. * - * @param boolean $value Show percentage + * @param bool $value Show percentage * @return Layout */ public function setShowPercent($value) { $this->showPercent = $value; + return $this; } /** * Get show bubble size * - * @return boolean + * @return bool */ public function getShowBubbleSize() { @@ -445,19 +455,20 @@ class Layout * Set show bubble size * 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 */ public function setShowBubbleSize($value) { $this->showBubbleSize = $value; + return $this; } /** * Get show leader lines * - * @return boolean + * @return bool */ public function getShowLeaderLines() { @@ -468,12 +479,13 @@ class Layout * Set show leader lines * Specifies that leader lines should be shown in data labels. * - * @param boolean $value Show leader lines + * @param bool $value Show leader lines * @return Layout */ public function setShowLeaderLines($value) { $this->showLeaderLines = $value; + return $this; } } diff --git a/src/PhpSpreadsheet/Chart/Legend.php b/src/PhpSpreadsheet/Chart/Legend.php index 539c848d..04efee57 100644 --- a/src/PhpSpreadsheet/Chart/Legend.php +++ b/src/PhpSpreadsheet/Chart/Legend.php @@ -32,24 +32,24 @@ class Legend 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_CUSTOM = -4161; // A custom position. - const XL_LEGEND_POSITION_LEFT = -4131; // Left 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_LEFT = -4131; // Left of the chart. + const XL_LEGEND_POSITION_RIGHT = -4152; // Right of the chart. + const XL_LEGEND_POSITION_TOP = -4160; // Above the chart. - const POSITION_RIGHT = 'r'; - const POSITION_LEFT = 'l'; - const POSITION_BOTTOM = 'b'; - const POSITION_TOP = 't'; + const POSITION_RIGHT = 'r'; + const POSITION_LEFT = 'l'; + const POSITION_BOTTOM = 'b'; + const POSITION_TOP = 't'; const POSITION_TOPRIGHT = 'tr'; - private static $positionXLref = array( + private static $positionXLref = [ self::XL_LEGEND_POSITION_BOTTOM => self::POSITION_BOTTOM, self::XL_LEGEND_POSITION_CORNER => self::POSITION_TOPRIGHT, self::XL_LEGEND_POSITION_CUSTOM => '??', - self::XL_LEGEND_POSITION_LEFT => self::POSITION_LEFT, - self::XL_LEGEND_POSITION_RIGHT => self::POSITION_RIGHT, - self::XL_LEGEND_POSITION_TOP => self::POSITION_TOP - ); + self::XL_LEGEND_POSITION_LEFT => self::POSITION_LEFT, + self::XL_LEGEND_POSITION_RIGHT => self::POSITION_RIGHT, + self::XL_LEGEND_POSITION_TOP => self::POSITION_TOP, + ]; /** * Legend position @@ -61,7 +61,7 @@ class Legend /** * Allow overlay of other elements? * - * @var boolean + * @var bool */ private $overlay = true; @@ -72,7 +72,6 @@ class Legend */ private $layout = null; - /** * Create a new Legend */ @@ -105,6 +104,7 @@ class Legend } $this->position = $position; + return true; } @@ -130,13 +130,14 @@ class Legend } $this->position = self::$positionXLref[$positionXL]; + return true; } /** * Get allow overlay of other elements? * - * @return boolean + * @return bool */ public function getOverlay() { @@ -146,8 +147,8 @@ class Legend /** * Set allow overlay of other elements? * - * @param boolean $overlay - * @return boolean + * @param bool $overlay + * @return bool */ public function setOverlay($overlay = false) { @@ -156,6 +157,7 @@ class Legend } $this->overlay = $overlay; + return true; } diff --git a/src/PhpSpreadsheet/Chart/PlotArea.php b/src/PhpSpreadsheet/Chart/PlotArea.php index 4c887202..61b67392 100644 --- a/src/PhpSpreadsheet/Chart/PlotArea.php +++ b/src/PhpSpreadsheet/Chart/PlotArea.php @@ -38,12 +38,12 @@ class PlotArea * * @var array of DataSeries */ - private $plotSeries = array(); + private $plotSeries = []; /** * Create a new PlotArea */ - public function __construct(Layout $layout = null, $plotSeries = array()) + public function __construct(Layout $layout = null, $plotSeries = []) { $this->layout = $layout; $this->plotSeries = $plotSeries; @@ -72,7 +72,7 @@ class PlotArea /** * Get Number of Plot Series * - * @return integer + * @return int */ public function getPlotSeriesCount() { @@ -80,6 +80,7 @@ class PlotArea foreach ($this->plotSeries as $plot) { $seriesCount += $plot->getPlotSeriesCount(); } + return $seriesCount; } @@ -109,7 +110,7 @@ class PlotArea * @param DataSeries[] * @return PlotArea */ - public function setPlotSeries($plotSeries = array()) + public function setPlotSeries($plotSeries = []) { $this->plotSeries = $plotSeries; diff --git a/src/PhpSpreadsheet/Chart/Properties.php b/src/PhpSpreadsheet/Chart/Properties.php index 13b3c000..a93f3df2 100644 --- a/src/PhpSpreadsheet/Chart/Properties.php +++ b/src/PhpSpreadsheet/Chart/Properties.php @@ -8,7 +8,6 @@ namespace PhpSpreadsheet\Chart; * Date: 7/2/14 * Time: 5:45 PM */ - abstract class Properties { const @@ -133,234 +132,235 @@ abstract class Properties protected function setColorProperties($color, $alpha, $type) { - return array( + return [ 'type' => (string) $type, 'value' => (string) $color, - 'alpha' => (string) $this->getTrueAlpha($alpha) - ); + 'alpha' => (string) $this->getTrueAlpha($alpha), + ]; } protected function getLineStyleArrowSize($array_selector, $array_kay_selector) { - $sizes = array( - 1 => array('w' => 'sm', 'len' => 'sm'), - 2 => array('w' => 'sm', 'len' => 'med'), - 3 => array('w' => 'sm', 'len' => 'lg'), - 4 => array('w' => 'med', 'len' => 'sm'), - 5 => array('w' => 'med', 'len' => 'med'), - 6 => array('w' => 'med', 'len' => 'lg'), - 7 => array('w' => 'lg', 'len' => 'sm'), - 8 => array('w' => 'lg', 'len' => 'med'), - 9 => array('w' => 'lg', 'len' => 'lg') - ); + $sizes = [ + 1 => ['w' => 'sm', 'len' => 'sm'], + 2 => ['w' => 'sm', 'len' => 'med'], + 3 => ['w' => 'sm', 'len' => 'lg'], + 4 => ['w' => 'med', 'len' => 'sm'], + 5 => ['w' => 'med', 'len' => 'med'], + 6 => ['w' => 'med', 'len' => 'lg'], + 7 => ['w' => 'lg', 'len' => 'sm'], + 8 => ['w' => 'lg', 'len' => 'med'], + 9 => ['w' => 'lg', 'len' => 'lg'], + ]; return $sizes[$array_selector][$array_kay_selector]; } protected function getShadowPresetsMap($shadow_presets_option) { - $presets_options = array( + $presets_options = [ //OUTER - 1 => array( + 1 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'direction' => '2700000', 'algn' => 'tl', - 'rotWithShape' => '0' - ), - 2 => array( + 'rotWithShape' => '0', + ], + 2 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'direction' => '5400000', 'algn' => 't', - 'rotWithShape' => '0' - ), - 3 => array( + 'rotWithShape' => '0', + ], + 3 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'direction' => '8100000', 'algn' => 'tr', - 'rotWithShape' => '0' - ), - 4 => array( + 'rotWithShape' => '0', + ], + 4 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'algn' => 'l', - 'rotWithShape' => '0' - ), - 5 => array( + 'rotWithShape' => '0', + ], + 5 => [ 'effect' => 'outerShdw', - 'size' => array( + 'size' => [ 'sx' => '102000', - 'sy' => '102000' - ) - , + 'sy' => '102000', + ], 'blur' => '63500', 'distance' => '38100', 'algn' => 'ctr', - 'rotWithShape' => '0' - ), - 6 => array( + 'rotWithShape' => '0', + ], + 6 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'direction' => '10800000', 'algn' => 'r', - 'rotWithShape' => '0' - ), - 7 => array( + 'rotWithShape' => '0', + ], + 7 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'direction' => '18900000', 'algn' => 'bl', - 'rotWithShape' => '0' - ), - 8 => array( + 'rotWithShape' => '0', + ], + 8 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'direction' => '16200000', - 'rotWithShape' => '0' - ), - 9 => array( + 'rotWithShape' => '0', + ], + 9 => [ 'effect' => 'outerShdw', 'blur' => '50800', 'distance' => '38100', 'direction' => '13500000', 'algn' => 'br', - 'rotWithShape' => '0' - ), + 'rotWithShape' => '0', + ], //INNER - 10 => array( + 10 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', 'direction' => '2700000', - ), - 11 => array( + ], + 11 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', 'direction' => '5400000', - ), - 12 => array( + ], + 12 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', 'direction' => '8100000', - ), - 13 => array( + ], + 13 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', - ), - 14 => array( + ], + 14 => [ 'effect' => 'innerShdw', 'blur' => '114300', - ), - 15 => array( + ], + 15 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', 'direction' => '10800000', - ), - 16 => array( + ], + 16 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', 'direction' => '18900000', - ), - 17 => array( + ], + 17 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', 'direction' => '16200000', - ), - 18 => array( + ], + 18 => [ 'effect' => 'innerShdw', 'blur' => '63500', 'distance' => '50800', 'direction' => '13500000', - ), + ], //perspective - 19 => array( + 19 => [ 'effect' => 'outerShdw', 'blur' => '152400', 'distance' => '317500', - 'size' => array( + 'size' => [ 'sx' => '90000', 'sy' => '-19000', - ), + ], 'direction' => '5400000', 'rotWithShape' => '0', - ), - 20 => array( + ], + 20 => [ 'effect' => 'outerShdw', 'blur' => '76200', 'direction' => '18900000', - 'size' => array( + 'size' => [ 'sy' => '23000', 'kx' => '-1200000', - ), + ], 'algn' => 'bl', 'rotWithShape' => '0', - ), - 21 => array( + ], + 21 => [ 'effect' => 'outerShdw', 'blur' => '76200', 'direction' => '13500000', - 'size' => array( + 'size' => [ 'sy' => '23000', 'kx' => '1200000', - ), + ], 'algn' => 'br', 'rotWithShape' => '0', - ), - 22 => array( + ], + 22 => [ 'effect' => 'outerShdw', 'blur' => '76200', 'distance' => '12700', 'direction' => '2700000', - 'size' => array( + 'size' => [ 'sy' => '-23000', 'kx' => '-800400', - ), + ], 'algn' => 'bl', 'rotWithShape' => '0', - ), - 23 => array( + ], + 23 => [ 'effect' => 'outerShdw', 'blur' => '76200', 'distance' => '12700', 'direction' => '8100000', - 'size' => array( + 'size' => [ 'sy' => '-23000', 'kx' => '800400', - ), + ], 'algn' => 'br', 'rotWithShape' => '0', - ), - ); + ], + ]; return $presets_options[$shadow_presets_option]; } protected function getArrayElementsValue($properties, $elements) { - $reference = & $properties; + $reference = &$properties; if (!is_array($elements)) { return $reference[$elements]; } else { foreach ($elements as $keys) { - $reference = & $reference[$keys]; + $reference = &$reference[$keys]; } + return $reference; } + return $this; } } diff --git a/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php b/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php index 89d4922e..39c09ed1 100644 --- a/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php +++ b/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php @@ -2,7 +2,7 @@ namespace PhpSpreadsheet\Chart\Renderer; -require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'/jpgraph.php'); +require_once \PhpSpreadsheet\Settings::getChartRendererPath() . '/jpgraph.php'; /** * Copyright (c) 2006 - 2016 PhpSpreadsheet @@ -28,31 +28,30 @@ require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'/jpgraph.php'); */ class JpGraph { - private static $width = 640; + private static $width = 640; - private static $height = 480; + private static $height = 480; private static $colourSet = [ 'mediumpurple1', 'palegreen3', 'gold1', 'cadetblue1', 'darkmagenta', 'coral', 'dodgerblue3', 'eggplant', 'mediumblue', 'magenta', 'sandybrown', 'cyan', 'firebrick1', 'forestgreen', 'deeppink4', 'darkolivegreen', - 'goldenrod2' + 'goldenrod2', ]; private static $markSet = [ - 'diamond' => MARK_DIAMOND, - 'square' => MARK_SQUARE, + 'diamond' => MARK_DIAMOND, + 'square' => MARK_SQUARE, 'triangle' => MARK_UTRIANGLE, - 'x' => MARK_X, - 'star' => MARK_STAR, - 'dot' => MARK_FILLEDCIRCLE, - 'dash' => MARK_DTRIANGLE, - 'circle' => MARK_CIRCLE, - 'plus' => MARK_CROSS + 'x' => MARK_X, + 'star' => MARK_STAR, + 'dot' => MARK_FILLEDCIRCLE, + 'dash' => MARK_DTRIANGLE, + 'circle' => MARK_CIRCLE, + 'plus' => MARK_CROSS, ]; - private $chart; private $graph; @@ -61,7 +60,6 @@ class JpGraph private static $plotMark = 0; - private function formatPointMarker($seriesPlot, $markerID) { $plotMarkKeys = array_keys(self::$markSet); @@ -89,7 +87,6 @@ class JpGraph return $seriesPlot; } - private function formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') { $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); @@ -102,7 +99,7 @@ class JpGraph foreach ($datasetLabels as $i => $datasetLabel) { if (is_array($datasetLabel)) { if ($rotation == 'bar') { - $datasetLabels[$i] = implode(" ", $datasetLabel); + $datasetLabels[$i] = implode(' ', $datasetLabel); } else { $datasetLabel = array_reverse($datasetLabel); $datasetLabels[$i] = implode("\n", $datasetLabel); @@ -119,7 +116,6 @@ class JpGraph return $datasetLabels; } - private function percentageSumCalculation($groupID, $seriesCount) { // Adjust our values to a percentage value across all series in the group @@ -141,7 +137,6 @@ class JpGraph return $sumValues; } - private function percentageAdjustValues($dataValues, $sumValues) { foreach ($dataValues as $k => $dataValue) { @@ -151,7 +146,6 @@ class JpGraph return $dataValues; } - private function getCaption($captionElement) { // Read any caption @@ -164,10 +158,10 @@ class JpGraph $caption = implode('', $caption); } } + return $caption; } - private function renderTitle() { $title = $this->getCaption($this->chart->getTitle()); @@ -176,7 +170,6 @@ class JpGraph } } - private function renderLegend() { $legend = $this->chart->getLegend(); @@ -208,7 +201,6 @@ class JpGraph } } - private function renderCartesianPlotArea($type = 'textlin') { $this->graph = new Graph(self::$width, self::$height); @@ -246,7 +238,6 @@ class JpGraph } } - private function renderPiePlotArea($doughnut = false) { $this->graph = new PieGraph(self::$width, self::$height); @@ -254,7 +245,6 @@ class JpGraph $this->renderTitle(); } - private function renderRadarPlotArea() { $this->graph = new RadarGraph(self::$width, self::$height); @@ -263,7 +253,6 @@ class JpGraph $this->renderTitle(); } - private function renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') { $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); @@ -276,7 +265,7 @@ class JpGraph } $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); + $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); } @@ -327,7 +316,6 @@ class JpGraph $this->graph->Add($groupPlot); } - private function renderPlotBar($groupID, $dimensions = '2d') { $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); @@ -351,9 +339,8 @@ class JpGraph $this->graph->xaxis->SetTickLabels($datasetLabels); } - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); + $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); } @@ -413,14 +400,13 @@ class JpGraph $this->graph->Add($groupPlot); } - private function renderPlotScatter($groupID, $bubble) { $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); + $seriesPlots = []; // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { @@ -459,13 +445,12 @@ class JpGraph } } - private function renderPlotRadar($groupID) { $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); + $seriesPlots = []; // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { @@ -473,7 +458,7 @@ class JpGraph $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); - $dataValues = array(); + $dataValues = []; foreach ($dataValuesY as $k => $dataValueY) { $dataValues[$k] = implode(' ', array_reverse($dataValueY)); } @@ -498,15 +483,14 @@ class JpGraph } } - private function renderPlotContour($groupID) { $contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); + $seriesPlots = []; - $dataValues = array(); + $dataValues = []; // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); @@ -519,13 +503,12 @@ class JpGraph $this->graph->Add($seriesPlot); } - private function renderPlotStock($groupID) { $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); - $dataValues = array(); + $dataValues = []; // Loop through each data series in turn and build the plot arrays foreach ($plotOrder as $i => $v) { $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); @@ -537,7 +520,7 @@ class JpGraph return; } - $dataValuesPlot = array(); + $dataValuesPlot = []; // Flatten the plot arrays to a single dimensional array to work with jpgraph for ($j = 0; $j < count($dataValues[0]); ++$j) { for ($i = 0; $i < $seriesCount; ++$i) { @@ -559,10 +542,9 @@ class JpGraph $this->graph->Add($seriesPlot); } - private function renderAreaChart($groupCount, $dimensions = '2d') { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php'; $this->renderCartesianPlotArea(); @@ -571,10 +553,9 @@ class JpGraph } } - private function renderLineChart($groupCount, $dimensions = '2d') { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php'; $this->renderCartesianPlotArea(); @@ -583,10 +564,9 @@ class JpGraph } } - private function renderBarChart($groupCount, $dimensions = '2d') { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_bar.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_bar.php'; $this->renderCartesianPlotArea(); @@ -595,12 +575,11 @@ class JpGraph } } - private function renderScatterChart($groupCount) { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_scatter.php'); - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_regstat.php'); - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_scatter.php'; + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_regstat.php'; + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php'; $this->renderCartesianPlotArea('linlin'); @@ -609,10 +588,9 @@ class JpGraph } } - private function renderBubbleChart($groupCount) { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_scatter.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_scatter.php'; $this->renderCartesianPlotArea('linlin'); @@ -621,12 +599,11 @@ class JpGraph } } - 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') { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_pie3d.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_pie3d.php'; } $this->renderPiePlotArea($doughnut); @@ -644,7 +621,7 @@ class JpGraph } $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 $jLimit = ($multiplePlots) ? $seriesCount : 1; // Loop through each data series in turn @@ -672,7 +649,7 @@ class JpGraph } if ($multiplePlots) { - $seriesPlot->SetSize(($jLimit-$j) / ($jLimit * 4)); + $seriesPlot->SetSize(($jLimit - $j) / ($jLimit * 4)); } if ($doughnut) { @@ -698,10 +675,9 @@ class JpGraph } } - private function renderRadarChart($groupCount) { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_radar.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_radar.php'; $this->renderRadarPlotArea(); @@ -710,10 +686,9 @@ class JpGraph } } - private function renderStockChart($groupCount) { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_stock.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_stock.php'; $this->renderCartesianPlotArea('intint'); @@ -722,10 +697,9 @@ class JpGraph } } - private function renderContourChart($groupCount, $dimensions) { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_contour.php'); + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_contour.php'; $this->renderCartesianPlotArea('intint'); @@ -734,14 +708,13 @@ class JpGraph } } - private function renderCombinationChart($groupCount, $dimensions, $outputDestination) { - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_line.php'); - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_bar.php'); - require_once(\PhpSpreadsheet\Settings::getChartRendererPath().'jpgraph_scatter.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'; + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_bar.php'; + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_scatter.php'; + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_regstat.php'; + require_once \PhpSpreadsheet\Settings::getChartRendererPath() . 'jpgraph_line.php'; $this->renderCartesianPlotArea(); @@ -775,6 +748,7 @@ class JpGraph break; default: $this->graph = null; + return false; } } @@ -782,10 +756,10 @@ class JpGraph $this->renderLegend(); $this->graph->Stroke($outputDestination); + return true; } - public function render($outputDestination) { self::$plotColour = 0; @@ -796,7 +770,7 @@ class JpGraph if ($groupCount == 1) { $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); } else { - $chartTypes = array(); + $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); } @@ -805,6 +779,7 @@ class JpGraph $chartType = array_pop($chartTypes); } elseif (count($chartTypes) == 0) { echo 'Chart is not yet implemented
'; + return false; } else { return $this->renderCombinationChart($groupCount, $dimensions, $outputDestination); @@ -861,22 +836,23 @@ class JpGraph $this->renderStockChart($groupCount, $dimensions); break; default: - echo $chartType.' is not yet implemented
'; + echo $chartType . ' is not yet implemented
'; + return false; } $this->renderLegend(); $this->graph->Stroke($outputDestination); + return true; } - /** * Create a new jpgraph */ public function __construct(\PhpSpreadsheet\Chart $chart) { - $this->graph = null; - $this->chart = $chart; + $this->graph = null; + $this->chart = $chart; } } diff --git a/src/PhpSpreadsheet/Chart/Title.php b/src/PhpSpreadsheet/Chart/Title.php index 5ec5496a..dbf3a243 100644 --- a/src/PhpSpreadsheet/Chart/Title.php +++ b/src/PhpSpreadsheet/Chart/Title.php @@ -26,7 +26,6 @@ namespace PhpSpreadsheet\Chart; */ class Title { - /** * Title Caption * diff --git a/src/PhpSpreadsheet/Comment.php b/src/PhpSpreadsheet/Comment.php index 3c3304d5..b7736e16 100644 --- a/src/PhpSpreadsheet/Comment.php +++ b/src/PhpSpreadsheet/Comment.php @@ -64,7 +64,7 @@ class Comment implements IComparable /** * Visible * - * @var boolean + * @var bool */ private $visible = false; @@ -97,8 +97,8 @@ class Comment implements IComparable public function __construct() { // Initialise variables - $this->author = 'Author'; - $this->text = new RichText(); + $this->author = 'Author'; + $this->text = new RichText(); $this->fillColor = new Style\Color('FFFFFFE1'); $this->alignment = Style\Alignment::HORIZONTAL_GENERAL; } @@ -122,6 +122,7 @@ class Comment implements IComparable public function setAuthor($pValue = '') { $this->author = $pValue; + return $this; } @@ -144,6 +145,7 @@ class Comment implements IComparable public function setText(RichText $pValue) { $this->text = $pValue; + return $this; } @@ -166,6 +168,7 @@ class Comment implements IComparable public function setWidth($value = '96pt') { $this->width = $value; + return $this; } @@ -188,6 +191,7 @@ class Comment implements IComparable public function setHeight($value = '55.5pt') { $this->height = $value; + return $this; } @@ -210,6 +214,7 @@ class Comment implements IComparable public function setMarginLeft($value = '59.25pt') { $this->marginLeft = $value; + return $this; } @@ -232,13 +237,14 @@ class Comment implements IComparable public function setMarginTop($value = '1.5pt') { $this->marginTop = $value; + return $this; } /** * Is the comment visible by default? * - * @return boolean + * @return bool */ public function getVisible() { @@ -248,12 +254,13 @@ class Comment implements IComparable /** * Set comment default visibility * - * @param boolean $value + * @param bool $value * @return Comment */ public function setVisible($value = false) { $this->visible = $value; + return $this; } @@ -276,6 +283,7 @@ class Comment implements IComparable public function setAlignment($pValue = Style\Alignment::HORIZONTAL_GENERAL) { $this->alignment = $pValue; + return $this; } diff --git a/src/PhpSpreadsheet/Document/Properties.php b/src/PhpSpreadsheet/Document/Properties.php index 5bfb62b7..615e5821 100644 --- a/src/PhpSpreadsheet/Document/Properties.php +++ b/src/PhpSpreadsheet/Document/Properties.php @@ -29,9 +29,9 @@ class Properties /** constants */ const PROPERTY_TYPE_BOOLEAN = 'b'; const PROPERTY_TYPE_INTEGER = 'i'; - const PROPERTY_TYPE_FLOAT = 'f'; - const PROPERTY_TYPE_DATE = 'd'; - const PROPERTY_TYPE_STRING = 's'; + const PROPERTY_TYPE_FLOAT = 'f'; + const PROPERTY_TYPE_DATE = 'd'; + const PROPERTY_TYPE_STRING = 's'; const PROPERTY_TYPE_UNKNOWN = 'u'; /** @@ -116,8 +116,7 @@ class Properties * * @var string */ - private $customProperties = array(); - + private $customProperties = []; /** * Create a new Document Properties instance @@ -126,7 +125,7 @@ class Properties { // Initialise values $this->lastModifiedBy = $this->creator; - $this->created = time(); + $this->created = time(); $this->modified = time(); } @@ -149,6 +148,7 @@ class Properties public function setCreator($pValue = '') { $this->creator = $pValue; + return $this; } @@ -171,6 +171,7 @@ class Properties public function setLastModifiedBy($pValue = '') { $this->lastModifiedBy = $pValue; + return $this; } @@ -203,6 +204,7 @@ class Properties } $this->created = $pValue; + return $this; } @@ -235,6 +237,7 @@ class Properties } $this->modified = $pValue; + return $this; } @@ -257,6 +260,7 @@ class Properties public function setTitle($pValue = '') { $this->title = $pValue; + return $this; } @@ -279,6 +283,7 @@ class Properties public function setDescription($pValue = '') { $this->description = $pValue; + return $this; } @@ -301,6 +306,7 @@ class Properties public function setSubject($pValue = '') { $this->subject = $pValue; + return $this; } @@ -323,6 +329,7 @@ class Properties public function setKeywords($pValue = '') { $this->keywords = $pValue; + return $this; } @@ -345,6 +352,7 @@ class Properties public function setCategory($pValue = '') { $this->category = $pValue; + return $this; } @@ -367,6 +375,7 @@ class Properties public function setCompany($pValue = '') { $this->company = $pValue; + return $this; } @@ -389,6 +398,7 @@ class Properties public function setManager($pValue = '') { $this->manager = $pValue; + return $this; } @@ -406,7 +416,7 @@ class Properties * Check if a Custom Property is defined * * @param string $propertyName - * @return boolean + * @return bool */ public function isCustomPropertySet($propertyName) { @@ -454,11 +464,11 @@ class Properties */ 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_STRING, self::PROPERTY_TYPE_DATE, - self::PROPERTY_TYPE_BOOLEAN)))) { + self::PROPERTY_TYPE_BOOLEAN, ]))) { if ($propertyValue === null) { $propertyType = self::PROPERTY_TYPE_STRING; } elseif (is_float($propertyValue)) { @@ -472,10 +482,11 @@ class Properties } } - $this->customProperties[$propertyName] = array( + $this->customProperties[$propertyName] = [ 'value' => $propertyValue, - 'type' => $propertyType - ); + 'type' => $propertyType, + ]; + return $this; } @@ -550,6 +561,7 @@ class Properties return $propertyValue; break; } + return $propertyValue; } @@ -603,6 +615,7 @@ class Properties return self::PROPERTY_TYPE_UNKNOWN; break; } + return self::PROPERTY_TYPE_UNKNOWN; } } diff --git a/src/PhpSpreadsheet/Document/Security.php b/src/PhpSpreadsheet/Document/Security.php index d703c75d..32f33267 100644 --- a/src/PhpSpreadsheet/Document/Security.php +++ b/src/PhpSpreadsheet/Document/Security.php @@ -29,21 +29,21 @@ class Security /** * LockRevision * - * @var boolean + * @var bool */ private $lockRevision = false; /** * LockStructure * - * @var boolean + * @var bool */ private $lockStructure = false; /** * LockWindows * - * @var boolean + * @var bool */ private $lockWindows = false; @@ -71,7 +71,7 @@ class Security /** * Is some sort of document security enabled? * - * @return boolean + * @return bool */ public function isSecurityEnabled() { @@ -83,7 +83,7 @@ class Security /** * Get LockRevision * - * @return boolean + * @return bool */ public function getLockRevision() { @@ -93,19 +93,20 @@ class Security /** * Set LockRevision * - * @param boolean $pValue + * @param bool $pValue * @return Security */ public function setLockRevision($pValue = false) { $this->lockRevision = $pValue; + return $this; } /** * Get LockStructure * - * @return boolean + * @return bool */ public function getLockStructure() { @@ -115,19 +116,20 @@ class Security /** * Set LockStructure * - * @param boolean $pValue + * @param bool $pValue * @return Security */ public function setLockStructure($pValue = false) { $this->lockStructure = $pValue; + return $this; } /** * Get LockWindows * - * @return boolean + * @return bool */ public function getLockWindows() { @@ -137,12 +139,13 @@ class Security /** * Set LockWindows * - * @param boolean $pValue + * @param bool $pValue * @return Security */ public function setLockWindows($pValue = false) { $this->lockWindows = $pValue; + return $this; } @@ -160,7 +163,7 @@ class Security * Set RevisionsPassword * * @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 */ public function setRevisionsPassword($pValue = '', $pAlreadyHashed = false) @@ -169,6 +172,7 @@ class Security $pValue = \PhpSpreadsheet\Shared\PasswordHasher::hashPassword($pValue); } $this->revisionsPassword = $pValue; + return $this; } @@ -186,7 +190,7 @@ class Security * Set WorkbookPassword * * @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 */ public function setWorkbookPassword($pValue = '', $pAlreadyHashed = false) @@ -195,6 +199,7 @@ class Security $pValue = \PhpSpreadsheet\Shared\PasswordHasher::hashPassword($pValue); } $this->workbookPassword = $pValue; + return $this; } diff --git a/src/PhpSpreadsheet/HashTable.php b/src/PhpSpreadsheet/HashTable.php index 3763727f..fd73c157 100644 --- a/src/PhpSpreadsheet/HashTable.php +++ b/src/PhpSpreadsheet/HashTable.php @@ -119,12 +119,11 @@ class HashTable /** * Clear HashTable - * */ public function clear() { - $this->items = array(); - $this->keyMap = array(); + $this->items = []; + $this->keyMap = []; } /** @@ -153,7 +152,6 @@ class HashTable * * @param int $pIndex * @return IComparable - * */ public function getByIndex($pIndex = 0) { @@ -169,7 +167,6 @@ class HashTable * * @param string $pHashCode * @return IComparable - * */ public function getByHashCode($pHashCode = '') { diff --git a/src/PhpSpreadsheet/Helper/HTML.php b/src/PhpSpreadsheet/Helper/HTML.php index fe76f4d4..0baf0491 100644 --- a/src/PhpSpreadsheet/Helper/HTML.php +++ b/src/PhpSpreadsheet/Helper/HTML.php @@ -557,7 +557,7 @@ class HTML protected $subscript = false; protected $strikethrough = false; - protected $startTagCallbacks = array( + protected $startTagCallbacks = [ 'font' => 'startFontTag', 'b' => 'startBoldTag', 'strong' => 'startBoldTag', @@ -568,9 +568,9 @@ class HTML 'del' => 'startStrikethruTag', 'sup' => 'startSuperscriptTag', 'sub' => 'startSubscriptTag', - ); + ]; - protected $endTagCallbacks = array( + protected $endTagCallbacks = [ 'font' => 'endFontTag', 'b' => 'endBoldTag', 'strong' => 'endBoldTag', @@ -589,9 +589,9 @@ class HTML 'h4' => 'breakTag', 'h5' => 'breakTag', 'h6' => 'breakTag', - ); + ]; - protected $stack = array(); + protected $stack = []; protected $stringData = ''; @@ -602,7 +602,7 @@ class HTML $this->face = $this->size = $this->color = null; $this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false; - $this->stack = array(); + $this->stack = []; $this->stringData = ''; } @@ -612,7 +612,7 @@ class HTML $this->initialise(); // Create a new DOM object - $dom = new \DOMDocument; + $dom = new \DOMDocument(); // 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 $loaded = @$dom->loadHTML($html); @@ -687,6 +687,7 @@ class HTML foreach ($values[0] as &$value) { $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); } + return implode($values[0]); } @@ -801,7 +802,7 @@ class HTML if (isset($callbacks[$callbackTag])) { $elementHandler = $callbacks[$callbackTag]; if (method_exists($this, $elementHandler)) { - call_user_func(array($this, $elementHandler), $element); + call_user_func([$this, $elementHandler], $element); } } } diff --git a/src/PhpSpreadsheet/IOFactory.php b/src/PhpSpreadsheet/IOFactory.php index 54514a11..01fe6be7 100644 --- a/src/PhpSpreadsheet/IOFactory.php +++ b/src/PhpSpreadsheet/IOFactory.php @@ -30,22 +30,20 @@ class IOFactory * Search locations * * @var array - * @access private * @static */ - private static $searchLocations = array( - array( 'type' => 'IWriter', 'path' => 'PhpSpreadsheet/Writer/{0}.php', 'class' => '\\PhpSpreadsheet\\Writer\\{0}' ), - array( 'type' => 'IReader', 'path' => 'PhpSpreadsheet/Reader/{0}.php', 'class' => '\\PhpSpreadsheet\\Reader\\{0}' ) - ); + private static $searchLocations = [ + ['type' => 'IWriter', 'path' => 'PhpSpreadsheet/Writer/{0}.php', 'class' => '\\PhpSpreadsheet\\Writer\\{0}'], + ['type' => 'IReader', 'path' => 'PhpSpreadsheet/Reader/{0}.php', 'class' => '\\PhpSpreadsheet\\Reader\\{0}'], + ]; /** * Autoresolve classes * * @var array - * @access private * @static */ - private static $autoResolveClasses = array( + private static $autoResolveClasses = [ 'Excel2007', 'Excel5', 'Excel2003XML', @@ -54,7 +52,7 @@ class IOFactory 'Gnumeric', 'HTML', 'CSV', - ); + ]; /** * Private constructor for IOFactory @@ -67,7 +65,6 @@ class IOFactory * Get search locations * * @static - * @access public * @return array */ public static function getSearchLocations() @@ -79,7 +76,6 @@ class IOFactory * Set search locations * * @static - * @access public * @param array $value * @throws Reader\Exception */ @@ -96,25 +92,23 @@ class IOFactory * Add search location * * @static - * @access public * @param string $type Example: IWriter * @param string $location Example: PhpSpreadsheet/Writer/{0}.php * @param string $classname Example: Writer\{0} */ 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 * * @static - * @access public * @param Spreadsheet $spreadsheet * @param string $writerType Example: Excel2007 - * @return Writer\IWriter * @throws Writer\Exception + * @return Writer\IWriter */ public static function createWriter(Spreadsheet $spreadsheet, $writerType = '') { @@ -141,10 +135,9 @@ class IOFactory * Create Reader\IReader * * @static - * @access public * @param string $readerType Example: Excel2007 - * @return Reader\IReader * @throws Reader\Exception + * @return Reader\IReader */ public static function createReader($readerType = '') { @@ -171,14 +164,14 @@ class IOFactory * Loads Spreadsheet from file using automatic Reader\IReader resolution * * @static - * @access public * @param string $pFilename The name of the spreadsheet file - * @return Spreadsheet * @throws Reader\Exception + * @return Spreadsheet */ public static function load($pFilename) { $reader = self::createReaderForFile($pFilename); + return $reader->load($pFilename); } @@ -186,10 +179,9 @@ class IOFactory * Identify file type using automatic Reader\IReader resolution * * @static - * @access public * @param string $pFilename The name of the spreadsheet file to identify - * @return string * @throws Reader\Exception + * @return string */ public static function identify($pFilename) { @@ -197,6 +189,7 @@ class IOFactory $className = get_class($reader); $classType = explode('\\', $className); unset($reader); + return array_pop($classType); } @@ -204,10 +197,9 @@ class IOFactory * Create Reader\IReader for file using automatic Reader\IReader resolution * * @static - * @access public * @param string $pFilename The name of the spreadsheet file - * @return Reader\IReader * @throws Reader\Exception + * @return Reader\IReader */ public static function createReaderForFile($pFilename) { diff --git a/src/PhpSpreadsheet/NamedRange.php b/src/PhpSpreadsheet/NamedRange.php index d76a88b5..08742670 100644 --- a/src/PhpSpreadsheet/NamedRange.php +++ b/src/PhpSpreadsheet/NamedRange.php @@ -81,11 +81,11 @@ class NamedRange } // Set local members - $this->name = $pName; - $this->worksheet = $pWorksheet; - $this->range = $pRange; - $this->localOnly = $pLocalOnly; - $this->scope = ($pLocalOnly == true) ? (($pScope == null) ? $pWorksheet : $pScope) : null; + $this->name = $pName; + $this->worksheet = $pWorksheet; + $this->range = $pRange; + $this->localOnly = $pLocalOnly; + $this->scope = ($pLocalOnly == true) ? (($pScope == null) ? $pWorksheet : $pScope) : null; } /** @@ -124,6 +124,7 @@ class NamedRange $newTitle = $this->name; ReferenceHelper::getInstance()->updateNamedFormulas($this->worksheet->getParent(), $oldTitle, $newTitle); } + return $this; } @@ -148,6 +149,7 @@ class NamedRange if ($value !== null) { $this->worksheet = $value; } + return $this; } @@ -172,6 +174,7 @@ class NamedRange if ($value !== null) { $this->range = $value; } + return $this; } @@ -195,6 +198,7 @@ class NamedRange { $this->localOnly = $value; $this->scope = $value ? $this->worksheet : null; + return $this; } @@ -218,6 +222,7 @@ class NamedRange { $this->scope = $value; $this->localOnly = ($value == null) ? false : true; + return $this; } diff --git a/src/PhpSpreadsheet/Reader/BaseReader.php b/src/PhpSpreadsheet/Reader/BaseReader.php index 901455f3..8afb069d 100644 --- a/src/PhpSpreadsheet/Reader/BaseReader.php +++ b/src/PhpSpreadsheet/Reader/BaseReader.php @@ -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; * or whether it should read both data and formatting * - * @var boolean + * @var bool */ 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 * null value or empty string * - * @var boolean + * @var bool */ protected $readEmptyCells = true; @@ -48,7 +48,7 @@ abstract class BaseReader implements IReader * Read charts that are defined 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; @@ -69,13 +69,12 @@ abstract class BaseReader implements IReader protected $fileHandle = null; - /** * 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 false (the default) it will read data and formatting. * - * @return boolean + * @return bool */ 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 false (the default) to advise the Reader to read both data and formatting for cells. * - * @param boolean $pValue + * @param bool $pValue * * @return IReader */ public function setReadDataOnly($pValue = false) { $this->readDataOnly = (boolean) $pValue; + 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 false it will not read data for cells containing a null value or an empty string. * - * @return boolean + * @return bool */ 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 false to advise the Reader to ignore cells containing a null value or an empty string. * - * @param boolean $pValue + * @param bool $pValue * * @return IReader */ public function setReadEmptyCells($pValue = true) { $this->readEmptyCells = (boolean) $pValue; + 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. * If false (the default) it will ignore any charts defined in the workbook file. * - * @return boolean + * @return bool */ 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. * Set to false (the default) to discard charts. * - * @param boolean $pValue + * @param bool $pValue * * @return IReader */ public function setIncludeCharts($pValue = false) { $this->includeCharts = (boolean) $pValue; + return $this; } @@ -180,7 +182,8 @@ abstract class BaseReader implements IReader return $this->setLoadAllSheets(); } - $this->loadSheetsOnly = is_array($value) ? $value : array($value); + $this->loadSheetsOnly = is_array($value) ? $value : [$value]; + return $this; } @@ -193,6 +196,7 @@ abstract class BaseReader implements IReader public function setLoadAllSheets() { $this->loadSheetsOnly = null; + return $this; } @@ -215,6 +219,7 @@ abstract class BaseReader implements IReader public function setReadFilter(IReadFilter $pValue) { $this->readFilter = $pValue; + return $this; } @@ -229,13 +234,13 @@ abstract class BaseReader implements IReader { // Check if file exists 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 $this->fileHandle = fopen($pFilename, 'r'); 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? * * @param string $pFilename - * @return boolean * @throws Exception + * @return bool */ public function canRead($pFilename) { @@ -257,6 +262,7 @@ abstract class BaseReader implements IReader $readable = $this->isValidFormat(); fclose($this->fileHandle); + return $readable; } @@ -272,6 +278,7 @@ abstract class BaseReader implements IReader if (preg_match($pattern, $xml)) { throw new Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); } + return $xml; } diff --git a/src/PhpSpreadsheet/Reader/CSV.php b/src/PhpSpreadsheet/Reader/CSV.php index 4fac17e7..7e11073f 100644 --- a/src/PhpSpreadsheet/Reader/CSV.php +++ b/src/PhpSpreadsheet/Reader/CSV.php @@ -31,7 +31,6 @@ class CSV extends BaseReader implements IReader /** * Input encoding * - * @access private * @var string */ private $inputEncoding = 'UTF-8'; @@ -39,7 +38,6 @@ class CSV extends BaseReader implements IReader /** * Delimiter * - * @access private * @var string */ private $delimiter = ','; @@ -47,7 +45,6 @@ class CSV extends BaseReader implements IReader /** * Enclosure * - * @access private * @var string */ private $enclosure = '"'; @@ -55,7 +52,6 @@ class CSV extends BaseReader implements IReader /** * Sheet index to read * - * @access private * @var int */ private $sheetIndex = 0; @@ -63,7 +59,6 @@ class CSV extends BaseReader implements IReader /** * Load rows contiguously * - * @access private * @var int */ private $contiguous = false; @@ -75,7 +70,6 @@ class CSV extends BaseReader implements IReader */ private $contiguousRow = -1; - /** * 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 * - * @return boolean + * @return bool */ protected function isValidFormat() { @@ -102,6 +96,7 @@ class CSV extends BaseReader implements IReader public function setInputEncoding($pValue = 'UTF-8') { $this->inputEncoding = $pValue; + return $this; } @@ -117,7 +112,6 @@ class CSV extends BaseReader implements IReader /** * Move filepointer past any BOM marker - * */ protected function skipBOM() { @@ -151,7 +145,6 @@ class CSV extends BaseReader implements IReader /** * Identify any separator that is explicitly set in the file - * */ protected function checkSeparator() { @@ -162,8 +155,10 @@ class CSV extends BaseReader implements IReader if ((strlen(trim($line, "\r\n")) == 5) && (stripos($line, 'sep=') === 0)) { $this->delimiter = substr($line, 4, 1); + return; } + return $this->skipBOM(); } @@ -179,7 +174,7 @@ class CSV extends BaseReader implements IReader $this->openFile($pFilename); if (!$this->isValidFormat()) { fclose($this->fileHandle); - throw new Exception($pFilename . " is an Invalid Spreadsheet file."); + throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); } $fileHandle = $this->fileHandle; @@ -187,9 +182,9 @@ class CSV extends BaseReader implements IReader $this->skipBOM(); $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]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnIndex'] = 0; @@ -198,7 +193,7 @@ class CSV extends BaseReader implements IReader // Loop through each line of the file in turn 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); } @@ -215,8 +210,8 @@ class CSV extends BaseReader implements IReader * Loads Spreadsheet from file * * @param string $pFilename - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function load($pFilename) { @@ -232,8 +227,8 @@ class CSV extends BaseReader implements IReader * * @param string $pFilename * @param Spreadsheet $spreadsheet - * @return Spreadsheet * @throws Exception + * @return Spreadsheet */ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) { @@ -244,7 +239,7 @@ class CSV extends BaseReader implements IReader $this->openFile($pFilename); if (!$this->isValidFormat()) { fclose($this->fileHandle); - throw new Exception($pFilename . " is an Invalid Spreadsheet file."); + throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); } $fileHandle = $this->fileHandle; @@ -258,9 +253,9 @@ class CSV extends BaseReader implements IReader } $sheet = $spreadsheet->setActiveSheetIndex($this->sheetIndex); - $escapeEnclosures = array( "\\" . $this->enclosure, - $this->enclosure . $this->enclosure - ); + $escapeEnclosures = ['\\' . $this->enclosure, + $this->enclosure . $this->enclosure, + ]; // Set our starting row based on whether we're in contiguous mode or not $currentRow = 1; @@ -321,6 +316,7 @@ class CSV extends BaseReader implements IReader public function setDelimiter($pValue = ',') { $this->delimiter = $pValue; + return $this; } @@ -346,13 +342,14 @@ class CSV extends BaseReader implements IReader $pValue = '"'; } $this->enclosure = $pValue; + return $this; } /** * Get sheet index * - * @return integer + * @return int */ public function getSheetIndex() { @@ -362,19 +359,20 @@ class CSV extends BaseReader implements IReader /** * Set sheet index * - * @param integer $pValue Sheet index + * @param int $pValue Sheet index * @return CSV */ public function setSheetIndex($pValue = 0) { $this->sheetIndex = $pValue; + return $this; } /** * Set Contiguous * - * @param boolean $contiguous + * @param bool $contiguous */ public function setContiguous($contiguous = false) { @@ -389,7 +387,7 @@ class CSV extends BaseReader implements IReader /** * Get Contiguous * - * @return boolean + * @return bool */ public function getContiguous() { diff --git a/src/PhpSpreadsheet/Reader/DefaultReadFilter.php b/src/PhpSpreadsheet/Reader/DefaultReadFilter.php index 062bbb8e..1d208ee2 100644 --- a/src/PhpSpreadsheet/Reader/DefaultReadFilter.php +++ b/src/PhpSpreadsheet/Reader/DefaultReadFilter.php @@ -32,7 +32,7 @@ class DefaultReadFilter implements IReadFilter * @param $column Column address (as a string value like "A", or "IV") * @param $row Row number * @param $worksheetName Optional worksheet name - * @return boolean + * @return bool */ public function readCell($column, $row, $worksheetName = '') { diff --git a/src/PhpSpreadsheet/Reader/Excel2003XML.php b/src/PhpSpreadsheet/Reader/Excel2003XML.php index ec187da9..b313cf5e 100644 --- a/src/PhpSpreadsheet/Reader/Excel2003XML.php +++ b/src/PhpSpreadsheet/Reader/Excel2003XML.php @@ -31,7 +31,7 @@ class Excel2003XML extends BaseReader implements IReader * * @var array */ - protected $styles = array(); + protected $styles = []; /** * Character set used in the file @@ -48,13 +48,12 @@ class Excel2003XML extends BaseReader implements IReader $this->readFilter = new DefaultReadFilter(); } - /** * Can the current IReader read the file? * * @param string $pFilename - * @return boolean * @throws Exception + * @return bool */ public function canRead($pFilename) { @@ -69,10 +68,10 @@ class Excel2003XML extends BaseReader implements IReader // Rowset xmlns:z="#RowsetSchema" // - $signature = array( + $signature = [ '' - ); + '', + ]; // Open file $this->openFile($pFilename); @@ -100,7 +99,6 @@ class Excel2003XML extends BaseReader implements IReader return $valid; } - /** * 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 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)) { - 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( $this->securityScan(file_get_contents($pFilename)), @@ -135,7 +133,6 @@ class Excel2003XML extends BaseReader implements IReader return $worksheetNames; } - /** * 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 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( $this->securityScan(file_get_contents($pFilename)), @@ -163,7 +160,7 @@ class Excel2003XML extends BaseReader implements IReader foreach ($xml_ss->Worksheet as $worksheet) { $worksheet_ss = $worksheet->attributes($namespaces['ss']); - $tmpInfo = array(); + $tmpInfo = []; $tmpInfo['worksheetName'] = ''; $tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnIndex'] = 0; @@ -210,13 +207,12 @@ class Excel2003XML extends BaseReader implements IReader return $worksheetInfo; } - /** * Loads PhpSpreadsheet from file * * @param string $pFilename - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function load($pFilename) { @@ -234,9 +230,11 @@ class Excel2003XML extends BaseReader implements IReader foreach ($styleList as $style) { if ($styleAttributeValue == strtolower($style)) { $styleAttributeValue = $style; + return true; } } + return false; } @@ -247,10 +245,11 @@ class Excel2003XML extends BaseReader implements IReader */ 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 += $UNIT_OFFSET_MAP[($pxs % 7)]; + return $widthUnits; } @@ -264,6 +263,7 @@ class Excel2003XML extends BaseReader implements IReader $pixels = ($widthUnits / 256) * 7; $offsetWidthUnits = $widthUnits % 256; $pixels += round($offsetWidthUnits / (256 / 7)); + return $pixels; } @@ -277,46 +277,46 @@ class Excel2003XML extends BaseReader implements IReader * * @param string $pFilename * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) { - $fromFormats = array('\-', '\ '); - $toFormats = array('-', ' '); + $fromFormats = ['\-', '\ ']; + $toFormats = ['-', ' ']; - $underlineStyles = array ( + $underlineStyles = [ \PhpSpreadsheet\Style\Font::UNDERLINE_NONE, \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE, \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING, \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE, - \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING - ); - $verticalAlignmentStyles = array ( + \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING, + ]; + $verticalAlignmentStyles = [ \PhpSpreadsheet\Style\Alignment::VERTICAL_BOTTOM, \PhpSpreadsheet\Style\Alignment::VERTICAL_TOP, \PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, - \PhpSpreadsheet\Style\Alignment::VERTICAL_JUSTIFY - ); - $horizontalAlignmentStyles = array ( + \PhpSpreadsheet\Style\Alignment::VERTICAL_JUSTIFY, + ]; + $horizontalAlignmentStyles = [ \PhpSpreadsheet\Style\Alignment::HORIZONTAL_GENERAL, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER_CONTINUOUS, - \PhpSpreadsheet\Style\Alignment::HORIZONTAL_JUSTIFY - ); + \PhpSpreadsheet\Style\Alignment::HORIZONTAL_JUSTIFY, + ]; $timezoneObj = new \DateTimeZone('Europe/London'); $GMT = new \DateTimeZone('UTC'); // Check if file exists 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)) { - throw new Exception($pFilename . " is an Invalid Spreadsheet file."); + throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); } $xml = simplexml_load_string( @@ -403,14 +403,14 @@ class Excel2003XML extends BaseReader implements IReader $style_ss = $style->attributes($namespaces['ss']); $styleID = (string) $style_ss['ID']; // echo 'Style ID = '.$styleID.'
'; - $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) { $styleAttributes = $styleData->attributes($namespaces['ss']); // echo $styleType.'
'; switch ($styleType) { case 'Alignment': foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { -// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + // echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; $styleAttributeValue = (string) $styleAttributeValue; switch ($styleAttributeKey) { case 'Vertical': @@ -432,9 +432,9 @@ class Excel2003XML extends BaseReader implements IReader case 'Borders': foreach ($styleData->Border as $borderStyle) { $borderAttributes = $borderStyle->attributes($namespaces['ss']); - $thisBorder = array(); + $thisBorder = []; foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) { -// echo $borderStyleKey.' = '.$borderStyleValue.'
'; + // echo $borderStyleKey.' = '.$borderStyleValue.'
'; switch ($borderStyleKey) { case 'LineStyle': $thisBorder['style'] = \PhpSpreadsheet\Style\Border::BORDER_MEDIUM; @@ -461,7 +461,7 @@ class Excel2003XML extends BaseReader implements IReader break; case 'Font': foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { -// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + // echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; $styleAttributeValue = (string) $styleAttributeValue; switch ($styleAttributeKey) { case 'FontName': @@ -489,7 +489,7 @@ class Excel2003XML extends BaseReader implements IReader break; case 'Interior': foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { -// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + // echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; switch ($styleAttributeKey) { case 'Color': $this->styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue, 1); @@ -499,7 +499,7 @@ class Excel2003XML extends BaseReader implements IReader break; case 'NumberFormat': foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { -// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + // echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); switch ($styleAttributeValue) { case 'Short Date': @@ -513,7 +513,7 @@ class Excel2003XML extends BaseReader implements IReader break; case 'Protection': foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { -// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + // echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; } break; } @@ -552,7 +552,7 @@ class Excel2003XML extends BaseReader implements IReader foreach ($worksheet->Table->Column as $columnData) { $columnData_ss = $columnData->attributes($namespaces['ss']); 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'])) { $columnWidth = $columnData_ss['Width']; @@ -578,9 +578,9 @@ class Excel2003XML extends BaseReader implements IReader foreach ($rowData->Cell as $cell) { $cell_ss = $cell->attributes($namespaces['ss']); 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()->readCell($columnID, $rowID, $worksheetName)) { @@ -591,14 +591,14 @@ class Excel2003XML extends BaseReader implements IReader if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) { $columnTo = $columnID; if (isset($cell_ss['MergeAcross'])) { - $additionalMergedCells += (int)$cell_ss['MergeAcross']; - $columnTo = \PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] -1); + $additionalMergedCells += (int) $cell_ss['MergeAcross']; + $columnTo = \PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] - 1); } $rowTo = $rowID; if (isset($cell_ss['MergeDown'])) { $rowTo = $rowTo + $cell_ss['MergeDown']; } - $cellRange .= ':'.$columnTo.$rowTo; + $cellRange .= ':' . $columnTo . $rowTo; $spreadsheet->getActiveSheet()->mergeCells($cellRange); } @@ -655,7 +655,7 @@ class Excel2003XML extends BaseReader implements IReader } if ($hasCalculatedValue) { -// echo 'FORMULA
'; + // echo 'FORMULA
'; $type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA; $columnNumber = \PhpSpreadsheet\Cell::columnIndexFromString($columnID); if (substr($cellDataFormula, 0, 3) == 'of:') { @@ -666,7 +666,7 @@ class Excel2003XML extends BaseReader implements IReader foreach ($temp as &$value) { // Only replace in alternate array entries (i.e. non-quoted blocks) if ($key = !$key) { - $value = str_replace(array('[.', '.', ']'), '', $value); + $value = str_replace(['[.', '.', ']'], '', $value); } } } else { @@ -703,7 +703,7 @@ class Excel2003XML extends BaseReader implements IReader if ($columnReference{0} == '[') { $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])); } } @@ -717,20 +717,20 @@ class Excel2003XML extends BaseReader implements IReader // echo 'Cell '.$columnID.$rowID.' is a '.$type.' with a value of '.(($hasCalculatedValue) ? $cellDataFormula : $cellValue).'
'; // - $spreadsheet->getActiveSheet()->getCell($columnID.$rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type); + $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type); if ($hasCalculatedValue) { -// echo 'Formula result is '.$cellValue.'
'; - $spreadsheet->getActiveSheet()->getCell($columnID.$rowID)->setCalculatedValue($cellValue); + // echo 'Formula result is '.$cellValue.'
'; + $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setCalculatedValue($cellValue); } $cellIsSet = $rowHasData = true; } if (isset($cell->Comment)) { -// echo 'comment found
'; + // echo 'comment found
'; $commentAttributes = $cell->Comment->attributes($namespaces['ss']); $author = 'unknown'; if (isset($commentAttributes->Author)) { - $author = (string)$commentAttributes->Author; + $author = (string) $commentAttributes->Author; // echo 'Author: ', $author,'
'; } $node = $cell->Comment->Data->asXML(); @@ -738,18 +738,18 @@ class Excel2003XML extends BaseReader implements IReader // echo $annotation,'
'; $annotation = strip_tags($node); // echo 'Annotation: ', $annotation,'
'; - $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']))) { $style = (string) $cell_ss['StyleID']; // echo 'Cell style for '.$columnID.$rowID.' is '.$style.'
'; if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) { -// echo 'Cell '.$columnID.$rowID.'
'; + // echo 'Cell '.$columnID.$rowID.'
'; // print_r($this->styles[$style]); // echo '
'; - if (!$spreadsheet->getActiveSheet()->cellExists($columnID.$rowID)) { - $spreadsheet->getActiveSheet()->getCell($columnID.$rowID)->setValue(null); + if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) { + $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null); } $spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]); } @@ -757,7 +757,7 @@ class Excel2003XML extends BaseReader implements IReader ++$columnID; while ($additionalMergedCells > 0) { ++$columnID; - $additionalMergedCells--; + --$additionalMergedCells; } } @@ -782,16 +782,15 @@ class Excel2003XML extends BaseReader implements IReader return $spreadsheet; } - protected static function convertStringEncoding($string, $charset) { if ($charset != 'UTF-8') { return \PhpSpreadsheet\Shared\StringHelper::convertEncoding($string, 'UTF-8', $charset); } + return $string; } - protected function parseRichText($is = '') { $value = new \PhpSpreadsheet\RichText(); diff --git a/src/PhpSpreadsheet/Reader/Excel2007.php b/src/PhpSpreadsheet/Reader/Excel2007.php index c3829500..84702691 100644 --- a/src/PhpSpreadsheet/Reader/Excel2007.php +++ b/src/PhpSpreadsheet/Reader/Excel2007.php @@ -53,14 +53,14 @@ class Excel2007 extends BaseReader implements IReader * Can the current IReader read the file? * * @param string $pFilename - * @return boolean * @throws Exception + * @return bool */ public function canRead($pFilename) { // Check if file exists 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(); @@ -72,21 +72,21 @@ class Excel2007 extends BaseReader implements IReader $xl = false; // Load file - $zip = new $zipClass; + $zip = new $zipClass(); if ($zip->open($pFilename) === true) { // check if it is an OOXML archive $rels = simplexml_load_string( $this->securityScan( - $this->getFromZipArchive($zip, "_rels/.rels") + $this->getFromZipArchive($zip, '_rels/.rels') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); if ($rels !== false) { foreach ($rels->Relationship as $rel) { - switch ($rel["Type"]) { - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": - if (basename($rel["Target"]) == 'workbook.xml') { + switch ($rel['Type']) { + case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': + if (basename($rel['Target']) == 'workbook.xml') { $xl = true; } break; @@ -99,7 +99,6 @@ class Excel2007 extends BaseReader implements IReader return $xl; } - /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object * @@ -110,27 +109,27 @@ class Excel2007 extends BaseReader implements IReader { // Check if file exists 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.'); } - $worksheetNames = array(); + $worksheetNames = []; $zipClass = \PhpSpreadsheet\Settings::getZipClass(); - $zip = new $zipClass; + $zip = new $zipClass(); $zip->open($pFilename); // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader $rels = simplexml_load_string( $this->securityScan( - $this->getFromZipArchive($zip, "_rels/.rels"), + $this->getFromZipArchive($zip, '_rels/.rels'), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ) ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); foreach ($rels->Relationship as $rel) { - switch ($rel["Type"]) { - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + switch ($rel['Type']) { + case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': $xmlWorkbook = simplexml_load_string( $this->securityScan( $this->getFromZipArchive($zip, "{$rel['Target']}"), @@ -142,7 +141,7 @@ class Excel2007 extends BaseReader implements IReader if ($xmlWorkbook->sheets) { foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { // Check if sheet should be skipped - $worksheetNames[] = (string) $eleSheet["name"]; + $worksheetNames[] = (string) $eleSheet['name']; } } } @@ -153,7 +152,6 @@ class Excel2007 extends BaseReader implements IReader return $worksheetNames; } - /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) * @@ -164,39 +162,39 @@ class Excel2007 extends BaseReader implements IReader { // Check if file exists 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(); - $zip = new $zipClass; + $zip = new $zipClass(); $zip->open($pFilename); $rels = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" - $this->securityScan($this->getFromZipArchive($zip, "_rels/.rels")), + $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); foreach ($rels->Relationship as $rel) { - if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") { - $dir = dirname($rel["Target"]); + if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') { + $dir = dirname($rel['Target']); $relsWorkbook = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" $this->securityScan( - $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels") + $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); - $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships'); - $worksheets = array(); + $worksheets = []; foreach ($relsWorkbook->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") { - $worksheets[(string) $ele["Id"]] = $ele["Target"]; + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') { + $worksheets[(string) $ele['Id']] = $ele['Target']; } } @@ -209,22 +207,22 @@ class Excel2007 extends BaseReader implements IReader \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); if ($xmlWorkbook->sheets) { - $dir = dirname($rel["Target"]); + $dir = dirname($rel['Target']); foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { - $tmpInfo = array( - 'worksheetName' => (string) $eleSheet["name"], + $tmpInfo = [ + 'worksheetName' => (string) $eleSheet['name'], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, - ); + ]; - $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')]; $xml = new \XMLReader(); $res = $xml->xml( $this->securityScanFile( - 'zip://'.\PhpSpreadsheet\Shared\File::realpath($pFilename).'#'."$dir/$fileWorksheet" + 'zip://' . \PhpSpreadsheet\Shared\File::realpath($pFilename) . '#' . "$dir/$fileWorksheet" ), null, \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() @@ -239,7 +237,7 @@ class Excel2007 extends BaseReader implements IReader $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; } elseif ($xml->name == 'c' && $xml->nodeType == \XMLReader::ELEMENT) { - $currCells++; + ++$currCells; } } $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); @@ -261,62 +259,63 @@ class Excel2007 extends BaseReader implements IReader private static function castToBoolean($c) { -// echo 'Initial Cast to Boolean', PHP_EOL; + // echo 'Initial Cast to Boolean', PHP_EOL; $value = isset($c->v) ? (string) $c->v : null; if ($value == '0') { return false; } elseif ($value == '1') { return true; } else { - return (bool)$c->v; + return (bool) $c->v; } + return $value; } private static function castToError($c) { -// echo 'Initial Cast to Error', PHP_EOL; + // echo 'Initial Cast to Error', PHP_EOL; return isset($c->v) ? (string) $c->v : null; } private static function castToString($c) { -// echo 'Initial Cast to String, PHP_EOL; + // echo 'Initial Cast to String, PHP_EOL; return isset($c->v) ? (string) $c->v : null; } private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType) { -// echo 'Formula', PHP_EOL; + // echo 'Formula', PHP_EOL; // echo '$c->f is ', $c->f, PHP_EOL; - $cellDataType = 'f'; - $value = "={$c->f}"; - $calculatedValue = self::$castBaseType($c); + $cellDataType = 'f'; + $value = "={$c->f}"; + $calculatedValue = self::$castBaseType($c); // Shared formula? - if (isset($c->f['t']) && strtolower((string)$c->f['t']) == 'shared') { -// echo 'SHARED FORMULA', PHP_EOL; - $instance = (string)$c->f['si']; + if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') { + // echo 'SHARED FORMULA', PHP_EOL; + $instance = (string) $c->f['si']; // echo 'Instance ID = ', $instance, PHP_EOL; // // echo 'Shared Formula Array:', PHP_EOL; // print_r($sharedFormulas); - if (!isset($sharedFormulas[(string)$c->f['si']])) { -// echo 'SETTING NEW SHARED FORMULA', PHP_EOL; + if (!isset($sharedFormulas[(string) $c->f['si']])) { + // echo 'SETTING NEW SHARED FORMULA', PHP_EOL; // echo 'Master is ', $r, PHP_EOL; // echo 'Formula is ', $value, PHP_EOL; - $sharedFormulas[$instance] = array('master' => $r, 'formula' => $value); + $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value]; // echo 'New Shared Formula Array:', PHP_EOL; // print_r($sharedFormulas); } else { -// echo 'GETTING SHARED FORMULA', PHP_EOL; + // echo 'GETTING SHARED FORMULA', PHP_EOL; // echo 'Master is ', $sharedFormulas[$instance]['master'], PHP_EOL; // echo 'Formula is ', $sharedFormulas[$instance]['formula'], PHP_EOL; $master = \PhpSpreadsheet\Cell::coordinateFromString($sharedFormulas[$instance]['master']); $current = \PhpSpreadsheet\Cell::coordinateFromString($r); - $difference = array(0, 0); + $difference = [0, 0]; $difference[0] = \PhpSpreadsheet\Cell::columnIndexFromString($current[0]) - \PhpSpreadsheet\Cell::columnIndexFromString($master[0]); $difference[1] = $current[1] - $master[1]; @@ -326,7 +325,6 @@ class Excel2007 extends BaseReader implements IReader } } - private function getFromZipArchive($archive, $fileName = '') { // Root-relative paths @@ -351,23 +349,22 @@ class Excel2007 extends BaseReader implements IReader return $contents; } - /** * Loads Spreadsheet from file * * @param string $pFilename - * @return Spreadsheet * @throws Exception + * @return Spreadsheet */ public function load($pFilename) { // Check if file exists 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.'); } // Initialisations - $excel = new \PhpSpreadsheet\Spreadsheet; + $excel = new \PhpSpreadsheet\Spreadsheet(); $excel->removeSheetByIndex(0); if (!$this->readDataOnly) { $excel->removeCellStyleXfByIndex(0); // remove the default style @@ -376,20 +373,20 @@ class Excel2007 extends BaseReader implements IReader $zipClass = \PhpSpreadsheet\Settings::getZipClass(); - $zip = new $zipClass; + $zip = new $zipClass(); $zip->open($pFilename); // Read the theme first, because we need the colour scheme when reading the styles $wbRels = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" - $this->securityScan($this->getFromZipArchive($zip, "xl/_rels/workbook.xml.rels")), + $this->securityScan($this->getFromZipArchive($zip, 'xl/_rels/workbook.xml.rels')), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); foreach ($wbRels->Relationship as $rel) { - switch ($rel["Type"]) { - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme": - $themeOrderArray = array('lt1', 'dk1', 'lt2', 'dk2'); + switch ($rel['Type']) { + case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme': + $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2']; $themeOrderAdditional = count($themeOrderArray); $xmlTheme = simplexml_load_string( @@ -399,14 +396,14 @@ class Excel2007 extends BaseReader implements IReader ); if (is_object($xmlTheme)) { $xmlThemeName = $xmlTheme->attributes(); - $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); - $themeName = (string)$xmlThemeName['name']; + $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main'); + $themeName = (string) $xmlThemeName['name']; $colourScheme = $xmlTheme->themeElements->clrScheme->attributes(); - $colourSchemeName = (string)$colourScheme['name']; - $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); + $colourSchemeName = (string) $colourScheme['name']; + $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main'); - $themeColours = array(); + $themeColours = []; foreach ($colourScheme as $k => $xmlColour) { $themePos = array_search($k, $themeOrderArray); if ($themePos === false) { @@ -428,35 +425,35 @@ class Excel2007 extends BaseReader implements IReader $rels = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" - $this->securityScan($this->getFromZipArchive($zip, "_rels/.rels")), + $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); foreach ($rels->Relationship as $rel) { - switch ($rel["Type"]) { - case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties": + switch ($rel['Type']) { + case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties': $xmlCore = simplexml_load_string( $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); if (is_object($xmlCore)) { - $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/"); - $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); - $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); + $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/'); + $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/'); + $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); $docProps = $excel->getProperties(); - $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath("dc:creator"))); - $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath("cp:lastModifiedBy"))); - $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath("dcterms:created")))); //! respect xsi:type - $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type - $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath("dc:title"))); - $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath("dc:description"))); - $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath("dc:subject"))); - $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath("cp:keywords"))); - $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath("cp:category"))); + $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator'))); + $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy'))); + $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type + $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type + $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title'))); + $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description'))); + $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject'))); + $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath('cp:keywords'))); + $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath('cp:category'))); } break; - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties": + case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties': $xmlCore = simplexml_load_string( $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', @@ -472,7 +469,7 @@ class Excel2007 extends BaseReader implements IReader } } break; - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties": + case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties': $xmlCore = simplexml_load_string( $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', @@ -495,23 +492,23 @@ class Excel2007 extends BaseReader implements IReader } break; //Ribbon - case "http://schemas.microsoft.com/office/2006/relationships/ui/extensibility": + case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility': $customUI = $rel['Target']; if (!is_null($customUI)) { $this->readRibbon($excel, $customUI, $zip); } break; - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": - $dir = dirname($rel["Target"]); + case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': + $dir = dirname($rel['Target']); $relsWorkbook = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" - $this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")), + $this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); - $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships'); - $sharedStrings = array(); + $sharedStrings = []; $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']")); $xmlStrings = simplexml_load_string( //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" @@ -529,16 +526,16 @@ class Excel2007 extends BaseReader implements IReader } } - $worksheets = array(); + $worksheets = []; $macros = $customUI = null; foreach ($relsWorkbook->Relationship as $ele) { switch ($ele['Type']) { - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet": - $worksheets[(string) $ele["Id"]] = $ele["Target"]; + case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet': + $worksheets[(string) $ele['Id']] = $ele['Target']; break; // a vbaProject ? (: some macros) - case "http://schemas.microsoft.com/office/2006/relationships/vbaProject": - $macros = $ele["Target"]; + case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject': + $macros = $ele['Target']; break; } } @@ -555,8 +552,8 @@ class Excel2007 extends BaseReader implements IReader } } } - $styles = array(); - $cellStyles = array(); + $styles = []; + $cellStyles = []; $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); $xmlStyles = simplexml_load_string( //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" @@ -569,81 +566,81 @@ class Excel2007 extends BaseReader implements IReader $numFmts = $xmlStyles->numFmts[0]; } if (isset($numFmts) && ($numFmts !== null)) { - $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); } if (!$this->readDataOnly && $xmlStyles) { foreach ($xmlStyles->cellXfs->xf as $xf) { $numFmt = \PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL; - if ($xf["numFmtId"]) { + if ($xf['numFmtId']) { if (isset($numFmts)) { $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); - if (isset($tmpNumFmt["formatCode"])) { - $numFmt = (string) $tmpNumFmt["formatCode"]; + if (isset($tmpNumFmt['formatCode'])) { + $numFmt = (string) $tmpNumFmt['formatCode']; } } // We shouldn't override any of the built-in MS Excel values (values below id 164) // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used // So we make allowance for them rather than lose formatting masks - if ((int)$xf["numFmtId"] < 164 && - \PhpSpreadsheet\Style\NumberFormat::builtInFormatCode((int)$xf["numFmtId"]) !== '') { - $numFmt = \PhpSpreadsheet\Style\NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + if ((int) $xf['numFmtId'] < 164 && + \PhpSpreadsheet\Style\NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '') { + $numFmt = \PhpSpreadsheet\Style\NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } $quotePrefix = false; - if (isset($xf["quotePrefix"])) { - $quotePrefix = (boolean) $xf["quotePrefix"]; + if (isset($xf['quotePrefix'])) { + $quotePrefix = (boolean) $xf['quotePrefix']; } - $style = (object) array( - "numFmt" => $numFmt, - "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], - "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], - "border" => $xmlStyles->borders->border[intval($xf["borderId"])], - "alignment" => $xf->alignment, - "protection" => $xf->protection, - "quotePrefix" => $quotePrefix, - ); + $style = (object) [ + 'numFmt' => $numFmt, + 'font' => $xmlStyles->fonts->font[intval($xf['fontId'])], + 'fill' => $xmlStyles->fills->fill[intval($xf['fillId'])], + 'border' => $xmlStyles->borders->border[intval($xf['borderId'])], + 'alignment' => $xf->alignment, + 'protection' => $xf->protection, + 'quotePrefix' => $quotePrefix, + ]; $styles[] = $style; // add style to cellXf collection - $objStyle = new \PhpSpreadsheet\Style; + $objStyle = new \PhpSpreadsheet\Style(); self::readStyle($objStyle, $style); $excel->addCellXf($objStyle); } foreach ($xmlStyles->cellStyleXfs->xf as $xf) { $numFmt = \PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL; - if ($numFmts && $xf["numFmtId"]) { + if ($numFmts && $xf['numFmtId']) { $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); - if (isset($tmpNumFmt["formatCode"])) { - $numFmt = (string) $tmpNumFmt["formatCode"]; - } elseif ((int)$xf["numFmtId"] < 165) { - $numFmt = \PhpSpreadsheet\Style\NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + if (isset($tmpNumFmt['formatCode'])) { + $numFmt = (string) $tmpNumFmt['formatCode']; + } elseif ((int) $xf['numFmtId'] < 165) { + $numFmt = \PhpSpreadsheet\Style\NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } - $cellStyle = (object) array( - "numFmt" => $numFmt, - "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], - "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], - "border" => $xmlStyles->borders->border[intval($xf["borderId"])], - "alignment" => $xf->alignment, - "protection" => $xf->protection, - "quotePrefix" => $quotePrefix, - ); + $cellStyle = (object) [ + 'numFmt' => $numFmt, + 'font' => $xmlStyles->fonts->font[intval($xf['fontId'])], + 'fill' => $xmlStyles->fills->fill[intval($xf['fillId'])], + 'border' => $xmlStyles->borders->border[intval($xf['borderId'])], + 'alignment' => $xf->alignment, + 'protection' => $xf->protection, + 'quotePrefix' => $quotePrefix, + ]; $cellStyles[] = $cellStyle; // add style to cellStyleXf collection - $objStyle = new \PhpSpreadsheet\Style; + $objStyle = new \PhpSpreadsheet\Style(); self::readStyle($objStyle, $cellStyle); $excel->addCellStyleXf($objStyle); } } - $dxfs = array(); + $dxfs = []; if (!$this->readDataOnly && $xmlStyles) { // Conditional Styles if ($xmlStyles->dxfs) { @@ -659,7 +656,7 @@ class Excel2007 extends BaseReader implements IReader if (intval($cellStyle['builtinId']) == 0) { if (isset($cellStyles[intval($cellStyle['xfId'])])) { // Set default style - $style = new \PhpSpreadsheet\Style; + $style = new \PhpSpreadsheet\Style(); self::readStyle($style, $cellStyles[intval($cellStyle['xfId'])]); // normal style, currently not using it for anything @@ -689,16 +686,16 @@ class Excel2007 extends BaseReader implements IReader $sheetId = 0; // keep track of new sheet id in final workbook $oldSheetId = -1; // keep track of old sheet id in final workbook $countSkippedSheets = 0; // keep track of number of skipped sheets - $mapSheetId = array(); // mapping of sheet ids from old to new + $mapSheetId = []; // mapping of sheet ids from old to new - $charts = $chartDetails = array(); + $charts = $chartDetails = []; if ($xmlWorkbook->sheets) { foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { ++$oldSheetId; // Check if sheet should be skipped - if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->loadSheetsOnly)) { + if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; continue; @@ -714,8 +711,8 @@ class Excel2007 extends BaseReader implements IReader // references in formula cells... during the load, all formulae should be correct, // and we're simply bringing the worksheet name in line with the formula, not the // reverse - $docSheet->setTitle((string) $eleSheet["name"], false); - $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $docSheet->setTitle((string) $eleSheet['name'], false); + $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')]; $xmlSheet = simplexml_load_string( //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" $this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")), @@ -723,10 +720,10 @@ class Excel2007 extends BaseReader implements IReader \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); - $sharedFormulas = array(); + $sharedFormulas = []; - if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') { - $docSheet->setSheetState((string) $eleSheet["state"]); + if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') { + $docSheet->setSheetState((string) $eleSheet['state']); } if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) { @@ -740,17 +737,17 @@ class Excel2007 extends BaseReader implements IReader $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']); } if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) { - $docSheet->setShowGridLines(self::boolean((string)$xmlSheet->sheetViews->sheetView['showGridLines'])); + $docSheet->setShowGridLines(self::boolean((string) $xmlSheet->sheetViews->sheetView['showGridLines'])); } if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) { - $docSheet->setShowRowColHeaders(self::boolean((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'])); + $docSheet->setShowRowColHeaders(self::boolean((string) $xmlSheet->sheetViews->sheetView['showRowColHeaders'])); } if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) { - $docSheet->setRightToLeft(self::boolean((string)$xmlSheet->sheetViews->sheetView['rightToLeft'])); + $docSheet->setRightToLeft(self::boolean((string) $xmlSheet->sheetViews->sheetView['rightToLeft'])); } if (isset($xmlSheet->sheetViews->sheetView->pane)) { if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) { - $docSheet->freezePane((string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell']); + $docSheet->freezePane((string) $xmlSheet->sheetViews->sheetView->pane['topLeftCell']); } else { $xSplit = 0; $ySplit = 0; @@ -769,7 +766,7 @@ class Excel2007 extends BaseReader implements IReader if (isset($xmlSheet->sheetViews->sheetView->selection)) { if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) { - $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref']; + $sqref = (string) $xmlSheet->sheetViews->sheetView->selection['sqref']; $sqref = explode(' ', $sqref); $sqref = $sqref[0]; $docSheet->setSelectedCells($sqref); @@ -779,7 +776,7 @@ class Excel2007 extends BaseReader implements IReader if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) { if (isset($xmlSheet->sheetPr->tabColor['rgb'])) { - $docSheet->getTabColor()->setARGB((string)$xmlSheet->sheetPr->tabColor['rgb']); + $docSheet->getTabColor()->setARGB((string) $xmlSheet->sheetPr->tabColor['rgb']); } } if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr['codeName'])) { @@ -814,39 +811,39 @@ class Excel2007 extends BaseReader implements IReader if (isset($xmlSheet->sheetFormatPr['customHeight']) && self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) && isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) { - $docSheet->getDefaultRowDimension()->setRowHeight((float)$xmlSheet->sheetFormatPr['defaultRowHeight']); + $docSheet->getDefaultRowDimension()->setRowHeight((float) $xmlSheet->sheetFormatPr['defaultRowHeight']); } if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) { - $docSheet->getDefaultColumnDimension()->setWidth((float)$xmlSheet->sheetFormatPr['defaultColWidth']); + $docSheet->getDefaultColumnDimension()->setWidth((float) $xmlSheet->sheetFormatPr['defaultColWidth']); } if (isset($xmlSheet->sheetFormatPr['zeroHeight']) && - ((string)$xmlSheet->sheetFormatPr['zeroHeight'] == '1')) { + ((string) $xmlSheet->sheetFormatPr['zeroHeight'] == '1')) { $docSheet->getDefaultRowDimension()->setZeroHeight(true); } } if (isset($xmlSheet->cols) && !$this->readDataOnly) { foreach ($xmlSheet->cols->col as $col) { - for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) { - if ($col["style"] && !$this->readDataOnly) { - $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"])); + for ($i = intval($col['min']) - 1; $i < intval($col['max']); ++$i) { + if ($col['style'] && !$this->readDataOnly) { + $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setXfIndex(intval($col['style'])); } - if (self::boolean($col["bestFit"])) { + if (self::boolean($col['bestFit'])) { //$docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setAutoSize(true); } - if (self::boolean($col["hidden"])) { + if (self::boolean($col['hidden'])) { // echo \PhpSpreadsheet\Cell::stringFromColumnIndex($i), ': HIDDEN COLUMN',PHP_EOL; $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setVisible(false); } - if (self::boolean($col["collapsed"])) { + if (self::boolean($col['collapsed'])) { $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setCollapsed(true); } - if ($col["outlineLevel"] > 0) { - $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"])); + if ($col['outlineLevel'] > 0) { + $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col['outlineLevel'])); } - $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"])); + $docSheet->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($i))->setWidth(floatval($col['width'])); - if (intval($col["max"]) == 16384) { + if (intval($col['max']) == 16384) { break; } } @@ -870,27 +867,27 @@ class Excel2007 extends BaseReader implements IReader if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) { foreach ($xmlSheet->sheetData->row as $row) { - if ($row["ht"] && !$this->readDataOnly) { - $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"])); + if ($row['ht'] && !$this->readDataOnly) { + $docSheet->getRowDimension(intval($row['r']))->setRowHeight(floatval($row['ht'])); } - if (self::boolean($row["hidden"]) && !$this->readDataOnly) { - $docSheet->getRowDimension(intval($row["r"]))->setVisible(false); + if (self::boolean($row['hidden']) && !$this->readDataOnly) { + $docSheet->getRowDimension(intval($row['r']))->setVisible(false); } - if (self::boolean($row["collapsed"])) { - $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(true); + if (self::boolean($row['collapsed'])) { + $docSheet->getRowDimension(intval($row['r']))->setCollapsed(true); } - if ($row["outlineLevel"] > 0) { - $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"])); + if ($row['outlineLevel'] > 0) { + $docSheet->getRowDimension(intval($row['r']))->setOutlineLevel(intval($row['outlineLevel'])); } - if ($row["s"] && !$this->readDataOnly) { - $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"])); + if ($row['s'] && !$this->readDataOnly) { + $docSheet->getRowDimension(intval($row['r']))->setXfIndex(intval($row['s'])); } foreach ($row->c as $c) { - $r = (string) $c["r"]; - $cellDataType = (string) $c["t"]; - $value = null; - $calculatedValue = null; + $r = (string) $c['r']; + $cellDataType = (string) $c['t']; + $value = null; + $calculatedValue = null; // Read cell? if ($this->getReadFilter() !== null) { @@ -908,9 +905,9 @@ class Excel2007 extends BaseReader implements IReader // // Read cell! switch ($cellDataType) { - case "s": + case 's': // echo 'String', PHP_EOL; - if ((string)$c->v != '') { + if ((string) $c->v != '') { $value = $sharedStrings[intval($c->v)]; if ($value instanceof \PhpSpreadsheet\RichText) { @@ -920,7 +917,7 @@ class Excel2007 extends BaseReader implements IReader $value = ''; } break; - case "b": + case 'b': // echo 'Boolean', PHP_EOL; if (!isset($c->f)) { $value = self::castToBoolean($c); @@ -928,14 +925,14 @@ class Excel2007 extends BaseReader implements IReader // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean'); if (isset($c->f['t'])) { - $att = array(); + $att = []; $att = $c->f; $docSheet->getCell($r)->setFormulaAttributes($att); } // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; } break; - case "inlineStr": + case 'inlineStr': // echo 'Inline String', PHP_EOL; if (isset($c->f)) { $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError'); @@ -943,7 +940,7 @@ class Excel2007 extends BaseReader implements IReader $value = $this->parseRichText($c->is); } break; - case "e": + case 'e': // echo 'Error', PHP_EOL; if (!isset($c->f)) { $value = self::castToError($c); @@ -956,10 +953,10 @@ class Excel2007 extends BaseReader implements IReader default: // echo 'Default', PHP_EOL; if (!isset($c->f)) { - // echo 'Not a Formula', PHP_EOL; + // echo 'Not a Formula', PHP_EOL; $value = self::castToString($c); } else { - // echo 'Treat as Formula', PHP_EOL; + // echo 'Treat as Formula', PHP_EOL; // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString'); // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; @@ -970,12 +967,12 @@ class Excel2007 extends BaseReader implements IReader // Check for numeric values if (is_numeric($value) && $cellDataType != 's') { - if ($value == (int)$value) { - $value = (int)$value; - } elseif ($value == (float)$value) { - $value = (float)$value; - } elseif ($value == (double)$value) { - $value = (double)$value; + if ($value == (int) $value) { + $value = (int) $value; + } elseif ($value == (float) $value) { + $value = (float) $value; + } elseif ($value == (double) $value) { + $value = (double) $value; } } @@ -996,45 +993,45 @@ class Excel2007 extends BaseReader implements IReader } // Style information? - if ($c["s"] && !$this->readDataOnly) { + if ($c['s'] && !$this->readDataOnly) { // no style index means 0, it seems - $cell->setXfIndex(isset($styles[intval($c["s"])]) ? - intval($c["s"]) : 0); + $cell->setXfIndex(isset($styles[intval($c['s'])]) ? + intval($c['s']) : 0); } } } } - $conditionals = array(); + $conditionals = []; if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) { foreach ($xmlSheet->conditionalFormatting as $conditional) { foreach ($conditional->cfRule as $cfRule) { - if (((string)$cfRule["type"] == \PhpSpreadsheet\Style\Conditional::CONDITION_NONE || (string)$cfRule["type"] == \PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS || (string)$cfRule["type"] == \PhpSpreadsheet\Style\Conditional::CONDITION_CONTAINSTEXT || (string)$cfRule["type"] == \PhpSpreadsheet\Style\Conditional::CONDITION_EXPRESSION) && isset($dxfs[intval($cfRule["dxfId"])])) { - $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule; + if (((string) $cfRule['type'] == \PhpSpreadsheet\Style\Conditional::CONDITION_NONE || (string) $cfRule['type'] == \PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS || (string) $cfRule['type'] == \PhpSpreadsheet\Style\Conditional::CONDITION_CONTAINSTEXT || (string) $cfRule['type'] == \PhpSpreadsheet\Style\Conditional::CONDITION_EXPRESSION) && isset($dxfs[intval($cfRule['dxfId'])])) { + $conditionals[(string) $conditional['sqref']][intval($cfRule['priority'])] = $cfRule; } } } foreach ($conditionals as $ref => $cfRules) { ksort($cfRules); - $conditionalStyles = array(); + $conditionalStyles = []; foreach ($cfRules as $cfRule) { $objConditional = new \PhpSpreadsheet\Style\Conditional(); - $objConditional->setConditionType((string)$cfRule["type"]); - $objConditional->setOperatorType((string)$cfRule["operator"]); + $objConditional->setConditionType((string) $cfRule['type']); + $objConditional->setOperatorType((string) $cfRule['operator']); - if ((string)$cfRule["text"] != '') { - $objConditional->setText((string)$cfRule["text"]); + if ((string) $cfRule['text'] != '') { + $objConditional->setText((string) $cfRule['text']); } if (count($cfRule->formula) > 1) { foreach ($cfRule->formula as $formula) { - $objConditional->addCondition((string)$formula); + $objConditional->addCondition((string) $formula); } } else { - $objConditional->addCondition((string)$cfRule->formula); + $objConditional->addCondition((string) $cfRule->formula); } - $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]); + $objConditional->setStyle(clone $dxfs[intval($cfRule['dxfId'])]); $conditionalStyles[] = $objConditional; } @@ -1046,36 +1043,36 @@ class Excel2007 extends BaseReader implements IReader } } - $aKeys = ["sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells"]; + $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells']; if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { foreach ($aKeys as $key) { - $method = "set" . ucfirst($key); + $method = 'set' . ucfirst($key); $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key])); } } if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { - $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], true); + $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true); if ($xmlSheet->protectedRanges->protectedRange) { foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { - $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true); + $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true); } } } if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) { - $autoFilterRange = (string) $xmlSheet->autoFilter["ref"]; + $autoFilterRange = (string) $xmlSheet->autoFilter['ref']; if (strpos($autoFilterRange, ':') !== false) { $autoFilter = $docSheet->getAutoFilter(); $autoFilter->setRange($autoFilterRange); foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) { - $column = $autoFilter->getColumnByOffset((integer) $filterColumn["colId"]); + $column = $autoFilter->getColumnByOffset((integer) $filterColumn['colId']); // Check for standard filters if ($filterColumn->filters) { $column->setFilterType(\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER); $filters = $filterColumn->filters; - if ((isset($filters["blank"])) && ($filters["blank"] == 1)) { + if ((isset($filters['blank'])) && ($filters['blank'] == 1)) { // Operator is undefined, but always treated as EQUAL $column->createRule()->setRule(null, '')->setRuleType(\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_FILTER); } @@ -1083,22 +1080,22 @@ class Excel2007 extends BaseReader implements IReader // Entries can be either filter elements foreach ($filters->filter as $filterRule) { // Operator is undefined, but always treated as EQUAL - $column->createRule()->setRule(null, (string) $filterRule["val"])->setRuleType(\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_FILTER); + $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_FILTER); } // Or Date Group elements foreach ($filters->dateGroupItem as $dateGroupItem) { $column->createRule()->setRule( // Operator is undefined, but always treated as EQUAL null, - array( - 'year' => (string) $dateGroupItem["year"], - 'month' => (string) $dateGroupItem["month"], - 'day' => (string) $dateGroupItem["day"], - 'hour' => (string) $dateGroupItem["hour"], - 'minute' => (string) $dateGroupItem["minute"], - 'second' => (string) $dateGroupItem["second"], - ), - (string) $dateGroupItem["dateTimeGrouping"] + [ + 'year' => (string) $dateGroupItem['year'], + 'month' => (string) $dateGroupItem['month'], + 'day' => (string) $dateGroupItem['day'], + 'hour' => (string) $dateGroupItem['hour'], + 'minute' => (string) $dateGroupItem['minute'], + 'second' => (string) $dateGroupItem['second'], + ], + (string) $dateGroupItem['dateTimeGrouping'] ) ->setRuleType(\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP); } @@ -1109,13 +1106,13 @@ class Excel2007 extends BaseReader implements IReader $customFilters = $filterColumn->customFilters; // Custom filters can an AND or an OR join; // and there should only ever be one or two entries - if ((isset($customFilters["and"])) && ($customFilters["and"] == 1)) { + if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) { $column->setJoin(\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND); } foreach ($customFilters->customFilter as $filterRule) { $column->createRule()->setRule( - (string) $filterRule["operator"], - (string) $filterRule["val"] + (string) $filterRule['operator'], + (string) $filterRule['val'] ) ->setRuleType(\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); } @@ -1128,15 +1125,15 @@ class Excel2007 extends BaseReader implements IReader $column->createRule()->setRule( // Operator is undefined, but always treated as EQUAL null, - (string) $filterRule["val"], - (string) $filterRule["type"] + (string) $filterRule['val'], + (string) $filterRule['type'] ) ->setRuleType(\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); - if (isset($filterRule["val"])) { - $column->setAttribute('val', (string) $filterRule["val"]); + if (isset($filterRule['val'])) { + $column->setAttribute('val', (string) $filterRule['val']); } - if (isset($filterRule["maxVal"])) { - $column->setAttribute('maxVal', (string) $filterRule["maxVal"]); + if (isset($filterRule['maxVal'])) { + $column->setAttribute('maxVal', (string) $filterRule['maxVal']); } } } @@ -1146,12 +1143,12 @@ class Excel2007 extends BaseReader implements IReader // We should only ever have one top10 filter foreach ($filterColumn->top10 as $filterRule) { $column->createRule()->setRule( - (((isset($filterRule["percent"])) && ($filterRule["percent"] == 1)) + (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1)) ? \PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT : \PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE ), - (string) $filterRule["val"], - (((isset($filterRule["top"])) && ($filterRule["top"] == 1)) + (string) $filterRule['val'], + (((isset($filterRule['top'])) && ($filterRule['top'] == 1)) ? \PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP : \PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM ) @@ -1165,70 +1162,70 @@ class Excel2007 extends BaseReader implements IReader if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) { foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) { - $mergeRef = (string) $mergeCell["ref"]; + $mergeRef = (string) $mergeCell['ref']; if (strpos($mergeRef, ':') !== false) { - $docSheet->mergeCells((string) $mergeCell["ref"]); + $docSheet->mergeCells((string) $mergeCell['ref']); } } } if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) { $docPageMargins = $docSheet->getPageMargins(); - $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"])); - $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"])); - $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"])); - $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"])); - $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"])); - $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"])); + $docPageMargins->setLeft(floatval($xmlSheet->pageMargins['left'])); + $docPageMargins->setRight(floatval($xmlSheet->pageMargins['right'])); + $docPageMargins->setTop(floatval($xmlSheet->pageMargins['top'])); + $docPageMargins->setBottom(floatval($xmlSheet->pageMargins['bottom'])); + $docPageMargins->setHeader(floatval($xmlSheet->pageMargins['header'])); + $docPageMargins->setFooter(floatval($xmlSheet->pageMargins['footer'])); } if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) { $docPageSetup = $docSheet->getPageSetup(); - if (isset($xmlSheet->pageSetup["orientation"])) { - $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]); + if (isset($xmlSheet->pageSetup['orientation'])) { + $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']); } - if (isset($xmlSheet->pageSetup["paperSize"])) { - $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"])); + if (isset($xmlSheet->pageSetup['paperSize'])) { + $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup['paperSize'])); } - if (isset($xmlSheet->pageSetup["scale"])) { - $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), false); + if (isset($xmlSheet->pageSetup['scale'])) { + $docPageSetup->setScale(intval($xmlSheet->pageSetup['scale']), false); } - if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) { - $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), false); + if (isset($xmlSheet->pageSetup['fitToHeight']) && intval($xmlSheet->pageSetup['fitToHeight']) >= 0) { + $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup['fitToHeight']), false); } - if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) { - $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), false); + if (isset($xmlSheet->pageSetup['fitToWidth']) && intval($xmlSheet->pageSetup['fitToWidth']) >= 0) { + $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup['fitToWidth']), false); } - if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) && - self::boolean((string) $xmlSheet->pageSetup["useFirstPageNumber"])) { - $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"])); + if (isset($xmlSheet->pageSetup['firstPageNumber']) && isset($xmlSheet->pageSetup['useFirstPageNumber']) && + self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) { + $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup['firstPageNumber'])); } } if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) { $docHeaderFooter = $docSheet->getHeaderFooter(); - if (isset($xmlSheet->headerFooter["differentOddEven"]) && - self::boolean((string)$xmlSheet->headerFooter["differentOddEven"])) { + if (isset($xmlSheet->headerFooter['differentOddEven']) && + self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) { $docHeaderFooter->setDifferentOddEven(true); } else { $docHeaderFooter->setDifferentOddEven(false); } - if (isset($xmlSheet->headerFooter["differentFirst"]) && - self::boolean((string)$xmlSheet->headerFooter["differentFirst"])) { + if (isset($xmlSheet->headerFooter['differentFirst']) && + self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) { $docHeaderFooter->setDifferentFirst(true); } else { $docHeaderFooter->setDifferentFirst(false); } - if (isset($xmlSheet->headerFooter["scaleWithDoc"]) && - !self::boolean((string)$xmlSheet->headerFooter["scaleWithDoc"])) { + if (isset($xmlSheet->headerFooter['scaleWithDoc']) && + !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) { $docHeaderFooter->setScaleWithDocument(false); } else { $docHeaderFooter->setScaleWithDocument(true); } - if (isset($xmlSheet->headerFooter["alignWithMargins"]) && - !self::boolean((string)$xmlSheet->headerFooter["alignWithMargins"])) { + if (isset($xmlSheet->headerFooter['alignWithMargins']) && + !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) { $docHeaderFooter->setAlignWithMargins(false); } else { $docHeaderFooter->setAlignWithMargins(true); @@ -1244,15 +1241,15 @@ class Excel2007 extends BaseReader implements IReader if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) { foreach ($xmlSheet->rowBreaks->brk as $brk) { - if ($brk["man"]) { + if ($brk['man']) { $docSheet->setBreak("A$brk[id]", \PhpSpreadsheet\Worksheet::BREAK_ROW); } } } if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) { foreach ($xmlSheet->colBreaks->brk as $brk) { - if ($brk["man"]) { - $docSheet->setBreak(\PhpSpreadsheet\Cell::stringFromColumnIndex((string) $brk["id"]) . "1", \PhpSpreadsheet\Worksheet::BREAK_COLUMN); + if ($brk['man']) { + $docSheet->setBreak(\PhpSpreadsheet\Cell::stringFromColumnIndex((string) $brk['id']) . '1', \PhpSpreadsheet\Worksheet::BREAK_COLUMN); } } } @@ -1260,7 +1257,7 @@ class Excel2007 extends BaseReader implements IReader if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) { foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) { // Uppercase coordinate - $range = strtoupper($dataValidation["sqref"]); + $range = strtoupper($dataValidation['sqref']); $rangeSet = explode(' ', $range); foreach ($rangeSet as $range) { $stRange = $docSheet->shrinkRangeToFit($range); @@ -1269,17 +1266,17 @@ class Excel2007 extends BaseReader implements IReader foreach (\PhpSpreadsheet\Cell::extractAllCellReferencesInRange($stRange) as $reference) { // Create validation $docValidation = $docSheet->getCell($reference)->getDataValidation(); - $docValidation->setType((string) $dataValidation["type"]); - $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]); - $docValidation->setOperator((string) $dataValidation["operator"]); - $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0); - $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0); - $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0); - $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0); - $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]); - $docValidation->setError((string) $dataValidation["error"]); - $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]); - $docValidation->setPrompt((string) $dataValidation["prompt"]); + $docValidation->setType((string) $dataValidation['type']); + $docValidation->setErrorStyle((string) $dataValidation['errorStyle']); + $docValidation->setOperator((string) $dataValidation['operator']); + $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0); + $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0); + $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0); + $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0); + $docValidation->setErrorTitle((string) $dataValidation['errorTitle']); + $docValidation->setError((string) $dataValidation['error']); + $docValidation->setPromptTitle((string) $dataValidation['promptTitle']); + $docValidation->setPrompt((string) $dataValidation['prompt']); $docValidation->setFormula1((string) $dataValidation->formula1); $docValidation->setFormula2((string) $dataValidation->formula2); } @@ -1288,21 +1285,21 @@ class Excel2007 extends BaseReader implements IReader } // Add hyperlinks - $hyperlinks = array(); + $hyperlinks = []; if (!$this->readDataOnly) { // Locate hyperlink relations - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { $relsWorksheet = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" $this->securityScan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") + $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") { - $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"]; + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') { + $hyperlinks[(string) $ele['Id']] = (string) $ele['Target']; } } } @@ -1316,18 +1313,18 @@ class Excel2007 extends BaseReader implements IReader foreach (\PhpSpreadsheet\Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) { $cell = $docSheet->getCell($cellReference); if (isset($linkRel['id'])) { - $hyperlinkUrl = $hyperlinks[ (string)$linkRel['id'] ]; + $hyperlinkUrl = $hyperlinks[ (string) $linkRel['id'] ]; if (isset($hyperlink['location'])) { $hyperlinkUrl .= '#' . (string) $hyperlink['location']; } $cell->getHyperlink()->setUrl($hyperlinkUrl); } elseif (isset($hyperlink['location'])) { - $cell->getHyperlink()->setUrl('sheet://' . (string)$hyperlink['location']); + $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']); } // Tooltip if (isset($hyperlink['tooltip'])) { - $cell->getHyperlink()->setTooltip((string)$hyperlink['tooltip']); + $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']); } } } @@ -1335,25 +1332,25 @@ class Excel2007 extends BaseReader implements IReader } // Add comments - $comments = array(); - $vmlComments = array(); + $comments = []; + $vmlComments = []; if (!$this->readDataOnly) { // Locate comment relations - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { $relsWorksheet = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" $this->securityScan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") + $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") { - $comments[(string)$ele["Id"]] = (string)$ele["Target"]; + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') { + $comments[(string) $ele['Id']] = (string) $ele['Target']; } - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { - $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"]; + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') { + $vmlComments[(string) $ele['Id']] = (string) $ele['Target']; } } } @@ -1361,7 +1358,7 @@ class Excel2007 extends BaseReader implements IReader // Loop through comments foreach ($comments as $relName => $relPath) { // Load comments file - $relPath = \PhpSpreadsheet\Shared\File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $relPath = \PhpSpreadsheet\Shared\File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); $commentsFile = simplexml_load_string( $this->securityScan($this->getFromZipArchive($zip, $relPath)), 'SimpleXMLElement', @@ -1369,26 +1366,26 @@ class Excel2007 extends BaseReader implements IReader ); // Utility variables - $authors = array(); + $authors = []; // Loop through authors foreach ($commentsFile->authors->author as $author) { - $authors[] = (string)$author; + $authors[] = (string) $author; } // Loop through contents foreach ($commentsFile->commentList->comment as $comment) { if (!empty($comment['authorId'])) { - $docSheet->getComment((string)$comment['ref'])->setAuthor($authors[(string)$comment['authorId']]); + $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]); } - $docSheet->getComment((string)$comment['ref'])->setText($this->parseRichText($comment->text)); + $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text)); } } // Loop through VML comments foreach ($vmlComments as $relName => $relPath) { // Load VML comments file - $relPath = \PhpSpreadsheet\Shared\File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $relPath = \PhpSpreadsheet\Shared\File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); $vmlCommentsFile = simplexml_load_string( $this->securityScan($this->getFromZipArchive($zip, $relPath)), 'SimpleXMLElement', @@ -1401,16 +1398,16 @@ class Excel2007 extends BaseReader implements IReader $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); if (isset($shape['style'])) { - $style = (string)$shape['style']; - $fillColor = strtoupper(substr((string)$shape['fillcolor'], 1)); - $column = null; - $row = null; + $style = (string) $shape['style']; + $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1)); + $column = null; + $row = null; - $clientData = $shape->xpath('.//x:ClientData'); + $clientData = $shape->xpath('.//x:ClientData'); if (is_array($clientData) && !empty($clientData)) { - $clientData = $clientData[0]; + $clientData = $clientData[0]; - if (isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note') { + if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') { $temp = $clientData->xpath('.//x:Row'); if (is_array($temp)) { $row = $temp[0]; @@ -1456,11 +1453,11 @@ class Excel2007 extends BaseReader implements IReader // Header/footer images if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) { - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { $relsWorksheet = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" $this->securityScan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") + $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() @@ -1468,8 +1465,8 @@ class Excel2007 extends BaseReader implements IReader $vmlRelationship = ''; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { - $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele["Target"]); + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') { + $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } @@ -1483,10 +1480,10 @@ class Excel2007 extends BaseReader implements IReader 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); - $drawings = array(); + $drawings = []; foreach ($relsVML->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { - $drawings[(string) $ele["Id"]] = self::dirAdd($vmlRelationship, $ele["Target"]); + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']); } } @@ -1498,7 +1495,7 @@ class Excel2007 extends BaseReader implements IReader ); $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); - $hfImages = array(); + $hfImages = []; $shapes = $vmlDrawing->xpath('//v:shape'); foreach ($shapes as $idx => $shape) { @@ -1507,14 +1504,14 @@ class Excel2007 extends BaseReader implements IReader $imageData = $imageData[$idx]; $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office'); - $style = self::toCSSArray((string)$shape['style']); + $style = self::toCSSArray((string) $shape['style']); $hfImages[(string) $shape['id']] = new \PhpSpreadsheet\Worksheet\HeaderFooterDrawing(); if (isset($imageData['title'])) { - $hfImages[(string) $shape['id']]->setName((string)$imageData['title']); + $hfImages[(string) $shape['id']]->setName((string) $imageData['title']); } - $hfImages[(string) $shape['id']]->setPath("zip://".\PhpSpreadsheet\Shared_File::realpath($pFilename)."#" . $drawings[(string)$imageData['relid']], false); + $hfImages[(string) $shape['id']]->setPath('zip://' . \PhpSpreadsheet\Shared_File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false); $hfImages[(string) $shape['id']]->setResizeProportional(false); $hfImages[(string) $shape['id']]->setWidth($style['width']); $hfImages[(string) $shape['id']]->setHeight($style['height']); @@ -1532,44 +1529,44 @@ class Excel2007 extends BaseReader implements IReader } // TODO: Autoshapes from twoCellAnchors! - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { $relsWorksheet = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" $this->securityScan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") + $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); - $drawings = array(); + $drawings = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") { - $drawings[(string) $ele["Id"]] = self::dirAdd("$dir/$fileWorksheet", $ele["Target"]); + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') { + $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } if ($xmlSheet->drawing && !$this->readDataOnly) { foreach ($xmlSheet->drawing as $drawing) { - $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')]; $relsDrawing = simplexml_load_string( //~ http://schemas.openxmlformats.org/package/2006/relationships" $this->securityScan( - $this->getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels") + $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); - $images = array(); + $images = []; if ($relsDrawing && $relsDrawing->Relationship) { foreach ($relsDrawing->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { - $images[(string) $ele["Id"]] = self::dirAdd($fileDrawing, $ele["Target"]); - } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") { + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']); + } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') { if ($this->includeCharts) { - $charts[self::dirAdd($fileDrawing, $ele["Target"])] = array( - 'id' => (string) $ele["Id"], - 'sheet' => $docSheet->getTitle() - ); + $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [ + 'id' => (string) $ele['Id'], + 'sheet' => $docSheet->getTitle(), + ]; } } } @@ -1578,22 +1575,22 @@ class Excel2007 extends BaseReader implements IReader $this->securityScan($this->getFromZipArchive($zip, $fileDrawing)), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() - )->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); + )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); if ($xmlDrawing->oneCellAnchor) { foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) { if ($oneCellAnchor->pic->blipFill) { - $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; - $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; - $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; - $objDrawing = new \PhpSpreadsheet\Worksheet\Drawing; - $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); - $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip; + $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm; + $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw; + $objDrawing = new \PhpSpreadsheet\Worksheet\Drawing(); + $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')); + $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr')); $objDrawing->setPath( - "zip://".\PhpSpreadsheet\Shared\File::realpath($pFilename)."#" . + 'zip://' . \PhpSpreadsheet\Shared\File::realpath($pFilename) . '#' . $images[(string) self::getArrayItem( - $blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), - "embed" + $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), + 'embed' )], false ); @@ -1601,46 +1598,46 @@ class Excel2007 extends BaseReader implements IReader $objDrawing->setOffsetX(\PhpSpreadsheet\Shared\Drawing::EMUToPixels($oneCellAnchor->from->colOff)); $objDrawing->setOffsetY(\PhpSpreadsheet\Shared\Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); $objDrawing->setResizeProportional(false); - $objDrawing->setWidth(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cx"))); - $objDrawing->setHeight(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cy"))); + $objDrawing->setWidth(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'))); + $objDrawing->setHeight(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'))); if ($xfrm) { - $objDrawing->setRotation(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), "rot"))); + $objDrawing->setRotation(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot'))); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); - $shadow->setBlurRadius(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "blurRad"))); - $shadow->setDistance(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "dist"))); - $shadow->setDirection(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), "dir"))); - $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), "algn")); - $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), "val")); - $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + $shadow->setBlurRadius(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'blurRad'))); + $shadow->setDistance(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist'))); + $shadow->setDirection(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir'))); + $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn')); + $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), 'val')); + $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), 'val') / 1000); } $objDrawing->setWorksheet($docSheet); } else { // ? Can charts be positioned with a oneCellAnchor ? $coordinates = \PhpSpreadsheet\Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1); - $offsetX = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($oneCellAnchor->from->colOff); - $offsetY = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($oneCellAnchor->from->rowOff); - $width = \PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cx")); - $height = \PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cy")); + $offsetX = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($oneCellAnchor->from->colOff); + $offsetY = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($oneCellAnchor->from->rowOff); + $width = \PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')); + $height = \PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')); } } } if ($xmlDrawing->twoCellAnchor) { foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) { if ($twoCellAnchor->pic->blipFill) { - $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; - $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; - $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; - $objDrawing = new \PhpSpreadsheet\Worksheet\Drawing; - $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); - $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip; + $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm; + $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw; + $objDrawing = new \PhpSpreadsheet\Worksheet\Drawing(); + $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')); + $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr')); $objDrawing->setPath( - "zip://".\PhpSpreadsheet\Shared\File::realpath($pFilename)."#" . + 'zip://' . \PhpSpreadsheet\Shared\File::realpath($pFilename) . '#' . $images[(string) self::getArrayItem( - $blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), - "embed" + $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), + 'embed' )], false ); @@ -1650,41 +1647,41 @@ class Excel2007 extends BaseReader implements IReader $objDrawing->setResizeProportional(false); if ($xfrm) { - $objDrawing->setWidth(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), "cx"))); - $objDrawing->setHeight(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), "cy"))); - $objDrawing->setRotation(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), "rot"))); + $objDrawing->setWidth(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx'))); + $objDrawing->setHeight(\PhpSpreadsheet\Shared\Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy'))); + $objDrawing->setRotation(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot'))); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); - $shadow->setBlurRadius(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "blurRad"))); - $shadow->setDistance(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "dist"))); - $shadow->setDirection(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), "dir"))); - $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), "algn")); - $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), "val")); - $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + $shadow->setBlurRadius(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'blurRad'))); + $shadow->setDistance(\PhpSpreadsheet\Shared\Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist'))); + $shadow->setDirection(\PhpSpreadsheet\Shared\Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir'))); + $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn')); + $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), 'val')); + $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), 'val') / 1000); } $objDrawing->setWorksheet($docSheet); } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) { $fromCoordinate = \PhpSpreadsheet\Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1); - $fromOffsetX = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->from->colOff); - $fromOffsetY = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->from->rowOff); - $toCoordinate = \PhpSpreadsheet\Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1); - $toOffsetX = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->to->colOff); - $toOffsetY = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->to->rowOff); - $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic; - $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart; - $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); + $fromOffsetX = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->from->colOff); + $fromOffsetY = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->from->rowOff); + $toCoordinate = \PhpSpreadsheet\Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1); + $toOffsetX = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->to->colOff); + $toOffsetY = \PhpSpreadsheet\Shared\Drawing::EMUToPixels($twoCellAnchor->to->rowOff); + $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic; + $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart; + $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $chartDetails[$docSheet->getTitle().'!'.$thisChart] = array( - 'fromCoordinate' => $fromCoordinate, - 'fromOffsetX' => $fromOffsetX, - 'fromOffsetY' => $fromOffsetY, - 'toCoordinate' => $toCoordinate, - 'toOffsetX' => $toOffsetX, - 'toOffsetY' => $toOffsetY, - 'worksheetTitle' => $docSheet->getTitle() - ); + $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ + 'fromCoordinate' => $fromCoordinate, + 'fromOffsetX' => $fromOffsetX, + 'fromOffsetY' => $fromOffsetY, + 'toCoordinate' => $toCoordinate, + 'toOffsetX' => $toOffsetX, + 'toOffsetY' => $toOffsetY, + 'worksheetTitle' => $docSheet->getTitle(), + ]; } } } @@ -1696,25 +1693,25 @@ class Excel2007 extends BaseReader implements IReader if ($xmlWorkbook->definedNames) { foreach ($xmlWorkbook->definedNames->definedName as $definedName) { // Extract range - $extractedRange = (string)$definedName; + $extractedRange = (string) $definedName; $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); if (($spos = strpos($extractedRange, '!')) !== false) { - $extractedRange = substr($extractedRange, 0, $spos).str_replace('$', '', substr($extractedRange, $spos)); + $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos)); } else { $extractedRange = str_replace('$', '', $extractedRange); } // Valid range? - if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') { + if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') { continue; } // Some definedNames are only applicable if we are on the same sheet... - if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) { + if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $sheetId) { // Switch on type - switch ((string)$definedName['name']) { + switch ((string) $definedName['name']) { case '_xlnm._FilterDatabase': - if ((string)$definedName['hidden'] !== '1') { + if ((string) $definedName['hidden'] !== '1') { $extractedRange = explode(',', $extractedRange); foreach ($extractedRange as $range) { $autoFilterRange = $range; @@ -1730,21 +1727,21 @@ class Excel2007 extends BaseReader implements IReader // Set print titles foreach ($extractedRange as $range) { - $matches = array(); + $matches = []; $range = str_replace('$', '', $range); // check for repeating columns, e g. 'A:A' or 'A:D' if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) { - $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2])); + $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]); } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) { // check for repeating rows, e.g. '1:1' or '1:5' - $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2])); + $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]); } } break; case '_xlnm.Print_Area': $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma? - $newRangeSets = array(); + $newRangeSets = []; foreach ($rangeSets as $rangeSet) { $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark? $rangeSet = isset($range[1]) ? $range[1] : $range[0]; @@ -1771,38 +1768,38 @@ class Excel2007 extends BaseReader implements IReader if ($xmlWorkbook->definedNames) { foreach ($xmlWorkbook->definedNames->definedName as $definedName) { // Extract range - $extractedRange = (string)$definedName; + $extractedRange = (string) $definedName; $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); if (($spos = strpos($extractedRange, '!')) !== false) { - $extractedRange = substr($extractedRange, 0, $spos).str_replace('$', '', substr($extractedRange, $spos)); + $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos)); } else { $extractedRange = str_replace('$', '', $extractedRange); } // Valid range? - if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') { + if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') { continue; } // Some definedNames are only applicable if we are on the same sheet... - if ((string)$definedName['localSheetId'] != '') { + if ((string) $definedName['localSheetId'] != '') { // Local defined name // Switch on type - switch ((string)$definedName['name']) { + switch ((string) $definedName['name']) { case '_xlnm._FilterDatabase': case '_xlnm.Print_Titles': case '_xlnm.Print_Area': break; default: if ($mapSheetId[(integer) $definedName['localSheetId']] !== null) { - $range = explode('!', (string)$definedName); + $range = explode('!', (string) $definedName); if (count($range) == 2) { $range[0] = str_replace("''", "'", $range[0]); - $range[0] = str_replace("'", "", $range[0]); + $range[0] = str_replace("'", '', $range[0]); if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) { $extractedRange = str_replace('$', '', $range[1]); $scope = $docSheet->getParent()->getSheet($mapSheetId[(integer) $definedName['localSheetId']]); - $excel->addNamedRange(new \PhpSpreadsheet\NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope)); + $excel->addNamedRange(new \PhpSpreadsheet\NamedRange((string) $definedName['name'], $worksheet, $extractedRange, true, $scope)); } } } @@ -1812,9 +1809,9 @@ class Excel2007 extends BaseReader implements IReader // "Global" definedNames $locatedSheet = null; $extractedSheetName = ''; - if (strpos((string)$definedName, '!') !== false) { + if (strpos((string) $definedName, '!') !== false) { // Extract sheet name - $extractedSheetName = \PhpSpreadsheet\Worksheet::extractSheetTitle((string)$definedName, true); + $extractedSheetName = \PhpSpreadsheet\Worksheet::extractSheetTitle((string) $definedName, true); $extractedSheetName = $extractedSheetName[0]; // Locate sheet @@ -1826,7 +1823,7 @@ class Excel2007 extends BaseReader implements IReader } if ($locatedSheet !== null) { - $excel->addNamedRange(new \PhpSpreadsheet\NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false)); + $excel->addNamedRange(new \PhpSpreadsheet\NamedRange((string) $definedName['name'], $locatedSheet, $extractedRange, false)); } } } @@ -1835,7 +1832,7 @@ class Excel2007 extends BaseReader implements IReader if ((!$this->readDataOnly) || (!empty($this->loadSheetsOnly))) { // active sheet index - $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index + $activeTab = intval($xmlWorkbook->bookViews->workbookView['activeTab']); // refers to old sheet index // keep active sheet index if sheet is still loaded, else first sheet is set as the active if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { @@ -1854,14 +1851,14 @@ class Excel2007 extends BaseReader implements IReader if (!$this->readDataOnly) { $contentTypes = simplexml_load_string( $this->securityScan( - $this->getFromZipArchive($zip, "[Content_Types].xml") + $this->getFromZipArchive($zip, '[Content_Types].xml') ), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); foreach ($contentTypes->Override as $contentType) { - switch ($contentType["ContentType"]) { - case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": + switch ($contentType['ContentType']) { + case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml': if ($this->includeCharts) { $chartEntryRef = ltrim($contentType['PartName'], '/'); $chartElements = simplexml_load_string( @@ -1877,10 +1874,10 @@ class Excel2007 extends BaseReader implements IReader // var_dump($charts[$chartEntryRef]); // if (isset($charts[$chartEntryRef])) { - $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id']; + $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id']; // echo 'Position Ref ', $chartPositionRef, '
'; if (isset($chartDetails[$chartPositionRef])) { -// var_dump($chartDetails[$chartPositionRef]); + // var_dump($chartDetails[$chartPositionRef]); $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); @@ -1900,24 +1897,26 @@ class Excel2007 extends BaseReader implements IReader private static function readColor($color, $background = false) { - if (isset($color["rgb"])) { - return (string)$color["rgb"]; - } elseif (isset($color["indexed"])) { - return \PhpSpreadsheet\Style\Color::indexedColor($color["indexed"]-7, $background)->getARGB(); - } elseif (isset($color["theme"])) { + if (isset($color['rgb'])) { + return (string) $color['rgb']; + } elseif (isset($color['indexed'])) { + return \PhpSpreadsheet\Style\Color::indexedColor($color['indexed'] - 7, $background)->getARGB(); + } elseif (isset($color['theme'])) { if (self::$theme !== null) { - $returnColour = self::$theme->getColourByIndex((int)$color["theme"]); - if (isset($color["tint"])) { - $tintAdjust = (float) $color["tint"]; + $returnColour = self::$theme->getColourByIndex((int) $color['theme']); + if (isset($color['tint'])) { + $tintAdjust = (float) $color['tint']; $returnColour = \PhpSpreadsheet\Style\Color::changeBrightness($returnColour, $tintAdjust); } - return 'FF'.$returnColour; + + return 'FF' . $returnColour; } } if ($background) { return 'FFFFFFFF'; } + return 'FF000000'; } @@ -1934,27 +1933,27 @@ class Excel2007 extends BaseReader implements IReader // font if (isset($style->font)) { - $docStyle->getFont()->setName((string) $style->font->name["val"]); - $docStyle->getFont()->setSize((string) $style->font->sz["val"]); + $docStyle->getFont()->setName((string) $style->font->name['val']); + $docStyle->getFont()->setSize((string) $style->font->sz['val']); if (isset($style->font->b)) { - $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || self::boolean((string) $style->font->b["val"])); + $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val'])); } if (isset($style->font->i)) { - $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || self::boolean((string) $style->font->i["val"])); + $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val'])); } if (isset($style->font->strike)) { - $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || self::boolean((string) $style->font->strike["val"])); + $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val'])); } $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color)); - if (isset($style->font->u) && !isset($style->font->u["val"])) { + if (isset($style->font->u) && !isset($style->font->u['val'])) { $docStyle->getFont()->setUnderline(\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); - } elseif (isset($style->font->u) && isset($style->font->u["val"])) { - $docStyle->getFont()->setUnderline((string)$style->font->u["val"]); + } elseif (isset($style->font->u) && isset($style->font->u['val'])) { + $docStyle->getFont()->setUnderline((string) $style->font->u['val']); } - if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) { - $vertAlign = strtolower((string)$style->font->vertAlign["val"]); + if (isset($style->font->vertAlign) && isset($style->font->vertAlign['val'])) { + $vertAlign = strtolower((string) $style->font->vertAlign['val']); if ($vertAlign == 'superscript') { $docStyle->getFont()->setSuperScript(true); } @@ -1968,15 +1967,15 @@ class Excel2007 extends BaseReader implements IReader if (isset($style->fill)) { if ($style->fill->gradientFill) { $gradientFill = $style->fill->gradientFill[0]; - if (!empty($gradientFill["type"])) { - $docStyle->getFill()->setFillType((string) $gradientFill["type"]); + if (!empty($gradientFill['type'])) { + $docStyle->getFill()->setFillType((string) $gradientFill['type']); } - $docStyle->getFill()->setRotation(floatval($gradientFill["degree"])); - $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath("sml:stop[@position=0]"))->color)); - $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath("sml:stop[@position=1]"))->color)); + $docStyle->getFill()->setRotation(floatval($gradientFill['degree'])); + $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); + $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); } elseif ($style->fill->patternFill) { - $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid'; + $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid'; $docStyle->getFill()->setFillType($patternType); if ($style->fill->patternFill->fgColor) { $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true)); @@ -1991,8 +1990,8 @@ class Excel2007 extends BaseReader implements IReader // border if (isset($style->border)) { - $diagonalUp = self::boolean((string) $style->border["diagonalUp"]); - $diagonalDown = self::boolean((string) $style->border["diagonalDown"]); + $diagonalUp = self::boolean((string) $style->border['diagonalUp']); + $diagonalDown = self::boolean((string) $style->border['diagonalDown']); if (!$diagonalUp && !$diagonalDown) { $docStyle->getBorders()->setDiagonalDirection(\PhpSpreadsheet\Style\Borders::DIAGONAL_NONE); } elseif ($diagonalUp && !$diagonalDown) { @@ -2011,21 +2010,21 @@ class Excel2007 extends BaseReader implements IReader // alignment if (isset($style->alignment)) { - $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]); - $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]); + $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']); + $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']); $textRotation = 0; - if ((int)$style->alignment["textRotation"] <= 90) { - $textRotation = (int)$style->alignment["textRotation"]; - } elseif ((int)$style->alignment["textRotation"] > 90) { - $textRotation = 90 - (int)$style->alignment["textRotation"]; + if ((int) $style->alignment['textRotation'] <= 90) { + $textRotation = (int) $style->alignment['textRotation']; + } elseif ((int) $style->alignment['textRotation'] > 90) { + $textRotation = 90 - (int) $style->alignment['textRotation']; } $docStyle->getAlignment()->setTextRotation(intval($textRotation)); - $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment["wrapText"])); - $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment["shrinkToFit"])); - $docStyle->getAlignment()->setIndent(intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0); - $docStyle->getAlignment()->setReadorder(intval((string)$style->alignment["readingOrder"]) > 0 ? intval((string)$style->alignment["readingOrder"]) : 0); + $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText'])); + $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit'])); + $docStyle->getAlignment()->setIndent(intval((string) $style->alignment['indent']) > 0 ? intval((string) $style->alignment['indent']) : 0); + $docStyle->getAlignment()->setReadorder(intval((string) $style->alignment['readingOrder']) > 0 ? intval((string) $style->alignment['readingOrder']) : 0); } // protection @@ -2055,8 +2054,8 @@ class Excel2007 extends BaseReader implements IReader private static function readBorder($docBorder, $eleBorder) { - if (isset($eleBorder["style"])) { - $docBorder->setBorderStyle((string) $eleBorder["style"]); + if (isset($eleBorder['style'])) { + $docBorder->setBorderStyle((string) $eleBorder['style']); } if (isset($eleBorder->color)) { $docBorder->getColor()->setARGB(self::readColor($eleBorder->color)); @@ -2077,25 +2076,25 @@ class Excel2007 extends BaseReader implements IReader } else { $objText = $value->createTextRun(\PhpSpreadsheet\Shared\StringHelper::controlCharacterOOXML2PHP((string) $run->t)); - if (isset($run->rPr->rFont["val"])) { - $objText->getFont()->setName((string) $run->rPr->rFont["val"]); + if (isset($run->rPr->rFont['val'])) { + $objText->getFont()->setName((string) $run->rPr->rFont['val']); } - if (isset($run->rPr->sz["val"])) { - $objText->getFont()->setSize((string) $run->rPr->sz["val"]); + if (isset($run->rPr->sz['val'])) { + $objText->getFont()->setSize((string) $run->rPr->sz['val']); } if (isset($run->rPr->color)) { $objText->getFont()->setColor(new \PhpSpreadsheet\Style\Color(self::readColor($run->rPr->color))); } - if ((isset($run->rPr->b["val"]) && self::boolean((string) $run->rPr->b["val"])) || - (isset($run->rPr->b) && !isset($run->rPr->b["val"]))) { + if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) || + (isset($run->rPr->b) && !isset($run->rPr->b['val']))) { $objText->getFont()->setBold(true); } - if ((isset($run->rPr->i["val"]) && self::boolean((string) $run->rPr->i["val"])) || - (isset($run->rPr->i) && !isset($run->rPr->i["val"]))) { + if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) || + (isset($run->rPr->i) && !isset($run->rPr->i['val']))) { $objText->getFont()->setItalic(true); } - if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) { - $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]); + if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign['val'])) { + $vertAlign = strtolower((string) $run->rPr->vertAlign['val']); if ($vertAlign == 'superscript') { $objText->getFont()->setSuperScript(true); } @@ -2103,13 +2102,13 @@ class Excel2007 extends BaseReader implements IReader $objText->getFont()->setSubScript(true); } } - if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) { + if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) { $objText->getFont()->setUnderline(\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); - } elseif (isset($run->rPr->u) && isset($run->rPr->u["val"])) { - $objText->getFont()->setUnderline((string)$run->rPr->u["val"]); + } elseif (isset($run->rPr->u) && isset($run->rPr->u['val'])) { + $objText->getFont()->setUnderline((string) $run->rPr->u['val']); } - if ((isset($run->rPr->strike["val"]) && self::boolean((string) $run->rPr->strike["val"])) || - (isset($run->rPr->strike) && !isset($run->rPr->strike["val"]))) { + if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) || + (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) { $objText->getFont()->setStrikethrough(true); } } @@ -2126,8 +2125,8 @@ class Excel2007 extends BaseReader implements IReader $nameCustomUI = basename($customUITarget); // get the xml file (ribbon) $localRibbon = $this->getFromZipArchive($zip, $customUITarget); - $customUIImagesNames = array(); - $customUIImagesBinaries = array(); + $customUIImagesNames = []; + $customUIImagesBinaries = []; // something like customUI/_rels/customUI.xml.rels $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels'; $dataRels = $this->getFromZipArchive($zip, $pathRels); @@ -2141,10 +2140,10 @@ class Excel2007 extends BaseReader implements IReader if ($UIRels) { // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image foreach ($UIRels->Relationship as $ele) { - if ($ele["Type"] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { // an image ? - $customUIImagesNames[(string) $ele['Id']] = (string)$ele['Target']; - $customUIImagesBinaries[(string)$ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); + $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target']; + $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); } } } @@ -2164,7 +2163,7 @@ class Excel2007 extends BaseReader implements IReader private static function getArrayItem($array, $key = 0) { - return (isset($array[$key]) ? $array[$key] : null); + return isset($array[$key]) ? $array[$key] : null; } private static function dirAdd($base, $add) @@ -2174,10 +2173,10 @@ class Excel2007 extends BaseReader implements IReader private static function toCSSArray($style) { - $style = str_replace(array("\r","\n"), "", $style); + $style = str_replace(["\r", "\n"], '', $style); $temp = explode(';', $style); - $style = array(); + $style = []; foreach ($temp as $item) { $item = explode(':', $item); @@ -2211,6 +2210,7 @@ class Excel2007 extends BaseReader implements IReader if (is_numeric($value)) { return (bool) $value; } - return ($value === 'true' || $value === 'TRUE'); + + return $value === 'true' || $value === 'TRUE'; } } diff --git a/src/PhpSpreadsheet/Reader/Excel2007/Chart.php b/src/PhpSpreadsheet/Reader/Excel2007/Chart.php index 8866e2f5..f75472e5 100644 --- a/src/PhpSpreadsheet/Reader/Excel2007/Chart.php +++ b/src/PhpSpreadsheet/Reader/Excel2007/Chart.php @@ -40,16 +40,16 @@ class Chart return (float) $attributes[$name]; } } + return null; } - private static function readColor($color, $background = false) { - if (isset($color["rgb"])) { - return (string)$color["rgb"]; - } elseif (isset($color["indexed"])) { - return \PhpSpreadsheet\Style\Color::indexedColor($color["indexed"]-7, $background)->getARGB(); + if (isset($color['rgb'])) { + return (string) $color['rgb']; + } elseif (isset($color['indexed'])) { + return \PhpSpreadsheet\Style\Color::indexedColor($color['indexed'] - 7, $background)->getARGB(); } } @@ -63,90 +63,90 @@ class Chart foreach ($chartElementsC as $chartElementKey => $chartElement) { switch ($chartElementKey) { - case "chart": + case 'chart': foreach ($chartElement as $chartDetailsKey => $chartDetails) { $chartDetailsC = $chartDetails->children($namespacesChartMeta['c']); switch ($chartDetailsKey) { - case "plotArea": + case 'plotArea': $plotAreaLayout = $XaxisLable = $YaxisLable = null; - $plotSeries = $plotAttributes = array(); + $plotSeries = $plotAttributes = []; foreach ($chartDetails as $chartDetailKey => $chartDetail) { switch ($chartDetailKey) { - case "layout": + case 'layout': $plotAreaLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'plotArea'); break; - case "catAx": + case 'catAx': if (isset($chartDetail->title)) { $XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); } break; - case "dateAx": + case 'dateAx': if (isset($chartDetail->title)) { $XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); } break; - case "valAx": + case 'valAx': if (isset($chartDetail->title)) { $YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); } break; - case "barChart": - case "bar3DChart": + case 'barChart': + case 'bar3DChart': $barDirection = self::getAttribute($chartDetail->barDir, 'val', 'string'); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer->setPlotDirection($barDirection); $plotSeries[] = $plotSer; $plotAttributes = self::readChartAttributes($chartDetail); break; - case "lineChart": - case "line3DChart": + case 'lineChart': + case 'line3DChart': $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotAttributes = self::readChartAttributes($chartDetail); break; - case "areaChart": - case "area3DChart": + case 'areaChart': + case 'area3DChart': $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotAttributes = self::readChartAttributes($chartDetail); break; - case "doughnutChart": - case "pieChart": - case "pie3DChart": + case 'doughnutChart': + case 'pieChart': + case 'pie3DChart': $explosion = isset($chartDetail->ser->explosion); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer->setPlotStyle($explosion); $plotSeries[] = $plotSer; $plotAttributes = self::readChartAttributes($chartDetail); break; - case "scatterChart": + case 'scatterChart': $scatterStyle = self::getAttribute($chartDetail->scatterStyle, 'val', 'string'); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer->setPlotStyle($scatterStyle); $plotSeries[] = $plotSer; $plotAttributes = self::readChartAttributes($chartDetail); break; - case "bubbleChart": + case 'bubbleChart': $bubbleScale = self::getAttribute($chartDetail->bubbleScale, 'val', 'integer'); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer->setPlotStyle($bubbleScale); $plotSeries[] = $plotSer; $plotAttributes = self::readChartAttributes($chartDetail); break; - case "radarChart": + case 'radarChart': $radarStyle = self::getAttribute($chartDetail->radarStyle, 'val', 'string'); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer->setPlotStyle($radarStyle); $plotSeries[] = $plotSer; $plotAttributes = self::readChartAttributes($chartDetail); break; - case "surfaceChart": - case "surface3DChart": + case 'surfaceChart': + case 'surface3DChart': $wireFrame = self::getAttribute($chartDetail->wireframe, 'val', 'boolean'); $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotSer->setPlotStyle($wireFrame); $plotSeries[] = $plotSer; $plotAttributes = self::readChartAttributes($chartDetail); break; - case "stockChart": + case 'stockChart': $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); $plotAttributes = self::readChartAttributes($plotAreaLayout); break; @@ -158,28 +158,28 @@ class Chart $plotArea = new \PhpSpreadsheet\Chart\PlotArea($plotAreaLayout, $plotSeries); self::setChartAttributes($plotAreaLayout, $plotAttributes); break; - case "plotVisOnly": + case 'plotVisOnly': $plotVisOnly = self::getAttribute($chartDetails, 'val', 'string'); break; - case "dispBlanksAs": + case 'dispBlanksAs': $dispBlanksAs = self::getAttribute($chartDetails, 'val', 'string'); break; - case "title": + case 'title': $title = self::chartTitle($chartDetails, $namespacesChartMeta, 'title'); break; - case "legend": + case 'legend': $legendPos = 'r'; $legendLayout = null; $legendOverlay = false; foreach ($chartDetails as $chartDetailKey => $chartDetail) { switch ($chartDetailKey) { - case "legendPos": + case 'legendPos': $legendPos = self::getAttribute($chartDetail, 'val', 'string'); break; - case "overlay": + case 'overlay': $legendOverlay = self::getAttribute($chartDetail, 'val', 'boolean'); break; - case "layout": + case 'layout': $legendLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'legend'); break; } @@ -197,21 +197,21 @@ class Chart private static function chartTitle($titleDetails, $namespacesChartMeta, $type) { - $caption = array(); + $caption = []; $titleLayout = null; foreach ($titleDetails as $titleDetailKey => $chartDetail) { switch ($titleDetailKey) { - case "tx": + case 'tx': $titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']); foreach ($titleDetails as $titleKey => $titleDetail) { switch ($titleKey) { - case "p": + case 'p': $titleDetailPart = $titleDetail->children($namespacesChartMeta['a']); $caption[] = self::parseRichText($titleDetailPart); } } break; - case "layout": + case 'layout': $titleLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta); break; } @@ -229,11 +229,12 @@ class Chart if (is_null($details)) { return null; } - $layout = array(); + $layout = []; 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'); } + return new \PhpSpreadsheet\Chart\Layout($layout); } @@ -241,54 +242,54 @@ class Chart { $multiSeriesType = null; $smoothLine = false; - $seriesLabel = $seriesCategory = $seriesValues = $plotOrder = array(); + $seriesLabel = $seriesCategory = $seriesValues = $plotOrder = []; $seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']); foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) { switch ($seriesDetailKey) { - case "grouping": + case 'grouping': $multiSeriesType = self::getAttribute($chartDetail->grouping, 'val', 'string'); break; - case "ser": + case 'ser': $marker = null; foreach ($seriesDetails as $seriesKey => $seriesDetail) { switch ($seriesKey) { - case "idx": + case 'idx': $seriesIndex = self::getAttribute($seriesDetail, 'val', 'integer'); break; - case "order": + case 'order': $seriesOrder = self::getAttribute($seriesDetail, 'val', 'integer'); $plotOrder[$seriesIndex] = $seriesOrder; break; - case "tx": + case 'tx': $seriesLabel[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta); break; - case "marker": + case 'marker': $marker = self::getAttribute($seriesDetail->symbol, 'val', 'string'); break; - case "smooth": + case 'smooth': $smoothLine = self::getAttribute($seriesDetail, 'val', 'boolean'); break; - case "cat": + case 'cat': $seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta); break; - case "val": + case 'val': $seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); break; - case "xVal": + case 'xVal': $seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); break; - case "yVal": + case 'yVal': $seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); break; } } } } + return new \PhpSpreadsheet\Chart\DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $smoothLine); } - private static function chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null, $smoothLine = false) { 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 null; } - private static function chartDataSeriesValues($seriesValueSet, $dataType = 'n') { - $seriesVal = array(); + $seriesVal = []; $formatCode = ''; $pointCount = 0; @@ -343,16 +344,16 @@ class Chart } } - return array( - 'formatCode' => $formatCode, - 'pointCount' => $pointCount, - 'dataValues' => $seriesVal - ); + return [ + 'formatCode' => $formatCode, + 'pointCount' => $pointCount, + 'dataValues' => $seriesVal, + ]; } private static function chartDataSeriesValuesMultiLevel($seriesValueSet, $dataType = 'n') { - $seriesVal = array(); + $seriesVal = []; $formatCode = ''; $pointCount = 0; @@ -377,11 +378,11 @@ class Chart } } - return array( - 'formatCode' => $formatCode, - 'pointCount' => $pointCount, - 'dataValues' => $seriesVal - ); + return [ + 'formatCode' => $formatCode, + 'pointCount' => $pointCount, + 'dataValues' => $seriesVal, + ]; } private static function parseRichText($titleDetailPart = null) @@ -393,8 +394,8 @@ class Chart $objText = $value->createTextRun((string) $titleDetailElement->t); } if (isset($titleDetailElement->rPr)) { - if (isset($titleDetailElement->rPr->rFont["val"])) { - $objText->getFont()->setName((string) $titleDetailElement->rPr->rFont["val"]); + if (isset($titleDetailElement->rPr->rFont['val'])) { + $objText->getFont()->setName((string) $titleDetailElement->rPr->rFont['val']); } $fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer')); @@ -453,7 +454,7 @@ class Chart private static function readChartAttributes($chartDetail) { - $plotAttributes = array(); + $plotAttributes = []; if (isset($chartDetail->dLbls)) { if (isset($chartDetail->dLbls->howLegendKey)) { $plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string'); diff --git a/src/PhpSpreadsheet/Reader/Excel2007/Theme.php b/src/PhpSpreadsheet/Reader/Excel2007/Theme.php index d3aaab78..6d0e0e84 100644 --- a/src/PhpSpreadsheet/Reader/Excel2007/Theme.php +++ b/src/PhpSpreadsheet/Reader/Excel2007/Theme.php @@ -47,7 +47,6 @@ class Theme */ private $colourMapValues; - /** * Colour Map * @@ -55,17 +54,15 @@ class Theme */ private $colourMap; - /** * Create a new Theme - * */ public function __construct($themeName, $colourSchemeName, $colourMap) { // Initialise values - $this->themeName = $themeName; + $this->themeName = $themeName; $this->colourSchemeName = $colourSchemeName; - $this->colourMap = $colourMap; + $this->colourMap = $colourMap; } /** @@ -98,6 +95,7 @@ class Theme if (isset($this->colourMap[$index])) { return $this->colourMap[$index]; } + return null; } diff --git a/src/PhpSpreadsheet/Reader/Excel5.php b/src/PhpSpreadsheet/Reader/Excel5.php index 72a8ae5c..c3eb9735 100644 --- a/src/PhpSpreadsheet/Reader/Excel5.php +++ b/src/PhpSpreadsheet/Reader/Excel5.php @@ -58,94 +58,94 @@ namespace PhpSpreadsheet\Reader; class Excel5 extends BaseReader implements IReader { // ParseXL definitions - const XLS_BIFF8 = 0x0600; - const XLS_BIFF7 = 0x0500; - const XLS_WORKBOOKGLOBALS = 0x0005; - const XLS_WORKSHEET = 0x0010; + const XLS_BIFF8 = 0x0600; + const XLS_BIFF7 = 0x0500; + const XLS_WORKBOOKGLOBALS = 0x0005; + const XLS_WORKSHEET = 0x0010; // record identifiers - const XLS_TYPE_FORMULA = 0x0006; - const XLS_TYPE_EOF = 0x000a; - const XLS_TYPE_PROTECT = 0x0012; - const XLS_TYPE_OBJECTPROTECT = 0x0063; - const XLS_TYPE_SCENPROTECT = 0x00dd; - const XLS_TYPE_PASSWORD = 0x0013; - const XLS_TYPE_HEADER = 0x0014; - const XLS_TYPE_FOOTER = 0x0015; - const XLS_TYPE_EXTERNSHEET = 0x0017; - const XLS_TYPE_DEFINEDNAME = 0x0018; - const XLS_TYPE_VERTICALPAGEBREAKS = 0x001a; + const XLS_TYPE_FORMULA = 0x0006; + const XLS_TYPE_EOF = 0x000a; + const XLS_TYPE_PROTECT = 0x0012; + const XLS_TYPE_OBJECTPROTECT = 0x0063; + const XLS_TYPE_SCENPROTECT = 0x00dd; + const XLS_TYPE_PASSWORD = 0x0013; + const XLS_TYPE_HEADER = 0x0014; + const XLS_TYPE_FOOTER = 0x0015; + const XLS_TYPE_EXTERNSHEET = 0x0017; + const XLS_TYPE_DEFINEDNAME = 0x0018; + const XLS_TYPE_VERTICALPAGEBREAKS = 0x001a; const XLS_TYPE_HORIZONTALPAGEBREAKS = 0x001b; - const XLS_TYPE_NOTE = 0x001c; - const XLS_TYPE_SELECTION = 0x001d; - const XLS_TYPE_DATEMODE = 0x0022; - const XLS_TYPE_EXTERNNAME = 0x0023; - const XLS_TYPE_LEFTMARGIN = 0x0026; - const XLS_TYPE_RIGHTMARGIN = 0x0027; - const XLS_TYPE_TOPMARGIN = 0x0028; - const XLS_TYPE_BOTTOMMARGIN = 0x0029; - const XLS_TYPE_PRINTGRIDLINES = 0x002b; - const XLS_TYPE_FILEPASS = 0x002f; - const XLS_TYPE_FONT = 0x0031; - const XLS_TYPE_CONTINUE = 0x003c; - const XLS_TYPE_PANE = 0x0041; - const XLS_TYPE_CODEPAGE = 0x0042; - const XLS_TYPE_DEFCOLWIDTH = 0x0055; - const XLS_TYPE_OBJ = 0x005d; - const XLS_TYPE_COLINFO = 0x007d; - const XLS_TYPE_IMDATA = 0x007f; - const XLS_TYPE_SHEETPR = 0x0081; - const XLS_TYPE_HCENTER = 0x0083; - const XLS_TYPE_VCENTER = 0x0084; - const XLS_TYPE_SHEET = 0x0085; - const XLS_TYPE_PALETTE = 0x0092; - const XLS_TYPE_SCL = 0x00a0; - const XLS_TYPE_PAGESETUP = 0x00a1; - const XLS_TYPE_MULRK = 0x00bd; - const XLS_TYPE_MULBLANK = 0x00be; - const XLS_TYPE_DBCELL = 0x00d7; - const XLS_TYPE_XF = 0x00e0; - const XLS_TYPE_MERGEDCELLS = 0x00e5; - const XLS_TYPE_MSODRAWINGGROUP = 0x00eb; - const XLS_TYPE_MSODRAWING = 0x00ec; - const XLS_TYPE_SST = 0x00fc; - const XLS_TYPE_LABELSST = 0x00fd; - const XLS_TYPE_EXTSST = 0x00ff; - const XLS_TYPE_EXTERNALBOOK = 0x01ae; - const XLS_TYPE_DATAVALIDATIONS = 0x01b2; - const XLS_TYPE_TXO = 0x01b6; - const XLS_TYPE_HYPERLINK = 0x01b8; - const XLS_TYPE_DATAVALIDATION = 0x01be; - const XLS_TYPE_DIMENSION = 0x0200; - const XLS_TYPE_BLANK = 0x0201; - const XLS_TYPE_NUMBER = 0x0203; - const XLS_TYPE_LABEL = 0x0204; - const XLS_TYPE_BOOLERR = 0x0205; - const XLS_TYPE_STRING = 0x0207; - const XLS_TYPE_ROW = 0x0208; - const XLS_TYPE_INDEX = 0x020b; - const XLS_TYPE_ARRAY = 0x0221; - const XLS_TYPE_DEFAULTROWHEIGHT = 0x0225; - const XLS_TYPE_WINDOW2 = 0x023e; - const XLS_TYPE_RK = 0x027e; - const XLS_TYPE_STYLE = 0x0293; - const XLS_TYPE_FORMAT = 0x041e; - const XLS_TYPE_SHAREDFMLA = 0x04bc; - const XLS_TYPE_BOF = 0x0809; - const XLS_TYPE_SHEETPROTECTION = 0x0867; - const XLS_TYPE_RANGEPROTECTION = 0x0868; - const XLS_TYPE_SHEETLAYOUT = 0x0862; - const XLS_TYPE_XFEXT = 0x087d; - const XLS_TYPE_PAGELAYOUTVIEW = 0x088b; - const XLS_TYPE_UNKNOWN = 0xffff; + const XLS_TYPE_NOTE = 0x001c; + const XLS_TYPE_SELECTION = 0x001d; + const XLS_TYPE_DATEMODE = 0x0022; + const XLS_TYPE_EXTERNNAME = 0x0023; + const XLS_TYPE_LEFTMARGIN = 0x0026; + const XLS_TYPE_RIGHTMARGIN = 0x0027; + const XLS_TYPE_TOPMARGIN = 0x0028; + const XLS_TYPE_BOTTOMMARGIN = 0x0029; + const XLS_TYPE_PRINTGRIDLINES = 0x002b; + const XLS_TYPE_FILEPASS = 0x002f; + const XLS_TYPE_FONT = 0x0031; + const XLS_TYPE_CONTINUE = 0x003c; + const XLS_TYPE_PANE = 0x0041; + const XLS_TYPE_CODEPAGE = 0x0042; + const XLS_TYPE_DEFCOLWIDTH = 0x0055; + const XLS_TYPE_OBJ = 0x005d; + const XLS_TYPE_COLINFO = 0x007d; + const XLS_TYPE_IMDATA = 0x007f; + const XLS_TYPE_SHEETPR = 0x0081; + const XLS_TYPE_HCENTER = 0x0083; + const XLS_TYPE_VCENTER = 0x0084; + const XLS_TYPE_SHEET = 0x0085; + const XLS_TYPE_PALETTE = 0x0092; + const XLS_TYPE_SCL = 0x00a0; + const XLS_TYPE_PAGESETUP = 0x00a1; + const XLS_TYPE_MULRK = 0x00bd; + const XLS_TYPE_MULBLANK = 0x00be; + const XLS_TYPE_DBCELL = 0x00d7; + const XLS_TYPE_XF = 0x00e0; + const XLS_TYPE_MERGEDCELLS = 0x00e5; + const XLS_TYPE_MSODRAWINGGROUP = 0x00eb; + const XLS_TYPE_MSODRAWING = 0x00ec; + const XLS_TYPE_SST = 0x00fc; + const XLS_TYPE_LABELSST = 0x00fd; + const XLS_TYPE_EXTSST = 0x00ff; + const XLS_TYPE_EXTERNALBOOK = 0x01ae; + const XLS_TYPE_DATAVALIDATIONS = 0x01b2; + const XLS_TYPE_TXO = 0x01b6; + const XLS_TYPE_HYPERLINK = 0x01b8; + const XLS_TYPE_DATAVALIDATION = 0x01be; + const XLS_TYPE_DIMENSION = 0x0200; + const XLS_TYPE_BLANK = 0x0201; + const XLS_TYPE_NUMBER = 0x0203; + const XLS_TYPE_LABEL = 0x0204; + const XLS_TYPE_BOOLERR = 0x0205; + const XLS_TYPE_STRING = 0x0207; + const XLS_TYPE_ROW = 0x0208; + const XLS_TYPE_INDEX = 0x020b; + const XLS_TYPE_ARRAY = 0x0221; + const XLS_TYPE_DEFAULTROWHEIGHT = 0x0225; + const XLS_TYPE_WINDOW2 = 0x023e; + const XLS_TYPE_RK = 0x027e; + const XLS_TYPE_STYLE = 0x0293; + const XLS_TYPE_FORMAT = 0x041e; + const XLS_TYPE_SHAREDFMLA = 0x04bc; + const XLS_TYPE_BOF = 0x0809; + const XLS_TYPE_SHEETPROTECTION = 0x0867; + const XLS_TYPE_RANGEPROTECTION = 0x0868; + const XLS_TYPE_SHEETLAYOUT = 0x0862; + const XLS_TYPE_XFEXT = 0x087d; + const XLS_TYPE_PAGELAYOUTVIEW = 0x088b; + const XLS_TYPE_UNKNOWN = 0xffff; // Encryption type - const MS_BIFF_CRYPTO_NONE = 0; - const MS_BIFF_CRYPTO_XOR = 1; - const MS_BIFF_CRYPTO_RC4 = 2; + const MS_BIFF_CRYPTO_NONE = 0; + const MS_BIFF_CRYPTO_XOR = 1; + const MS_BIFF_CRYPTO_RC4 = 2; // Size of stream blocks when using RC4 encryption - const REKEY_BLOCK = 0x400; + const REKEY_BLOCK = 0x400; /** * Summary Information stream data. @@ -185,7 +185,7 @@ class Excel5 extends BaseReader implements IReader /** * Current position in stream * - * @var integer + * @var int */ private $pos; @@ -284,14 +284,14 @@ class Excel5 extends BaseReader implements IReader /** * Panes are frozen? (in sheet currently being read). See WINDOW2 record. * - * @var boolean + * @var bool */ private $frozen; /** * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record. * - * @var boolean + * @var bool */ private $isFitToPages; @@ -413,14 +413,14 @@ class Excel5 extends BaseReader implements IReader * Can the current IReader read the file? * * @param string $pFilename - * @return boolean * @throws Exception + * @return bool */ public function canRead($pFilename) { // Check if file exists 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.'); } try { @@ -429,6 +429,7 @@ class Excel5 extends BaseReader implements IReader // get excel data $res = $ole->read($pFilename); + return true; } catch (\PhpSpreadsheet\Exception $e) { return false; @@ -445,10 +446,10 @@ class Excel5 extends BaseReader implements IReader { // Check if file exists 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.'); } - $worksheetNames = array(); + $worksheetNames = []; // Read the OLE file $this->loadOLE($pFilename); @@ -456,8 +457,8 @@ class Excel5 extends BaseReader implements IReader // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); - $this->pos = 0; - $this->sheets = array(); + $this->pos = 0; + $this->sheets = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { @@ -491,7 +492,6 @@ class Excel5 extends BaseReader implements IReader return $worksheetNames; } - /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) * @@ -502,10 +502,10 @@ class Excel5 extends BaseReader implements IReader { // Check if file exists 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 = []; // Read the OLE file $this->loadOLE($pFilename); @@ -514,8 +514,8 @@ class Excel5 extends BaseReader implements IReader $this->dataSize = strlen($this->data); // initialize - $this->pos = 0; - $this->sheets = array(); + $this->pos = 0; + $this->sheets = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { @@ -546,7 +546,7 @@ class Excel5 extends BaseReader implements IReader continue; } - $tmpInfo = array(); + $tmpInfo = []; $tmpInfo['worksheetName'] = $sheet['name']; $tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnIndex'] = 0; @@ -598,13 +598,12 @@ class Excel5 extends BaseReader implements IReader return $worksheetInfo; } - /** * Loads PhpSpreadsheet from file * * @param string $pFilename - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function load($pFilename) { @@ -629,20 +628,20 @@ class Excel5 extends BaseReader implements IReader $this->dataSize = strlen($this->data); // initialize - $this->pos = 0; - $this->codepage = 'CP1252'; - $this->formats = array(); - $this->objFonts = array(); - $this->palette = array(); - $this->sheets = array(); - $this->externalBooks = array(); - $this->ref = array(); - $this->definedname = array(); - $this->sst = array(); - $this->drawingGroupData = ''; - $this->xfIndex = ''; - $this->mapCellXfIndex = array(); - $this->mapCellStyleXfIndex = array(); + $this->pos = 0; + $this->codepage = 'CP1252'; + $this->formats = []; + $this->objFonts = []; + $this->palette = []; + $this->sheets = []; + $this->externalBooks = []; + $this->ref = []; + $this->definedname = []; + $this->sst = []; + $this->drawingGroupData = ''; + $this->xfIndex = ''; + $this->mapCellXfIndex = []; + $this->mapCellStyleXfIndex = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { @@ -733,10 +732,10 @@ class Excel5 extends BaseReader implements IReader } // border colors - $top = $objStyle->getBorders()->getTop(); - $right = $objStyle->getBorders()->getRight(); - $bottom = $objStyle->getBorders()->getBottom(); - $left = $objStyle->getBorders()->getLeft(); + $top = $objStyle->getBorders()->getTop(); + $right = $objStyle->getBorders()->getRight(); + $bottom = $objStyle->getBorders()->getBottom(); + $left = $objStyle->getBorders()->getLeft(); $diagonal = $objStyle->getBorders()->getDiagonal(); if (isset($top->colorIndex)) { @@ -798,19 +797,19 @@ class Excel5 extends BaseReader implements IReader $this->drawingData = ''; // Initialize objs - $this->objs = array(); + $this->objs = []; // Initialize shared formula parts - $this->sharedFormulaParts = array(); + $this->sharedFormulaParts = []; // Initialize shared formulas - $this->sharedFormulas = array(); + $this->sharedFormulas = []; // Initialize text objs - $this->textObjects = array(); + $this->textObjects = []; // Initialize cell annotations - $this->cellNotes = array(); + $this->cellNotes = []; $this->textObjRef = -1; while ($this->pos <= $this->dataSize - 4) { @@ -992,7 +991,7 @@ class Excel5 extends BaseReader implements IReader // treat OBJ records foreach ($this->objs as $n => $obj) { -// echo '
Object reference is ', $n,'
'; + // echo '
Object reference is ', $n,'
'; // var_dump($obj); // echo '
'; @@ -1118,7 +1117,7 @@ class Excel5 extends BaseReader implements IReader // in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2 $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? - $extractedRanges = array(); + $extractedRanges = []; foreach ($ranges as $range) { // $range should look like one of these // Foo!$C$7:$J$66 @@ -1165,10 +1164,10 @@ class Excel5 extends BaseReader implements IReader if ($firstColumn == 'A' and $lastColumn == 'IV') { // then we have repeating rows - $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($firstRow, $lastRow)); + $docSheet->getPageSetup()->setRowsToRepeatAtTop([$firstRow, $lastRow]); } elseif ($firstRow == 1 and $lastRow == 65536) { // then we have repeating columns - $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($firstColumn, $lastColumn)); + $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$firstColumn, $lastColumn]); } } } @@ -1244,7 +1243,7 @@ class Excel5 extends BaseReader implements IReader $data = substr($data, $step); $pos += $step; $len -= $step; - $block++; + ++$block; $this->rc4Key = $this->makeKey($block, $this->md5Ctxt); } $recordData .= $this->rc4Key->RC4(substr($data, 0, $len)); @@ -1255,6 +1254,7 @@ class Excel5 extends BaseReader implements IReader } elseif ($this->encryption == self::MS_BIFF_CRYPTO_XOR) { throw new Exception('XOr encryption not supported'); } + return $recordData; } @@ -1279,7 +1279,6 @@ class Excel5 extends BaseReader implements IReader // $this->userDefinedProperties = $ole->getUserDefinedProperties(); } - /** * Read summary information */ @@ -1306,7 +1305,7 @@ class Excel5 extends BaseReader implements IReader $secLength = self::getInt4d($this->summaryInformation, $secOffset); // offset: $secOffset+4; size: 4; property count - $countProperties = self::getInt4d($this->summaryInformation, $secOffset+4); + $countProperties = self::getInt4d($this->summaryInformation, $secOffset + 4); // initialize code page (used to resolve string values) $codePage = 'CP1252'; @@ -1315,11 +1314,11 @@ class Excel5 extends BaseReader implements IReader // loop through property decarations and properties for ($i = 0; $i < $countProperties; ++$i) { // offset: ($secOffset+8) + (8 * $i); size: 4; property ID - $id = self::getInt4d($this->summaryInformation, ($secOffset+8) + (8 * $i)); + $id = self::getInt4d($this->summaryInformation, ($secOffset + 8) + (8 * $i)); // Use value of property id as appropriate // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48) - $offset = self::getInt4d($this->summaryInformation, ($secOffset+12) + (8 * $i)); + $offset = self::getInt4d($this->summaryInformation, ($secOffset + 12) + (8 * $i)); $type = self::getInt4d($this->summaryInformation, $secOffset + $offset); @@ -1414,7 +1413,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read additional document summary information */ @@ -1444,7 +1442,7 @@ class Excel5 extends BaseReader implements IReader // echo '$secLength = ', $secLength,'
'; // offset: $secOffset+4; size: 4; property count - $countProperties = self::getInt4d($this->documentSummaryInformation, $secOffset+4); + $countProperties = self::getInt4d($this->documentSummaryInformation, $secOffset + 4); // echo '$countProperties = ', $countProperties,'
'; // initialize code page (used to resolve string values) @@ -1453,14 +1451,14 @@ class Excel5 extends BaseReader implements IReader // offset: ($secOffset+8); size: var // loop through property decarations and properties for ($i = 0; $i < $countProperties; ++$i) { -// echo 'Property ', $i,'
'; + // echo 'Property ', $i,'
'; // offset: ($secOffset+8) + (8 * $i); size: 4; property ID - $id = self::getInt4d($this->documentSummaryInformation, ($secOffset+8) + (8 * $i)); + $id = self::getInt4d($this->documentSummaryInformation, ($secOffset + 8) + (8 * $i)); // echo 'ID is ', $id,'
'; // Use value of property id as appropriate // offset: 60 + 8 * $i; size: 4; offset from beginning of section (48) - $offset = self::getInt4d($this->documentSummaryInformation, ($secOffset+12) + (8 * $i)); + $offset = self::getInt4d($this->documentSummaryInformation, ($secOffset + 12) + (8 * $i)); $type = self::getInt4d($this->documentSummaryInformation, $secOffset + $offset); // echo 'Type is ', $type,', '; @@ -1551,7 +1549,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record. */ @@ -1564,14 +1561,13 @@ class Excel5 extends BaseReader implements IReader $this->pos += 4 + $length; } - /** * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions, * this record stores a note (cell note). This feature was significantly enhanced in Excel 97. */ private function readNote() { -// echo 'Read Cell Annotation
'; + // echo 'Read Cell Annotation
'; $length = self::getInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -1591,11 +1587,11 @@ class Excel5 extends BaseReader implements IReader // echo 'Note Object ID=', $noteObjID,'
'; // echo 'Note Author=', $noteAuthor,'
'; // - $this->cellNotes[$noteObjID] = array( - 'cellRef' => $cellAddress, - 'objectID' => $noteObjID, - 'author' => $noteAuthor - ); + $this->cellNotes[$noteObjID] = [ + 'cellRef' => $cellAddress, + 'objectID' => $noteObjID, + 'author' => $noteAuthor, + ]; } else { $extension = false; if ($cellAddress == '$B$65536') { @@ -1618,7 +1614,7 @@ class Excel5 extends BaseReader implements IReader // Concatenate this extension with the currently set comment for the cell $comment = $this->phpSheet->getComment($cellAddress); $commentText = $comment->getText()->getPlainText(); - $comment->setText($this->parseRichText($commentText.$noteText)); + $comment->setText($this->parseRichText($commentText . $noteText)); } else { // Set comment for the cell $this->phpSheet->getComment($cellAddress)->setText($this->parseRichText($noteText)); @@ -1627,7 +1623,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * The TEXT Object record contains the text associated with a cell annotation. */ @@ -1649,25 +1644,24 @@ class Excel5 extends BaseReader implements IReader // cchText: 2 bytes; length of the text (in the first continue record) // cbRuns: 2 bytes; length of the formatting (in the second continue record) // followed by the continuation records containing the actual text and formatting - $grbitOpts = self::getInt2d($recordData, 0); - $rot = self::getInt2d($recordData, 2); - $cchText = self::getInt2d($recordData, 10); - $cbRuns = self::getInt2d($recordData, 12); - $text = $this->getSplicedRecordData(); + $grbitOpts = self::getInt2d($recordData, 0); + $rot = self::getInt2d($recordData, 2); + $cchText = self::getInt2d($recordData, 10); + $cbRuns = self::getInt2d($recordData, 12); + $text = $this->getSplicedRecordData(); - $this->textObjects[$this->textObjRef] = array( - 'text' => substr($text["recordData"], $text["spliceOffsets"][0]+1, $cchText), - 'format' => substr($text["recordData"], $text["spliceOffsets"][1], $cbRuns), + $this->textObjects[$this->textObjRef] = [ + 'text' => substr($text['recordData'], $text['spliceOffsets'][0] + 1, $cchText), + 'format' => substr($text['recordData'], $text['spliceOffsets'][1], $cbRuns), 'alignment' => $grbitOpts, - 'rotation' => $rot - ); + 'rotation' => $rot, + ]; // echo '_readTextObject()
'; // var_dump($this->textObjects[$this->textObjRef]); // echo '
'; } - /** * Read BOF */ @@ -1705,7 +1699,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * FILEPASS * @@ -1747,7 +1740,7 @@ class Excel5 extends BaseReader implements IReader /** * Make an RC4 decryptor for the given block * - * @var int $block Block for which to create decrypto + * @var int Block for which to create decrypto * @var string $valContext MD5 context state * * @return Excel5\RC4 @@ -1756,7 +1749,7 @@ class Excel5 extends BaseReader implements IReader { $pwarray = str_repeat("\0", 64); - for ($i = 0; $i < 5; $i++) { + for ($i = 0; $i < 5; ++$i) { $pwarray[$i] = $valContext[$i]; } @@ -1772,13 +1765,14 @@ class Excel5 extends BaseReader implements IReader $md5->add($pwarray); $s = $md5->getContext(); + return new Excel5\RC4($s); } /** * Verify RC4 file password * - * @var string $password Password to check + * @var string Password to check * @var string $docid Document id * @var string $salt_data Salt data * @var string $hashedsalt_data Hashed salt data @@ -1790,7 +1784,7 @@ class Excel5 extends BaseReader implements IReader { $pwarray = str_repeat("\0", 64); - for ($i = 0; $i < strlen($password); $i++) { + for ($i = 0; $i < strlen($password); ++$i) { $o = ord(substr($password, $i, 1)); $pwarray[2 * $i] = chr($o & 0xff); $pwarray[2 * $i + 1] = chr(($o >> 8) & 0xff); @@ -1813,7 +1807,7 @@ class Excel5 extends BaseReader implements IReader if ((64 - $offset) < 5) { $tocopy = 64 - $offset; } - for ($i = 0; $i <= $tocopy; $i++) { + for ($i = 0; $i <= $tocopy; ++$i) { $pwarray[$offset + $i] = $mdContext1[$keyoffset + $i]; } $offset += $tocopy; @@ -1828,14 +1822,14 @@ class Excel5 extends BaseReader implements IReader $keyoffset = 0; $tocopy = 5; - for ($i = 0; $i < 16; $i++) { + for ($i = 0; $i < 16; ++$i) { $pwarray[$offset + $i] = $docid[$i]; } $offset += 16; } $pwarray[16] = "\x80"; - for ($i = 0; $i < 47; $i++) { + for ($i = 0; $i < 47; ++$i) { $pwarray[17 + $i] = "\0"; } $pwarray[56] = "\x80"; @@ -1882,7 +1876,6 @@ class Excel5 extends BaseReader implements IReader $this->codepage = \PhpSpreadsheet\Shared\CodePage::numberToName($codepage); } - /** * DATEMODE * @@ -1910,7 +1903,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read a FONT record */ @@ -2001,7 +1993,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * FORMAT * @@ -2039,7 +2030,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * XF - Extended Format * @@ -2079,13 +2069,13 @@ class Excel5 extends BaseReader implements IReader $numberFormatIndex = self::getInt2d($recordData, 2); if (isset($this->formats[$numberFormatIndex])) { // then we have user-defined format code - $numberformat = array('code' => $this->formats[$numberFormatIndex]); + $numberformat = ['code' => $this->formats[$numberFormatIndex]]; } elseif (($code = \PhpSpreadsheet\Style\NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') { // then we have built-in format code - $numberformat = array('code' => $code); + $numberformat = ['code' => $code]; } else { // we set the general format code - $numberformat = array('code' => 'General'); + $numberformat = ['code' => 'General']; } $objStyle->getNumberFormat()->setFormatCode($numberformat['code']); @@ -2332,7 +2322,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * */ @@ -2375,7 +2364,7 @@ class Excel5 extends BaseReader implements IReader switch ($extType) { case 4: // fill start color - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2390,7 +2379,7 @@ class Excel5 extends BaseReader implements IReader } break; case 5: // fill end color - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2405,7 +2394,7 @@ class Excel5 extends BaseReader implements IReader } break; case 7: // border color top - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2420,7 +2409,7 @@ class Excel5 extends BaseReader implements IReader } break; case 8: // border color bottom - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2435,7 +2424,7 @@ class Excel5 extends BaseReader implements IReader } break; case 9: // border color left - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2450,7 +2439,7 @@ class Excel5 extends BaseReader implements IReader } break; case 10: // border color right - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2465,7 +2454,7 @@ class Excel5 extends BaseReader implements IReader } break; case 11: // border color diagonal - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2480,7 +2469,7 @@ class Excel5 extends BaseReader implements IReader } break; case 13: // font color - $xclfType = self::getInt2d($extData, 0); // color type + $xclfType = self::getInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { @@ -2501,7 +2490,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read STYLE record */ @@ -2540,7 +2528,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read PALETTE record */ @@ -2564,7 +2551,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * SHEET * @@ -2617,15 +2603,14 @@ class Excel5 extends BaseReader implements IReader $rec_name = $string['value']; } - $this->sheets[] = array( + $this->sheets[] = [ 'name' => $rec_name, 'offset' => $rec_offset, 'sheetState' => $sheetState, 'sheetType' => $sheetType, - ); + ]; } - /** * Read EXTERNALBOOK record */ @@ -2652,7 +2637,7 @@ class Excel5 extends BaseReader implements IReader $offset += $encodedUrlString['size']; // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length) - $externalSheetNames = array(); + $externalSheetNames = []; for ($i = 0; $i < $nm; ++$i) { $externalSheetNameString = self::readUnicodeStringLong(substr($recordData, $offset)); $externalSheetNames[] = $externalSheetNameString['value']; @@ -2660,35 +2645,34 @@ class Excel5 extends BaseReader implements IReader } // store the record data - $this->externalBooks[] = array( + $this->externalBooks[] = [ 'type' => 'external', 'encodedUrl' => $encodedUrlString['value'], 'externalSheetNames' => $externalSheetNames, - ); + ]; } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) { // internal reference // offset: 0; size: 2; number of sheet in this document // offset: 2; size: 2; 0x01 0x04 - $this->externalBooks[] = array( + $this->externalBooks[] = [ 'type' => 'internal', - ); + ]; } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) { // add-in function // offset: 0; size: 2; 0x0001 - $this->externalBooks[] = array( + $this->externalBooks[] = [ 'type' => 'addInFunction', - ); + ]; } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) { // DDE links, OLE links // offset: 0; size: 2; 0x0000 // offset: 2; size: var; encoded source document name - $this->externalBooks[] = array( + $this->externalBooks[] = [ 'type' => 'DDEorOLE', - ); + ]; } } - /** * Read EXTERNNAME record. */ @@ -2716,14 +2700,13 @@ class Excel5 extends BaseReader implements IReader $offset = 6 + $nameString['size']; $formula = $this->getFormulaFromStructure(substr($recordData, $offset)); - $this->externalNames[] = array( + $this->externalNames[] = [ 'name' => $nameString['value'], 'formula' => $formula, - ); + ]; } } - /** * Read EXTERNSHEET record */ @@ -2740,19 +2723,18 @@ class Excel5 extends BaseReader implements IReader // offset: 0; size: 2; number of following ref structures $nm = self::getInt2d($recordData, 0); for ($i = 0; $i < $nm; ++$i) { - $this->ref[] = array( + $this->ref[] = [ // offset: 2 + 6 * $i; index to EXTERNALBOOK record 'externalBookIndex' => self::getInt2d($recordData, 2 + 6 * $i), // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record 'firstSheetIndex' => self::getInt2d($recordData, 4 + 6 * $i), // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record 'lastSheetIndex' => self::getInt2d($recordData, 6 + 6 * $i), - ); + ]; } } } - /** * DEFINEDNAME * @@ -2806,16 +2788,15 @@ class Excel5 extends BaseReader implements IReader $formula = ''; } - $this->definedname[] = array( + $this->definedname[] = [ 'isBuiltInName' => $isBuiltInName, 'name' => $string['value'], 'formula' => $formula, 'scope' => $scope, - ); + ]; } } - /** * Read MSODRAWINGGROUP record */ @@ -2830,7 +2811,6 @@ class Excel5 extends BaseReader implements IReader $this->drawingGroupData .= $recordData; } - /** * SST - Shared String Table * @@ -2871,7 +2851,7 @@ class Excel5 extends BaseReader implements IReader ++$pos; // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed - $isCompressed = (($optionFlags & 0x01) == 0) ; + $isCompressed = (($optionFlags & 0x01) == 0); // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic $hasAsian = (($optionFlags & 0x04) != 0); @@ -2956,7 +2936,8 @@ class Excel5 extends BaseReader implements IReader // this fragment compressed $len = min($charsLeft, $limitpos - $pos); for ($j = 0; $j < $len; ++$j) { - $retstr .= $recordData{$pos + $j} . chr(0); + $retstr .= $recordData{$pos + $j} + . chr(0); } $charsLeft -= $len; $isCompressed = false; @@ -2982,7 +2963,7 @@ class Excel5 extends BaseReader implements IReader $retstr = self::encodeUTF16($retstr, $isCompressed); // read additional Rich-Text information, if any - $fmtRuns = array(); + $fmtRuns = []; if ($hasRichText) { // list of formatting runs for ($j = 0; $j < $formattingRuns; ++$j) { @@ -2992,10 +2973,10 @@ class Excel5 extends BaseReader implements IReader // index to font record $fontIndex = self::getInt2d($recordData, $pos + 2 + $j * 4); - $fmtRuns[] = array( + $fmtRuns[] = [ 'charPos' => $charPos, 'fontIndex' => $fontIndex, - ); + ]; } $pos += 4 * $formattingRuns; } @@ -3007,16 +2988,15 @@ class Excel5 extends BaseReader implements IReader } // store the shared sting - $this->sst[] = array( + $this->sst[] = [ 'value' => $retstr, 'fmtRuns' => $fmtRuns, - ); + ]; } // getSplicedRecordData() takes care of moving current position in data stream } - /** * Read PRINTGRIDLINES record */ @@ -3035,7 +3015,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read DEFAULTROWHEIGHT record */ @@ -3053,7 +3032,6 @@ class Excel5 extends BaseReader implements IReader $this->phpSheet->getDefaultRowDimension()->setRowHeight($height / 20); } - /** * Read SHEETPR record */ @@ -3080,7 +3058,6 @@ class Excel5 extends BaseReader implements IReader $this->isFitToPages = (bool) ((0x0100 & self::getInt2d($recordData, 0)) >> 8); } - /** * Read HORIZONTALPAGEBREAKS record */ @@ -3108,7 +3085,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read VERTICALPAGEBREAKS record */ @@ -3136,7 +3112,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read HEADER record */ @@ -3164,7 +3139,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read FOOTER record */ @@ -3191,7 +3165,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read HCENTER record */ @@ -3211,7 +3184,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read VCENTER record */ @@ -3231,7 +3203,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read LEFTMARGIN record */ @@ -3249,7 +3220,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read RIGHTMARGIN record */ @@ -3267,7 +3237,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read TOPMARGIN record */ @@ -3285,7 +3254,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read BOTTOMMARGIN record */ @@ -3303,7 +3271,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read PAGESETUP record */ @@ -3364,7 +3331,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * PROTECT - Sheet protection (BIFF2 through BIFF8) * if this record is omitted, then it also means no sheet protection @@ -3385,10 +3351,9 @@ class Excel5 extends BaseReader implements IReader // bit 0, mask 0x01; 1 = sheet is protected $bool = (0x01 & self::getInt2d($recordData, 0)) >> 0; - $this->phpSheet->getProtection()->setSheet((bool)$bool); + $this->phpSheet->getProtection()->setSheet((bool) $bool); } - /** * SCENPROTECT */ @@ -3409,10 +3374,9 @@ class Excel5 extends BaseReader implements IReader // bit: 0, mask 0x01; 1 = scenarios are protected $bool = (0x01 & self::getInt2d($recordData, 0)) >> 0; - $this->phpSheet->getProtection()->setScenarios((bool)$bool); + $this->phpSheet->getProtection()->setScenarios((bool) $bool); } - /** * OBJECTPROTECT */ @@ -3433,10 +3397,9 @@ class Excel5 extends BaseReader implements IReader // bit: 0, mask 0x01; 1 = objects are protected $bool = (0x01 & self::getInt2d($recordData, 0)) >> 0; - $this->phpSheet->getProtection()->setObjects((bool)$bool); + $this->phpSheet->getProtection()->setObjects((bool) $bool); } - /** * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8) */ @@ -3455,7 +3418,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read DEFCOLWIDTH record */ @@ -3474,7 +3436,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read COLINFO record */ @@ -3525,7 +3486,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * ROW * @@ -3594,7 +3554,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read RK record * This record represents a cell that contains an RK value @@ -3641,7 +3600,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read LABELSST record * This record represents a cell that contains a string. It @@ -3727,7 +3685,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read MULRK record * This record represents a cell range containing RK value @@ -3781,7 +3738,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read NUMBER record * This record represents a cell that contains a @@ -3823,7 +3779,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read FORMULA record + perhaps a following STRING record if formula result is a string * This record contains the token array and the result of a @@ -3869,7 +3824,7 @@ class Excel5 extends BaseReader implements IReader // get the base cell, grab tExp token $baseRow = self::getInt2d($formulaStructure, 3); $baseCol = self::getInt2d($formulaStructure, 5); - $this->_baseCell = \PhpSpreadsheet\Cell::stringFromColumnIndex($baseCol). ($baseRow + 1); + $this->_baseCell = \PhpSpreadsheet\Cell::stringFromColumnIndex($baseCol) . ($baseRow + 1); } // Read cell? @@ -3953,7 +3908,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader, * which usually contains relative references. @@ -3983,7 +3937,6 @@ class Excel5 extends BaseReader implements IReader $this->sharedFormulas[$this->_baseCell] = $formula; } - /** * Read a STRING record from current stream position and advance the stream pointer to next record * This record is used for storing result from FORMULA record when it is a string, and @@ -4010,7 +3963,6 @@ class Excel5 extends BaseReader implements IReader return $value; } - /** * Read BOOLERR record * This record represents a Boolean value or error value @@ -4068,7 +4020,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read MULBLANK record * This record represents a cell range of empty cells. All @@ -4108,7 +4059,6 @@ class Excel5 extends BaseReader implements IReader // offset: 6; size 2; index to last column (not needed) } - /** * Read LABEL record * This record represents a cell that contains a string. In @@ -4160,7 +4110,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read BLANK record */ @@ -4191,7 +4140,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read MSODRAWING record */ @@ -4206,7 +4154,6 @@ class Excel5 extends BaseReader implements IReader $this->drawingData .= $recordData; } - /** * Read OBJ record */ @@ -4231,19 +4178,19 @@ class Excel5 extends BaseReader implements IReader // data: var; subrecord data // for now, we are just interested in the second subrecord containing the object type - $ftCmoType = self::getInt2d($recordData, 0); - $cbCmoSize = self::getInt2d($recordData, 2); - $otObjType = self::getInt2d($recordData, 4); - $idObjID = self::getInt2d($recordData, 6); - $grbitOpts = self::getInt2d($recordData, 6); + $ftCmoType = self::getInt2d($recordData, 0); + $cbCmoSize = self::getInt2d($recordData, 2); + $otObjType = self::getInt2d($recordData, 4); + $idObjID = self::getInt2d($recordData, 6); + $grbitOpts = self::getInt2d($recordData, 6); - $this->objs[] = array( + $this->objs[] = [ 'ftCmoType' => $ftCmoType, 'cbCmoSize' => $cbCmoSize, 'otObjType' => $otObjType, - 'idObjID' => $idObjID, - 'grbitOpts' => $grbitOpts - ); + 'idObjID' => $idObjID, + 'grbitOpts' => $grbitOpts, + ]; $this->textObjRef = $idObjID; // echo '_readObj()
'; @@ -4251,7 +4198,6 @@ class Excel5 extends BaseReader implements IReader // echo '
'; } - /** * Read WINDOW2 record */ @@ -4298,7 +4244,7 @@ class Excel5 extends BaseReader implements IReader $this->frozen = (bool) ((0x0008 & $options) >> 3); // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left - $this->phpSheet->setRightToLeft((bool)((0x0040 & $options) >> 6)); + $this->phpSheet->setRightToLeft((bool) ((0x0040 & $options) >> 6)); // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active $isActive = (bool) ((0x0400 & $options) >> 10); @@ -4351,8 +4297,8 @@ class Excel5 extends BaseReader implements IReader $grbit = self::getInt2d($recordData, 14); // decomprise grbit - $fPageLayoutView = $grbit & 0x01; - $fRulerVisible = ($grbit >> 1) & 0x01; //no support + $fPageLayoutView = $grbit & 0x01; + $fRulerVisible = ($grbit >> 1) & 0x01; //no support $fWhitespaceHidden = ($grbit >> 3) & 0x01; //no support if ($fPageLayoutView === 1) { @@ -4383,7 +4329,6 @@ class Excel5 extends BaseReader implements IReader $this->phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator); } - /** * Read PANE record */ @@ -4411,7 +4356,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read SELECTION record. There is one such record for each pane in the sheet. */ @@ -4462,16 +4406,15 @@ class Excel5 extends BaseReader implements IReader } } - private function includeCellRangeFiltered($cellRangeAddress) { $includeCellRange = true; if ($this->getReadFilter() !== null) { $includeCellRange = false; $rangeBoundaries = \PhpSpreadsheet\Cell::getRangeBoundaries($cellRangeAddress); - $rangeBoundaries[1][0]++; - for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; $row++) { - for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; $column++) { + ++$rangeBoundaries[1][0]; + for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; ++$row) { + for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; ++$column) { if ($this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) { $includeCellRange = true; break 2; @@ -4479,10 +4422,10 @@ class Excel5 extends BaseReader implements IReader } } } + return $includeCellRange; } - /** * MERGEDCELLS * @@ -4511,7 +4454,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read HYPERLINK record */ @@ -4683,7 +4625,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read DATAVALIDATIONS record */ @@ -4696,7 +4637,6 @@ class Excel5 extends BaseReader implements IReader $this->pos += 4 + $length; } - /** * Read DATAVALIDATION record */ @@ -4873,9 +4813,9 @@ class Excel5 extends BaseReader implements IReader $objValidation = $this->phpSheet->getCell($coordinate)->getDataValidation(); $objValidation->setType($type); $objValidation->setErrorStyle($errorStyle); - $objValidation->setAllowBlank((bool)$allowBlank); - $objValidation->setShowInputMessage((bool)$showInputMessage); - $objValidation->setShowErrorMessage((bool)$showErrorMessage); + $objValidation->setAllowBlank((bool) $allowBlank); + $objValidation->setShowInputMessage((bool) $showInputMessage); + $objValidation->setShowErrorMessage((bool) $showErrorMessage); $objValidation->setShowDropDown(!$suppressDropDown); $objValidation->setOperator($operator); $objValidation->setErrorTitle($errorTitle); @@ -4926,7 +4866,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read SHEETPROTECTION record (FEATHEADR) */ @@ -5025,7 +4964,6 @@ class Excel5 extends BaseReader implements IReader // offset: 21; size: 2; not used } - /** * Read RANGEPROTECTION record * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification, @@ -5062,7 +5000,7 @@ class Excel5 extends BaseReader implements IReader $offset += 6; // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record) - $cellRanges = array(); + $cellRanges = []; for ($i = 0; $i < $cref; ++$i) { try { $cellRange = $this->readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8)); @@ -5088,7 +5026,6 @@ class Excel5 extends BaseReader implements IReader } } - /** * Read IMDATA record */ @@ -5138,7 +5075,7 @@ class Excel5 extends BaseReader implements IReader // var_dump($bcBitCount); $rgbString = substr($iData, 12); - $rgbTriples = array(); + $rgbTriples = []; while (strlen($rgbString) > 0) { $rgbTriples[] = unpack('Cb/Cg/Cr', $rgbString); $rgbString = substr($rgbString, 3); @@ -5166,7 +5103,6 @@ class Excel5 extends BaseReader implements IReader // getSplicedRecordData() takes care of moving current position in data stream } - /** * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented. @@ -5200,7 +5136,7 @@ class Excel5 extends BaseReader implements IReader // 0xF003 MsofbtSpgrContainer // 0xF004 MsofbtSpContainer // 0xF00D MsofbtClientTextbox - $validSplitPoints = array(0xF003, 0xF004, 0xF00D); // add identifiers if we find more + $validSplitPoints = [0xF003, 0xF004, 0xF00D]; // add identifiers if we find more $splitPoint = self::getInt2d($recordData, 2); if (in_array($splitPoint, $validSplitPoints)) { @@ -5215,7 +5151,6 @@ class Excel5 extends BaseReader implements IReader $this->pos += 4 + $length; } - /** * Reads a record from current position in data stream and continues reading data as long as CONTINUE * records are found. Splices the record data pieces and returns the combined string as if record data @@ -5227,7 +5162,7 @@ class Excel5 extends BaseReader implements IReader private function getSplicedRecordData() { $data = ''; - $spliceOffsets = array(); + $spliceOffsets = []; $i = 0; $spliceOffsets[0] = 0; @@ -5247,15 +5182,14 @@ class Excel5 extends BaseReader implements IReader $nextIdentifier = self::getInt2d($this->data, $this->pos); } while ($nextIdentifier == self::XLS_TYPE_CONTINUE); - $splicedData = array( + $splicedData = [ 'recordData' => $data, 'spliceOffsets' => $spliceOffsets, - ); + ]; return $splicedData; } - /** * Convert formula structure into human readable Excel formula like 'A3+A5*5' * @@ -5293,7 +5227,6 @@ class Excel5 extends BaseReader implements IReader return $this->getFormulaFromData($formulaData, $additionalData, $baseCell); } - /** * Take formula data and additional data for formula and return human readable formula * @@ -5305,7 +5238,7 @@ class Excel5 extends BaseReader implements IReader private function getFormulaFromData($formulaData, $additionalData = '', $baseCell = 'A1') { // start parsing the formula data - $tokens = array(); + $tokens = []; while (strlen($formulaData) > 0 and $token = $this->getNextToken($formulaData, $baseCell)) { $tokens[] = $token; @@ -5320,7 +5253,6 @@ class Excel5 extends BaseReader implements IReader return $formulaString; } - /** * Take array of tokens together with additional data for formula and return human readable formula * @@ -5336,7 +5268,7 @@ class Excel5 extends BaseReader implements IReader return ''; } - $formulaStrings = array(); + $formulaStrings = []; foreach ($tokens as $token) { // initialize spaces $space0 = isset($space0) ? $space0 : ''; // spaces before next token, not tParen @@ -5417,22 +5349,22 @@ class Excel5 extends BaseReader implements IReader case 'tFuncV': // function with variable number of arguments if ($token['data']['function'] != '') { // normal function - $ops = array(); // array of operators + $ops = []; // array of operators for ($i = 0; $i < $token['data']['args']; ++$i) { $ops[] = array_pop($formulaStrings); } $ops = array_reverse($ops); - $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ")"; + $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ')'; unset($space0, $space1); } else { // add-in function - $ops = array(); // array of operators + $ops = []; // array of operators for ($i = 0; $i < $token['data']['args'] - 1; ++$i) { $ops[] = array_pop($formulaStrings); } $ops = array_reverse($ops); $function = array_pop($formulaStrings); - $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ")"; + $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ')'; unset($space0, $space1); } break; @@ -5484,14 +5416,13 @@ class Excel5 extends BaseReader implements IReader return $formulaString; } - /** * Fetch next token from binary formula data * * @param string Formula data * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas - * @return array * @throws Exception + * @return array */ private function getNextToken($formulaData, $baseCell = 'A1') { @@ -5591,8 +5522,8 @@ class Excel5 extends BaseReader implements IReader $data = '%'; break; case 0x15: // parenthesis - $name = 'tParen'; - $size = 1; + $name = 'tParen'; + $size = 1; $data = null; break; case 0x16: // missing argument @@ -5670,7 +5601,7 @@ class Excel5 extends BaseReader implements IReader // offset: 3; size: 1; number of inserted spaces/carriage returns $spacecount = ord($formulaData[3]); - $data = array('spacetype' => $spacetype, 'spacecount' => $spacecount); + $data = ['spacetype' => $spacetype, 'spacecount' => $spacecount]; break; default: throw new Exception('Unrecognized attribute flag in tAttr token'); @@ -5700,7 +5631,7 @@ class Excel5 extends BaseReader implements IReader $name = 'tNum'; $size = 9; $data = self::extractNumber(substr($formulaData, 1)); - $data = str_replace(',', '.', (string)$data); // in case non-English locale + $data = str_replace(',', '.', (string) $data); // in case non-English locale break; case 0x20: // array constant case 0x40: @@ -6361,7 +6292,7 @@ class Excel5 extends BaseReader implements IReader throw new Exception('Unrecognized function in formula'); break; } - $data = array('function' => $function, 'args' => $args); + $data = ['function' => $function, 'args' => $args]; break; case 0x22: // function with variable number of arguments case 0x42: @@ -6641,7 +6572,7 @@ class Excel5 extends BaseReader implements IReader throw new Exception('Unrecognized function in formula'); break; } - $data = array('function' => $function, 'args' => $args); + $data = ['function' => $function, 'args' => $args]; break; case 0x23: // index to defined name case 0x43: @@ -6764,15 +6695,14 @@ class Excel5 extends BaseReader implements IReader break; } - return array( + return [ 'id' => $id, 'name' => $name, 'size' => $size, 'data' => $data, - ); + ]; } - /** * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2' * section 3.3.4 @@ -6801,7 +6731,6 @@ class Excel5 extends BaseReader implements IReader return $column . $row; } - /** * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column * to indicate offsets from a base cell @@ -6844,15 +6773,14 @@ class Excel5 extends BaseReader implements IReader return $column . $row; } - /** * Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1' * always fixed range * section 2.5.14 * * @param string $subData - * @return string * @throws Exception + * @return string */ private function readBIFF5CellRangeAddressFixed($subData) { @@ -6880,18 +6808,18 @@ class Excel5 extends BaseReader implements IReader if ($fr == $lr and $fc == $lc) { return "$fc$fr"; } + return "$fc$fr:$lc$lr"; } - /** * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1' * always fixed range * section 2.5.14 * * @param string $subData - * @return string * @throws Exception + * @return string */ private function readBIFF8CellRangeAddressFixed($subData) { @@ -6919,10 +6847,10 @@ class Excel5 extends BaseReader implements IReader if ($fr == $lr and $fc == $lc) { return "$fc$fr"; } + return "$fc$fr:$lc$lr"; } - /** * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6' * there are flags indicating whether column/row index is relative @@ -6975,7 +6903,6 @@ class Excel5 extends BaseReader implements IReader return "$fc$fr:$lc$lr"; } - /** * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column * to indicate offsets from a base cell @@ -7058,7 +6985,6 @@ class Excel5 extends BaseReader implements IReader return "$fc$fr:$lc$lr"; } - /** * Read BIFF8 cell range address list * section 2.5.15 @@ -7068,7 +6994,7 @@ class Excel5 extends BaseReader implements IReader */ private function readBIFF8CellRangeAddressList($subData) { - $cellRangeAddresses = array(); + $cellRangeAddresses = []; // offset: 0; size: 2; number of the following cell range addresses $nm = self::getInt2d($subData, 0); @@ -7080,13 +7006,12 @@ class Excel5 extends BaseReader implements IReader $offset += 8; } - return array( + return [ 'size' => 2 + 8 * $nm, 'cellRangeAddresses' => $cellRangeAddresses, - ); + ]; } - /** * Read BIFF5 cell range address list * section 2.5.15 @@ -7096,7 +7021,7 @@ class Excel5 extends BaseReader implements IReader */ private function readBIFF5CellRangeAddressList($subData) { - $cellRangeAddresses = array(); + $cellRangeAddresses = []; // offset: 0; size: 2; number of the following cell range addresses $nm = self::getInt2d($subData, 0); @@ -7108,13 +7033,12 @@ class Excel5 extends BaseReader implements IReader $offset += 6; } - return array( + return [ 'size' => 2 + 6 * $nm, 'cellRangeAddresses' => $cellRangeAddresses, - ); + ]; } - /** * Get a sheet range like Sheet1:Sheet3 from REF index * Note: If there is only one sheet in the range, one gets e.g Sheet1 @@ -7122,8 +7046,8 @@ class Excel5 extends BaseReader implements IReader * in which case an Exception is thrown * * @param int $index - * @return string|false * @throws Exception + * @return string|false */ private function readSheetRangeByRefIndex($index) { @@ -7167,10 +7091,10 @@ class Excel5 extends BaseReader implements IReader break; } } + return false; } - /** * read BIFF8 constant value array from array data * returns e.g. array('value' => '{1,2;3,4}', 'size' => 40} @@ -7190,9 +7114,9 @@ class Excel5 extends BaseReader implements IReader $arrayData = substr($arrayData, 3); // offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values - $matrixChunks = array(); + $matrixChunks = []; for ($r = 1; $r <= $nr + 1; ++$r) { - $items = array(); + $items = []; for ($c = 1; $c <= $nc + 1; ++$c) { $constant = self::_readBIFF8Constant($arrayData); $items[] = $constant['value']; @@ -7203,13 +7127,12 @@ class Excel5 extends BaseReader implements IReader } $matrix = '{' . implode(';', $matrixChunks) . '}'; - return array( + return [ 'value' => $matrix, 'size' => $size, - ); + ]; } - /** * read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value' * section 2.5.7 @@ -7254,13 +7177,13 @@ class Excel5 extends BaseReader implements IReader $size = 9; break; } - return array( + + return [ 'value' => $value, 'size' => $size, - ); + ]; } - /** * Extract RGB color * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.4 @@ -7282,10 +7205,9 @@ class Excel5 extends BaseReader implements IReader // HEX notation, e.g. 'FF00FC' $rgb = sprintf('%02X%02X%02X', $r, $g, $b); - return array('rgb' => $rgb); + return ['rgb' => $rgb]; } - /** * Read byte string (8-bit string length) * OpenOffice documentation: 2.5.2 @@ -7301,13 +7223,12 @@ class Excel5 extends BaseReader implements IReader // offset: 1: size: var; character array (8-bit characters) $value = $this->decodeCodepage(substr($subData, 1, $ln)); - return array( + return [ 'value' => $value, 'size' => 1 + $ln, // size in bytes of data structure - ); + ]; } - /** * Read byte string (16-bit string length) * OpenOffice documentation: 2.5.2 @@ -7324,13 +7245,12 @@ class Excel5 extends BaseReader implements IReader $value = $this->decodeCodepage(substr($subData, 2)); //return $string; - return array( + return [ 'value' => $value, 'size' => 2 + $ln, // size in bytes of data structure - ); + ]; } - /** * Extracts an Excel Unicode short string (8-bit string length) * OpenOffice documentation: 2.5.3 @@ -7354,7 +7274,6 @@ class Excel5 extends BaseReader implements IReader return $string; } - /** * Extracts an Excel Unicode long string (16-bit string length) * OpenOffice documentation: 2.5.3 @@ -7378,7 +7297,6 @@ class Excel5 extends BaseReader implements IReader return $string; } - /** * Read Unicode string with no string length field, but with known character count * this function is under construction, needs to support rich text, and Asian phonetic settings @@ -7407,13 +7325,12 @@ class Excel5 extends BaseReader implements IReader // needs to be fixed $value = self::encodeUTF16(substr($subData, 1, $isCompressed ? $characterCount : 2 * $characterCount), $isCompressed); - return array( + return [ 'value' => $value, 'size' => $isCompressed ? 1 + $characterCount : 1 + 2 * $characterCount, // the size in bytes including the option flags - ); + ]; } - /** * Convert UTF-8 string to string surounded by double quotes. Used for explicit string tokens in formulas. * Example: hello"world --> "hello""world" @@ -7426,7 +7343,6 @@ class Excel5 extends BaseReader implements IReader return '"' . str_replace('"', '""', $value) . '"'; } - /** * Reads first 8 bytes of a string and return IEEE 754 float * @@ -7456,7 +7372,6 @@ class Excel5 extends BaseReader implements IReader return $value; } - private static function getIEEE754($rknum) { if (($rknum & 0x02) != 0) { @@ -7470,7 +7385,7 @@ class Excel5 extends BaseReader implements IReader $sign = ($rknum & 0x80000000) >> 31; $exp = ($rknum & 0x7ff00000) >> 20; $mantissa = (0x100000 | ($rknum & 0x000ffffc)); - $value = $mantissa / pow(2, (20- ($exp - 1023))); + $value = $mantissa / pow(2, (20 - ($exp - 1023))); if ($sign) { $value = -1 * $value; } @@ -7479,10 +7394,10 @@ class Excel5 extends BaseReader implements IReader if (($rknum & 0x01) != 0) { $value /= 100; } + return $value; } - /** * Get UTF-8 string from (compressed or uncompressed) UTF-16 string * @@ -7499,7 +7414,6 @@ class Excel5 extends BaseReader implements IReader return \PhpSpreadsheet\Shared\StringHelper::convertEncoding($string, 'UTF-8', 'UTF-16LE'); } - /** * Convert UTF-16 string in compressed notation to uncompressed form. Only used for BIFF8. * @@ -7517,7 +7431,6 @@ class Excel5 extends BaseReader implements IReader return $uncompressedString; } - /** * Convert string to UTF-8. Only used for BIFF5. * @@ -7529,7 +7442,6 @@ class Excel5 extends BaseReader implements IReader return \PhpSpreadsheet\Shared\StringHelper::convertEncoding($string, 'UTF-8', $this->codepage); } - /** * Read 16-bit unsigned integer * @@ -7539,10 +7451,9 @@ class Excel5 extends BaseReader implements IReader */ public static function getInt2d($data, $pos) { - return ord($data[$pos]) | (ord($data[$pos+1]) << 8); + return ord($data[$pos]) | (ord($data[$pos + 1]) << 8); } - /** * Read 32-bit signed integer * @@ -7562,9 +7473,9 @@ class Excel5 extends BaseReader implements IReader } else { $_ord_24 = ($_or_24 & 127) << 24; } - return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | $_ord_24; - } + return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; + } private function parseRichText($is = '') { diff --git a/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF5.php b/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF5.php index 9c0ad529..68f78cef 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF5.php +++ b/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF5.php @@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5\Color; class BIFF5 { - protected static $map = array( + protected static $map = [ 0x08 => '000000', 0x09 => 'FFFFFF', 0x0A => 'FF0000', @@ -61,7 +61,7 @@ class BIFF5 0x3D => '85396A', 0x3E => '4A3285', 0x3F => '424242', - ); + ]; /** * Map color array from BIFF5 built-in color index @@ -72,8 +72,9 @@ class BIFF5 public static function lookup($color) { if (isset(self::$map[$color])) { - return array('rgb' => self::$map[$color]); + return ['rgb' => self::$map[$color]]; } - return array('rgb' => '000000'); + + return ['rgb' => '000000']; } } diff --git a/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF8.php b/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF8.php index b7d04c1d..af1ed559 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF8.php +++ b/src/PhpSpreadsheet/Reader/Excel5/Color/BIFF8.php @@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5\Color; class BIFF8 { - protected static $map = array( + protected static $map = [ 0x08 => '000000', 0x09 => 'FFFFFF', 0x0A => 'FF0000', @@ -61,9 +61,9 @@ class BIFF8 0x3D => '993366', 0x3E => '333399', 0x3F => '333333', - ); + ]; - /** + /** * Map color array from BIFF8 built-in color index * * @param int $color @@ -72,8 +72,9 @@ class BIFF8 public static function lookup($color) { if (isset(self::$map[$color])) { - return array('rgb' => self::$map[$color]); + return ['rgb' => self::$map[$color]]; } - return array('rgb' => '000000'); + + return ['rgb' => '000000']; } } diff --git a/src/PhpSpreadsheet/Reader/Excel5/Color/BuiltIn.php b/src/PhpSpreadsheet/Reader/Excel5/Color/BuiltIn.php index ed8132e2..610b40f5 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/Color/BuiltIn.php +++ b/src/PhpSpreadsheet/Reader/Excel5/Color/BuiltIn.php @@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5\Color; class BuiltIn { - protected static $map = array( + protected static $map = [ 0x00 => '000000', 0x01 => 'FFFFFF', 0x02 => 'FF0000', @@ -15,7 +15,7 @@ class BuiltIn 0x07 => '00FFFF', 0x40 => '000000', // system window text color 0x41 => 'FFFFFF', // system window background color - ); + ]; /** * Map built-in color to RGB value @@ -26,8 +26,9 @@ class BuiltIn public static function lookup($color) { if (isset(self::$map[$color])) { - return array('rgb' => self::$map[$color]); + return ['rgb' => self::$map[$color]]; } - return array('rgb' => '000000'); + + return ['rgb' => '000000']; } } diff --git a/src/PhpSpreadsheet/Reader/Excel5/ErrorCode.php b/src/PhpSpreadsheet/Reader/Excel5/ErrorCode.php index 7c36baec..d3e9f877 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/ErrorCode.php +++ b/src/PhpSpreadsheet/Reader/Excel5/ErrorCode.php @@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Reader\Excel5; class ErrorCode { - protected static $map = array( + protected static $map = [ 0x00 => '#NULL!', 0x07 => '#DIV/0!', 0x0F => '#VALUE!', @@ -12,19 +12,20 @@ class ErrorCode 0x1D => '#NAME?', 0x24 => '#NUM!', 0x2A => '#N/A', - ); + ]; /** * Map error code, e.g. '#N/A' * * @param int $code - * @return string|boolean + * @return string|bool */ public static function lookup($code) { if (isset(self::$map[$code])) { return self::$map[$code]; } + return false; } } diff --git a/src/PhpSpreadsheet/Reader/Excel5/Escher.php b/src/PhpSpreadsheet/Reader/Excel5/Escher.php index bc0f7943..22c413c9 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/Escher.php +++ b/src/PhpSpreadsheet/Reader/Excel5/Escher.php @@ -26,24 +26,24 @@ namespace PhpSpreadsheet\Reader\Excel5; */ class Escher { - const DGGCONTAINER = 0xF000; - const BSTORECONTAINER = 0xF001; - const DGCONTAINER = 0xF002; - const SPGRCONTAINER = 0xF003; - const SPCONTAINER = 0xF004; - const DGG = 0xF006; - const BSE = 0xF007; - const DG = 0xF008; - const SPGR = 0xF009; - const SP = 0xF00A; - const OPT = 0xF00B; - const CLIENTTEXTBOX = 0xF00D; - const CLIENTANCHOR = 0xF010; - const CLIENTDATA = 0xF011; - const BLIPJPEG = 0xF01D; - const BLIPPNG = 0xF01E; - const SPLITMENUCOLORS = 0xF11E; - const TERTIARYOPT = 0xF122; + const DGGCONTAINER = 0xF000; + const BSTORECONTAINER = 0xF001; + const DGCONTAINER = 0xF002; + const SPGRCONTAINER = 0xF003; + const SPCONTAINER = 0xF004; + const DGG = 0xF006; + const BSE = 0xF007; + const DG = 0xF008; + const SPGR = 0xF009; + const SP = 0xF00A; + const OPT = 0xF00B; + const CLIENTTEXTBOX = 0xF00D; + const CLIENTANCHOR = 0xF010; + const CLIENTDATA = 0xF011; + const BLIPJPEG = 0xF01D; + const BLIPPNG = 0xF01E; + const SPLITMENUCOLORS = 0xF11E; + const TERTIARYOPT = 0xF122; /** * Escher stream data (binary) @@ -201,7 +201,7 @@ class Escher // record is a container, read contents $dggContainer = new \PhpSpreadsheet\Shared\Escher\DggContainer(); $this->object->setDggContainer($dggContainer); - $reader = new Escher($dggContainer); + $reader = new self($dggContainer); $reader->load($recordData); } @@ -231,7 +231,7 @@ class Escher // record is a container, read contents $bstoreContainer = new \PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer(); $this->object->setBstoreContainer($bstoreContainer); - $reader = new Escher($bstoreContainer); + $reader = new self($bstoreContainer); $reader->load($recordData); } @@ -324,7 +324,7 @@ class Escher $pos += 16; // 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); $pos += 16; } @@ -485,7 +485,7 @@ class Escher $this->object->addChild($spgrContainer); } - $reader = new Escher($spgrContainer); + $reader = new self($spgrContainer); $escher = $reader->load($recordData); } @@ -505,7 +505,7 @@ class Escher $this->pos += 8 + $length; // record is a container, read contents - $reader = new Escher($spContainer); + $reader = new self($spContainer); $escher = $reader->load($recordData); } diff --git a/src/PhpSpreadsheet/Reader/Excel5/MD5.php b/src/PhpSpreadsheet/Reader/Excel5/MD5.php index e2dd51b0..607a0781 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/MD5.php +++ b/src/PhpSpreadsheet/Reader/Excel5/MD5.php @@ -59,7 +59,7 @@ class MD5 public function getContext() { $s = ''; - foreach (array('a', 'b', 'c', 'd') as $i) { + foreach (['a', 'b', 'c', 'd'] as $i) { $v = $this->{$i}; $s .= chr($v & 0xff); $s .= chr(($v >> 8) & 0xff); @@ -84,10 +84,10 @@ class MD5 $C = $this->c; $D = $this->d; - $F = ['self','f']; - $G = ['self','g']; - $H = ['self','h']; - $I = ['self','i']; + $F = ['self', 'f']; + $G = ['self', 'g']; + $H = ['self', 'h']; + $I = ['self', 'i']; /* ROUND 1 */ self::step($F, $A, $B, $C, $D, $words[0], 7, 0xd76aa478); @@ -169,22 +169,22 @@ class MD5 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) { - 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) { - 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) { - 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) @@ -196,7 +196,8 @@ class MD5 private static function rotate($decimal, $bits) { - $binary = str_pad(decbin($decimal), 32, "0", STR_PAD_LEFT); - return bindec(substr($binary, $bits).substr($binary, 0, $bits)); + $binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT); + + return bindec(substr($binary, $bits) . substr($binary, 0, $bits)); } } diff --git a/src/PhpSpreadsheet/Reader/Excel5/RC4.php b/src/PhpSpreadsheet/Reader/Excel5/RC4.php index e3ff31d2..994cb664 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/RC4.php +++ b/src/PhpSpreadsheet/Reader/Excel5/RC4.php @@ -27,7 +27,7 @@ namespace PhpSpreadsheet\Reader\Excel5; class RC4 { // Context - protected $s = array(); + protected $s = []; protected $i = 0; protected $j = 0; @@ -40,12 +40,12 @@ class RC4 { $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->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; $t = $this->s[$this->i]; $this->s[$this->i] = $this->s[$this->j]; @@ -64,7 +64,7 @@ class RC4 public function RC4($data) { $len = strlen($data); - for ($c = 0; $c < $len; $c++) { + for ($c = 0; $c < $len; ++$c) { $this->i = ($this->i + 1) % 256; $this->j = ($this->j + $this->s[$this->i]) % 256; $t = $this->s[$this->i]; @@ -75,6 +75,7 @@ class RC4 $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]); } + return $data; } } diff --git a/src/PhpSpreadsheet/Reader/Excel5/Style/Border.php b/src/PhpSpreadsheet/Reader/Excel5/Style/Border.php index 5ee7d886..50faf6ae 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/Style/Border.php +++ b/src/PhpSpreadsheet/Reader/Excel5/Style/Border.php @@ -2,11 +2,11 @@ namespace PhpSpreadsheet\Reader\Excel5\Style; -use \PhpSpreadsheet\Style\Border as StyleBorder; +use PhpSpreadsheet\Style\Border as StyleBorder; class Border { - protected static $map = array( + protected static $map = [ 0x00 => StyleBorder::BORDER_NONE, 0x01 => StyleBorder::BORDER_THIN, 0x02 => StyleBorder::BORDER_MEDIUM, @@ -21,7 +21,7 @@ class Border 0x0B => StyleBorder::BORDER_DASHDOTDOT, 0x0C => StyleBorder::BORDER_MEDIUMDASHDOTDOT, 0x0D => StyleBorder::BORDER_SLANTDASHDOT, - ); + ]; /** * Map border style @@ -35,6 +35,7 @@ class Border if (isset(self::$map[$index])) { return self::$map[$index]; } + return StyleBorder::BORDER_NONE; } } diff --git a/src/PhpSpreadsheet/Reader/Excel5/Style/FillPattern.php b/src/PhpSpreadsheet/Reader/Excel5/Style/FillPattern.php index 8a3d5457..1a34b54e 100644 --- a/src/PhpSpreadsheet/Reader/Excel5/Style/FillPattern.php +++ b/src/PhpSpreadsheet/Reader/Excel5/Style/FillPattern.php @@ -2,11 +2,11 @@ namespace PhpSpreadsheet\Reader\Excel5\Style; -use \PhpSpreadsheet\Style\Fill; +use PhpSpreadsheet\Style\Fill; class FillPattern { - protected static $map = array( + protected static $map = [ 0x00 => Fill::FILL_NONE, 0x01 => Fill::FILL_SOLID, 0x02 => Fill::FILL_PATTERN_MEDIUMGRAY, @@ -26,7 +26,7 @@ class FillPattern 0x10 => Fill::FILL_PATTERN_LIGHTTRELLIS, 0x11 => Fill::FILL_PATTERN_GRAY125, 0x12 => Fill::FILL_PATTERN_GRAY0625, - ); + ]; /** * Get fill pattern from index @@ -40,6 +40,7 @@ class FillPattern if (isset(self::$map[$index])) { return self::$map[$index]; } + return Fill::FILL_NONE; } } diff --git a/src/PhpSpreadsheet/Reader/Gnumeric.php b/src/PhpSpreadsheet/Reader/Gnumeric.php index 000a332b..08591480 100644 --- a/src/PhpSpreadsheet/Reader/Gnumeric.php +++ b/src/PhpSpreadsheet/Reader/Gnumeric.php @@ -31,14 +31,14 @@ class Gnumeric extends BaseReader implements IReader * * @var array */ - private $styles = array(); + private $styles = []; /** * Shared Expressions * * @var array */ - private $expressions = array(); + private $expressions = []; private $referenceHelper = null; @@ -47,7 +47,7 @@ class Gnumeric extends BaseReader implements IReader */ public function __construct() { - $this->readFilter = new DefaultReadFilter(); + $this->readFilter = new DefaultReadFilter(); $this->referenceHelper = \PhpSpreadsheet\ReferenceHelper::getInstance(); } @@ -55,19 +55,19 @@ class Gnumeric extends BaseReader implements IReader * Can the current IReader read the file? * * @param string $pFilename - * @return boolean * @throws Exception + * @return bool */ public function canRead($pFilename) { // Check if file exists 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 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) @@ -75,7 +75,7 @@ class Gnumeric extends BaseReader implements IReader $data = fread($fh, 2); fclose($fh); - if ($data != chr(0x1F).chr(0x8B)) { + if ($data != chr(0x1F) . chr(0x8B)) { return false; } @@ -92,14 +92,14 @@ class Gnumeric extends BaseReader implements IReader { // Check if file exists 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->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); - $worksheetNames = array(); + $worksheetNames = []; while ($xml->read()) { if ($xml->name == 'gnm:SheetName' && $xml->nodeType == XMLReader::ELEMENT) { $xml->read(); // Move onto the value node @@ -123,23 +123,23 @@ class Gnumeric extends BaseReader implements IReader { // Check if file exists 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->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); - $worksheetInfo = array(); + $worksheetInfo = []; while ($xml->read()) { if ($xml->name == 'gnm:Sheet' && $xml->nodeType == XMLReader::ELEMENT) { - $tmpInfo = array( + $tmpInfo = [ 'worksheetName' => '', 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, - ); + ]; while ($xml->read()) { if ($xml->name == 'gnm:Name' && $xml->nodeType == XMLReader::ELEMENT) { @@ -173,6 +173,7 @@ class Gnumeric extends BaseReader implements IReader } gzclose($file); } + return $data; } @@ -180,8 +181,8 @@ class Gnumeric extends BaseReader implements IReader * Loads PhpSpreadsheet from file * * @param string $pFilename - * @return PhpSpreadsheet * @throws Exception + * @return PhpSpreadsheet */ public function load($pFilename) { @@ -197,14 +198,14 @@ class Gnumeric extends BaseReader implements IReader * * @param string $pFilename * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return PhpSpreadsheet * @throws Exception + * @return PhpSpreadsheet */ public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) { // Check if file exists 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'); @@ -231,7 +232,7 @@ class Gnumeric extends BaseReader implements IReader $officeDocMetaXML = $officeDocXML->meta; foreach ($officeDocMetaXML as $officePropertyData) { - $officePropertyDC = array(); + $officePropertyDC = []; if (isset($namespacesMeta['dc'])) { $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); } @@ -258,7 +259,7 @@ class Gnumeric extends BaseReader implements IReader break; } } - $officePropertyMeta = array(); + $officePropertyMeta = []; if (isset($namespacesMeta['meta'])) { $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); } @@ -407,11 +408,11 @@ class Gnumeric extends BaseReader implements IReader $type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA; if ($ExprID > '') { if (((string) $cell) > '') { - $this->expressions[$ExprID] = array( - 'column' => $cellAttributes->Col, - 'row' => $cellAttributes->Row, - 'formula' => (string) $cell - ); + $this->expressions[$ExprID] = [ + 'column' => $cellAttributes->Col, + 'row' => $cellAttributes->Row, + 'formula' => (string) $cell, + ]; // echo 'NEW EXPRESSION ', $ExprID,'
'; } else { $expression = $this->expressions[$ExprID]; @@ -452,7 +453,7 @@ class Gnumeric extends BaseReader implements IReader 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))) { @@ -460,7 +461,7 @@ class Gnumeric extends BaseReader implements IReader $commentAttributes = $comment->attributes(); // Only comment objects are handled at the moment 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); $endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow']; $endRow += 1; - $cellRange = $startColumn.$startRow.':'.$endColumn.$endRow; + $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow; // echo $cellRange,'
'; $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 if ((!$this->readDataOnly) || (\PhpSpreadsheet\Shared\Date::isDateTimeFormatCode((string) $styleAttributes['Format']))) { - $styleArray = array(); + $styleArray = []; $styleArray['numberformat']['code'] = (string) $styleAttributes['Format']; // If readDataOnly is false, we set all formatting information if (!$this->readDataOnly) { @@ -530,15 +531,15 @@ class Gnumeric extends BaseReader implements IReader $styleArray['alignment']['wrap'] = ($styleAttributes['WrapText'] == '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; - $RGB = self::parseGnumericColour($styleAttributes["Back"]); - $shade = $styleAttributes["Shade"]; + $RGB = self::parseGnumericColour($styleAttributes['Back']); + $shade = $styleAttributes['Shade']; if (($RGB != '000000') || ($shade != '0')) { $styleArray['fill']['color']['rgb'] = $styleArray['fill']['startcolor']['rgb'] = $RGB; - $RGB2 = self::parseGnumericColour($styleAttributes["PatternColor"]); + $RGB2 = self::parseGnumericColour($styleAttributes['PatternColor']); $styleArray['fill']['endcolor']['rgb'] = $RGB2; switch ($shade) { case '1': @@ -677,19 +678,19 @@ class Gnumeric extends BaseReader implements IReader if ((!$this->readDataOnly) && (isset($sheet->Cols))) { // Column Widths $columnAttributes = $sheet->Cols->attributes(); - $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; + $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; $c = 0; foreach ($sheet->Cols->ColInfo as $columnOverride) { $columnAttributes = $columnOverride->attributes(); $column = $columnAttributes['No']; - $columnWidth = $columnAttributes['Unit'] / 5.4; + $columnWidth = $columnAttributes['Unit'] / 5.4; $hidden = ((isset($columnAttributes['Hidden'])) && ($columnAttributes['Hidden'] == '1')) ? true : false; $columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1; while ($c < $column) { $spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setWidth($defaultWidth); ++$c; } - while (($c < ($column+$columnCount)) && ($c <= $maxCol)) { + while (($c < ($column + $columnCount)) && ($c <= $maxCol)) { $spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setWidth($columnWidth); if ($hidden) { $spreadsheet->getActiveSheet()->getColumnDimension(\PhpSpreadsheet\Cell::stringFromColumnIndex($c))->setVisible(false); @@ -719,7 +720,7 @@ class Gnumeric extends BaseReader implements IReader ++$r; $spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); } - while (($r < ($row+$rowCount)) && ($r < $maxRow)) { + while (($r < ($row + $rowCount)) && ($r < $maxRow)) { ++$r; $spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight); if ($hidden) { @@ -742,7 +743,7 @@ class Gnumeric extends BaseReader implements IReader } } - $worksheetID++; + ++$worksheetID; } // Loop through definedNames (global named ranges) @@ -769,12 +770,12 @@ class Gnumeric extends BaseReader implements IReader private static function parseBorderAttributes($borderAttributes) { - $styleArray = array(); - if (isset($borderAttributes["Color"])) { - $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes["Color"]); + $styleArray = []; + if (isset($borderAttributes['Color'])) { + $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']); } - switch ($borderAttributes["Style"]) { + switch ($borderAttributes['Style']) { case '0': $styleArray['style'] = \PhpSpreadsheet\Style\Border::BORDER_NONE; break; @@ -818,6 +819,7 @@ class Gnumeric extends BaseReader implements IReader $styleArray['style'] = \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHDOTDOT; break; } + return $styleArray; } @@ -835,6 +837,7 @@ class Gnumeric extends BaseReader implements IReader $gnmR = substr(str_pad($gnmR, 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); + return $gnmR . $gnmG . $gnmB; } } diff --git a/src/PhpSpreadsheet/Reader/HTML.php b/src/PhpSpreadsheet/Reader/HTML.php index 323250fe..2f85b977 100644 --- a/src/PhpSpreadsheet/Reader/HTML.php +++ b/src/PhpSpreadsheet/Reader/HTML.php @@ -27,7 +27,6 @@ namespace PhpSpreadsheet\Reader; /** PhpSpreadsheet root directory */ class HTML extends BaseReader implements IReader { - /** * Input encoding * @@ -47,64 +46,64 @@ class HTML extends BaseReader implements IReader * * @var array */ - protected $formats = array( - 'h1' => array( - 'font' => array( + protected $formats = [ + 'h1' => [ + 'font' => [ 'bold' => true, 'size' => 24, - ), - ), // Bold, 24pt - 'h2' => array( - 'font' => array( + ], + ], // Bold, 24pt + 'h2' => [ + 'font' => [ 'bold' => true, 'size' => 18, - ), - ), // Bold, 18pt - 'h3' => array( - 'font' => array( + ], + ], // Bold, 18pt + 'h3' => [ + 'font' => [ 'bold' => true, 'size' => 13.5, - ), - ), // Bold, 13.5pt - 'h4' => array( - 'font' => array( + ], + ], // Bold, 13.5pt + 'h4' => [ + 'font' => [ 'bold' => true, 'size' => 12, - ), - ), // Bold, 12pt - 'h5' => array( - 'font' => array( + ], + ], // Bold, 12pt + 'h5' => [ + 'font' => [ 'bold' => true, 'size' => 10, - ), - ), // Bold, 10pt - 'h6' => array( - 'font' => array( + ], + ], // Bold, 10pt + 'h6' => [ + 'font' => [ 'bold' => true, 'size' => 7.5, - ), - ), // Bold, 7.5pt - 'a' => array( - 'font' => array( + ], + ], // Bold, 7.5pt + 'a' => [ + 'font' => [ 'underline' => true, - 'color' => array( + 'color' => [ 'argb' => \PhpSpreadsheet\Style\Color::COLOR_BLUE, - ), - ), - ), // Blue underlined - 'hr' => array( - 'borders' => array( - 'bottom' => array( + ], + ], + ], // Blue underlined + 'hr' => [ + 'borders' => [ + 'bottom' => [ 'style' => \PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => array( + 'color' => [ \PhpSpreadsheet\Style\Color::COLOR_BLACK, - ), - ), - ), - ), // Bottom border - ); + ], + ], + ], + ], // Bottom border + ]; - protected $rowspan = array(); + protected $rowspan = []; /** * 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 * - * @return boolean + * @return bool */ protected function isValidFormat() { @@ -135,8 +134,8 @@ class HTML extends BaseReader implements IReader * Loads PhpSpreadsheet from file * * @param string $pFilename - * @return PhpSpreadsheet * @throws Exception + * @return PhpSpreadsheet */ 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 - protected $dataArray = array(); + protected $dataArray = []; protected $tableLevel = 0; - protected $nestedColumn = array('A'); + protected $nestedColumn = ['A']; protected function setTableStartColumn($column) { @@ -230,11 +229,11 @@ class HTML extends BaseReader implements IReader // TODO } } elseif ($child instanceof DOMElement) { -// echo 'DOM ELEMENT: ' , strtoupper($child->nodeName) , '
'; + // echo 'DOM ELEMENT: ' , strtoupper($child->nodeName) , '
'; - $attributeArray = array(); + $attributeArray = []; foreach ($child->attributes as $attribute) { -// echo 'ATTRIBUTE: ' , $attribute->name , ' => ' , $attribute->value , '
'; + // echo 'ATTRIBUTE: ' , $attribute->name , ' => ' , $attribute->value , '
'; $attributeArray[$attribute->name] = $attribute->value; } @@ -329,7 +328,7 @@ class HTML extends BaseReader implements IReader } else { if ($cellContent > '') { $this->flushCell($sheet, $column, $row, $cellContent); - $row++; + ++$row; } // echo 'START OF PARAGRAPH: ' , '
'; $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]); } - $row++; + ++$row; $column = 'A'; } break; @@ -414,7 +413,7 @@ class HTML extends BaseReader implements IReader if (isset($attributeArray['rowspan']) && isset($attributeArray['colspan'])) { //create merging rowspan and colspan $columnTo = $column; - for ($i = 0; $i < $attributeArray['colspan'] - 1; $i++) { + for ($i = 0; $i < $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $range = $column . $row . ':' . $columnTo . ($row + $attributeArray['rowspan'] - 1); @@ -433,7 +432,7 @@ class HTML extends BaseReader implements IReader } elseif (isset($attributeArray['colspan'])) { //create merging colspan $columnTo = $column; - for ($i = 0; $i < $attributeArray['colspan'] - 1; $i++) { + for ($i = 0; $i < $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $sheet->mergeCells($column . $row . ':' . $columnTo . $row); @@ -460,8 +459,8 @@ class HTML extends BaseReader implements IReader * * @param string $pFilename * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) { @@ -469,7 +468,7 @@ class HTML extends BaseReader implements IReader $this->openFile($pFilename); if (!$this->isValidFormat()) { fclose($this->fileHandle); - throw new Exception($pFilename . " is an Invalid HTML file."); + throw new Exception($pFilename . ' is an Invalid HTML file.'); } // Close after validating fclose($this->fileHandle); @@ -481,7 +480,7 @@ class HTML extends BaseReader implements IReader $spreadsheet->setActiveSheetIndex($this->sheetIndex); // Create a new DOM object - $dom = new domDocument; + $dom = new domDocument(); // Reload the HTML file into the DOM object $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanFile($pFilename), 'HTML-ENTITIES', 'UTF-8')); if ($loaded === false) { @@ -535,6 +534,7 @@ class HTML extends BaseReader implements IReader if (preg_match($pattern, $xml)) { throw new Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); } + return $xml; } } diff --git a/src/PhpSpreadsheet/Reader/IReadFilter.php b/src/PhpSpreadsheet/Reader/IReadFilter.php index 1a87f776..4c8de5f5 100644 --- a/src/PhpSpreadsheet/Reader/IReadFilter.php +++ b/src/PhpSpreadsheet/Reader/IReadFilter.php @@ -32,7 +32,7 @@ interface IReadFilter * @param $column Column address (as a string value like "A", or "IV") * @param $row Row number * @param $worksheetName Optional worksheet name - * @return boolean + * @return bool */ public function readCell($column, $row, $worksheetName = ''); } diff --git a/src/PhpSpreadsheet/Reader/IReader.php b/src/PhpSpreadsheet/Reader/IReader.php index 36006cbf..6d401017 100644 --- a/src/PhpSpreadsheet/Reader/IReader.php +++ b/src/PhpSpreadsheet/Reader/IReader.php @@ -30,7 +30,7 @@ interface IReader * Can the current IReader read the file? * * @param string $pFilename - * @return boolean + * @return bool */ public function canRead($pFilename); @@ -38,8 +38,8 @@ interface IReader * Loads PhpSpreadsheet from file * * @param string $pFilename - * @return PhpSpreadsheet * @throws Exception + * @return PhpSpreadsheet */ public function load($pFilename); } diff --git a/src/PhpSpreadsheet/Reader/OOCalc.php b/src/PhpSpreadsheet/Reader/OOCalc.php index 6fe1efad..4d006b57 100644 --- a/src/PhpSpreadsheet/Reader/OOCalc.php +++ b/src/PhpSpreadsheet/Reader/OOCalc.php @@ -31,28 +31,28 @@ class OOCalc extends BaseReader implements IReader * * @var array */ - private $styles = array(); + private $styles = []; /** * Create a new OOCalc Reader instance */ public function __construct() { - $this->readFilter = new DefaultReadFilter(); + $this->readFilter = new DefaultReadFilter(); } /** * Can the current IReader read the file? * * @param string $pFilename - * @return boolean * @throws Exception + * @return bool */ public function canRead($pFilename) { // Check if file exists 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(); @@ -64,7 +64,7 @@ class OOCalc extends BaseReader implements IReader $mimeType = 'UNKNOWN'; // Load file - $zip = new $zipClass; + $zip = new $zipClass(); if ($zip->open($pFilename) === true) { // check if it is an OOXML archive $stat = $zip->statName('mimetype'); @@ -91,13 +91,12 @@ class OOCalc extends BaseReader implements IReader $zip->close(); - return ($mimeType === 'application/vnd.oasis.opendocument.spreadsheet'); + return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; } return false; } - /** * 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 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(); - $zip = new $zipClass; + $zip = new $zipClass(); 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(); $res = $xml->xml( - $this->securityScanFile('zip://'.realpath($pFilename).'#content.xml'), + $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'), null, \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); @@ -164,21 +163,21 @@ class OOCalc extends BaseReader implements IReader { // Check if file exists 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(); - $zip = new $zipClass; + $zip = new $zipClass(); 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(); $res = $xml->xml( - $this->securityScanFile('zip://'.realpath($pFilename).'#content.xml'), + $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'), null, \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); @@ -200,13 +199,13 @@ class OOCalc extends BaseReader implements IReader if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { $worksheetNames[] = $xml->getAttribute('table:name'); - $tmpInfo = array( + $tmpInfo = [ 'worksheetName' => $xml->getAttribute('table:name'), 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, - ); + ]; // Loop through each child node of the table:table element reading $currCells = 0; @@ -223,7 +222,7 @@ class OOCalc extends BaseReader implements IReader do { if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { if (!$xml->isEmptyElement) { - $currCells++; + ++$currCells; $xml->next(); } else { $xml->read(); @@ -287,8 +286,8 @@ class OOCalc extends BaseReader implements IReader * Loads PhpSpreadsheet from file * * @param string $pFilename - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function load($pFilename) { @@ -305,9 +304,11 @@ class OOCalc extends BaseReader implements IReader foreach ($styleList as $style) { if ($styleAttributeValue == strtolower($style)) { $styleAttributeValue = $style; + return true; } } + return false; } @@ -316,14 +317,14 @@ class OOCalc extends BaseReader implements IReader * * @param string $pFilename * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) { // Check if file exists 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'); @@ -331,14 +332,14 @@ class OOCalc extends BaseReader implements IReader $zipClass = \PhpSpreadsheet\Settings::getZipClass(); - $zip = new $zipClass; + $zip = new $zipClass(); 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 '

Meta Information

'; $xml = simplexml_load_string( - $this->securityScan($zip->getFromName("meta.xml")), + $this->securityScan($zip->getFromName('meta.xml')), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); @@ -350,7 +351,7 @@ class OOCalc extends BaseReader implements IReader $docProps = $spreadsheet->getProperties(); $officeProperty = $xml->children($namespacesMeta['office']); foreach ($officeProperty as $officePropertyData) { - $officePropertyDC = array(); + $officePropertyDC = []; if (isset($namespacesMeta['dc'])) { $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); } @@ -377,7 +378,7 @@ class OOCalc extends BaseReader implements IReader break; } } - $officePropertyMeta = array(); + $officePropertyMeta = []; if (isset($namespacesMeta['dc'])) { $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); } @@ -425,10 +426,9 @@ class OOCalc extends BaseReader implements IReader } } - // echo '

Workbook Content

'; $xml = simplexml_load_string( - $this->securityScan($zip->getFromName("content.xml")), + $this->securityScan($zip->getFromName('content.xml')), 'SimpleXMLElement', \PhpSpreadsheet\Settings::getLibXmlLoaderOptions() ); @@ -467,7 +467,7 @@ class OOCalc extends BaseReader implements IReader $rowID = 1; foreach ($worksheetData as $key => $rowData) { -// echo ''.$key.'
'; + // echo ''.$key.'
'; switch ($key) { case 'table-header-rows': foreach ($rowData as $keyRowData => $cellData) { @@ -509,13 +509,13 @@ class OOCalc extends BaseReader implements IReader } if (isset($cellDataOffice->annotation)) { -// echo 'Cell has comment
'; + // echo 'Cell has comment
'; $annotationText = $cellDataOffice->annotation->children($namespacesContent['text']); - $textArray = array(); + $textArray = []; foreach ($annotationText as $t) { if (isset($t->span)) { foreach ($t->span as $text) { - $textArray[] = (string)$text; + $textArray[] = (string) $text; } } else { $textArray[] = (string) $t; @@ -523,13 +523,13 @@ class OOCalc extends BaseReader implements IReader } $text = implode("\n", $textArray); // echo $text, '
'; - $spreadsheet->getActiveSheet()->getComment($columnID.$rowID)->setText($this->parseRichText($text)); + $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setText($this->parseRichText($text)); // ->setAuthor( $author ) } if (isset($cellDataText->p)) { // 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:p newlines, but text:span does not. // 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) { if (isset($pData->span)) { // span sections do not newline, so we just create one large string here - $spanSection = ""; + $spanSection = ''; foreach ($pData->span as $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')); $dataValue = \PhpSpreadsheet\Shared\Date::formattedPHPToExcel($year, $month, $day, $hour, $minute, $second); 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 { $formatting = \PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15; } break; case 'time': $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; break; } @@ -620,7 +620,7 @@ class OOCalc extends BaseReader implements IReader if ($hasCalculatedValue) { $type = \PhpSpreadsheet\Cell\DataType::TYPE_FORMULA; // echo 'Formula: ', $cellDataFormula, PHP_EOL; - $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=')+1); + $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1); $temp = explode('"', $cellDataFormula); $tKey = false; foreach ($temp as &$value) { @@ -648,18 +648,18 @@ class OOCalc extends BaseReader implements IReader if ($type !== \PhpSpreadsheet\Cell\DataType::TYPE_NULL) { for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$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) { -// echo 'Forumla result is '.$dataValue.'
'; - $spreadsheet->getActiveSheet()->getCell($columnID.$rID)->setCalculatedValue($dataValue); + // echo 'Forumla result is '.$dataValue.'
'; + $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->setCalculatedValue($dataValue); } if ($formatting !== null) { - $spreadsheet->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode($formatting); + $spreadsheet->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode($formatting); } 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) { - $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)) { $columnTo = $columnID; 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; if (isset($cellDataTableAttributes['number-rows-spanned'])) { $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1; } - $cellRange = $columnID.$rowID.':'.$columnTo.$rowTo; + $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo; $spreadsheet->getActiveSheet()->mergeCells($cellRange); } } diff --git a/src/PhpSpreadsheet/Reader/SYLK.php b/src/PhpSpreadsheet/Reader/SYLK.php index 019cc4f1..33574f1e 100644 --- a/src/PhpSpreadsheet/Reader/SYLK.php +++ b/src/PhpSpreadsheet/Reader/SYLK.php @@ -45,7 +45,7 @@ class SYLK extends BaseReader implements IReader * * @var array */ - private $formats = array(); + private $formats = []; /** * Format Count @@ -65,7 +65,7 @@ class SYLK extends BaseReader implements IReader /** * Validate that the current file is a SYLK file * - * @return boolean + * @return bool */ protected function isValidFormat() { @@ -95,6 +95,7 @@ class SYLK extends BaseReader implements IReader public function setInputEncoding($pValue = 'ANSI') { $this->inputEncoding = $pValue; + return $this; } @@ -120,12 +121,12 @@ class SYLK extends BaseReader implements IReader $this->openFile($pFilename); if (!$this->isValidFormat()) { fclose($this->fileHandle); - throw new Exception($pFilename . " is an Invalid Spreadsheet file."); + throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); } $fileHandle = $this->fileHandle; rewind($fileHandle); - $worksheetInfo = array(); + $worksheetInfo = []; $worksheetInfo[0]['worksheetName'] = 'Worksheet'; $worksheetInfo[0]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnIndex'] = 0; @@ -133,7 +134,7 @@ class SYLK extends BaseReader implements IReader $worksheetInfo[0]['totalColumns'] = 0; // Loop through file - $rowData = array(); + $rowData = []; // loop through one row (line) at a time in the file $rowIndex = 0; @@ -181,8 +182,8 @@ class SYLK extends BaseReader implements IReader * Loads PhpSpreadsheet from file * * @param string $pFilename - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function load($pFilename) { @@ -198,8 +199,8 @@ class SYLK extends BaseReader implements IReader * * @param string $pFilename * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return \PhpSpreadsheet\Spreadsheet * @throws Exception + * @return \PhpSpreadsheet\Spreadsheet */ public function loadIntoExisting($pFilename, \PhpSpreadsheet\Spreadsheet $spreadsheet) { @@ -207,7 +208,7 @@ class SYLK extends BaseReader implements IReader $this->openFile($pFilename); if (!$this->isValidFormat()) { fclose($this->fileHandle); - throw new Exception($pFilename . " is an Invalid Spreadsheet file."); + throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); } $fileHandle = $this->fileHandle; rewind($fileHandle); @@ -218,11 +219,11 @@ class SYLK extends BaseReader implements IReader } $spreadsheet->setActiveSheetIndex($this->sheetIndex); - $fromFormats = array('\-', '\ '); - $toFormats = array('-', ' '); + $fromFormats = ['\-', '\ ']; + $toFormats = ['-', ' ']; // Loop through file - $rowData = array(); + $rowData = []; $column = $row = ''; // 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); // Read shared styles if ($dataType == 'P') { - $formatArray = array(); + $formatArray = []; foreach ($rowData as $rowDatum) { switch ($rowDatum{0}) { case 'P': @@ -252,7 +253,7 @@ class SYLK extends BaseReader implements IReader break; case 'S': $styleSettings = substr($rowDatum, 1); - for ($i=0; $iformats['P'.$this->format++] = $formatArray; + $this->formats['P' . $this->format++] = $formatArray; // Read cell value data } elseif ($dataType == 'C') { $hasCalculatedValue = false; @@ -296,14 +297,14 @@ class SYLK extends BaseReader implements IReader $cellData = substr($rowDatum, 1); break; case 'E': - $cellDataFormula = '='.substr($rowDatum, 1); + $cellDataFormula = '=' . substr($rowDatum, 1); // Convert R1C1 style references to A1 style references (but only when not quoted) $temp = explode('"', $cellDataFormula); $key = false; foreach ($temp as &$value) { // Only count/replace in alternate array entries 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 // through the formula from left to right. Reversing means that we work right to left.through // the formula @@ -329,7 +330,7 @@ class SYLK extends BaseReader implements IReader if ($columnReference{0} == '[') { $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])); } @@ -342,19 +343,19 @@ class SYLK extends BaseReader implements IReader break; } } - $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); + $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1); $cellData = \PhpSpreadsheet\Calculation::unwrapResult($cellData); // Set cell value - $spreadsheet->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); + $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); if ($hasCalculatedValue) { $cellData = \PhpSpreadsheet\Calculation::unwrapResult($cellData); - $spreadsheet->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData); + $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setCalculatedValue($cellData); } // Read cell formatting } elseif ($dataType == 'F') { $formatStyle = $columnWidth = $styleSettings = ''; - $styleData = array(); + $styleData = []; foreach ($rowData as $rowDatum) { switch ($rowDatum{0}) { case 'C': @@ -373,7 +374,7 @@ class SYLK extends BaseReader implements IReader break; case 'S': $styleSettings = substr($rowDatum, 1); - for ($i=0; $i '') && ($column > '') && ($row > '')) { - $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); + $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1); 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 > '')) { - $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column-1); - $spreadsheet->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData); + $columnLetter = \PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1); + $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData); } if ($columnWidth > '') { if ($startCol == $endCol) { - $startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol-1); + $startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol - 1); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); } else { - $startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol-1); - $endCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($endCol-1); + $startCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($startCol - 1); + $endCol = \PhpSpreadsheet\Cell::stringFromColumnIndex($endCol - 1); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); do { $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); @@ -463,6 +464,7 @@ class SYLK extends BaseReader implements IReader public function setSheetIndex($pValue = 0) { $this->sheetIndex = $pValue; + return $this; } } diff --git a/src/PhpSpreadsheet/ReferenceHelper.php b/src/PhpSpreadsheet/ReferenceHelper.php index 60d69fd7..4e0c6c81 100644 --- a/src/PhpSpreadsheet/ReferenceHelper.php +++ b/src/PhpSpreadsheet/ReferenceHelper.php @@ -28,10 +28,10 @@ class ReferenceHelper { /** Constants */ /** Regular Expressions */ - const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?getBreaks(); ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aBreaks, array('self','cellReverseSort')) : - uksort($aBreaks, array('self','cellSort')); + uksort($aBreaks, ['self', 'cellReverseSort']) : + uksort($aBreaks, ['self', 'cellSort']); foreach ($aBreaks as $key => $value) { if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { @@ -191,15 +194,15 @@ class ReferenceHelper * * @param Worksheet $pSheet The worksheet that we're editing * @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 integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param integer $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 $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param int $beforeRow Number of the row we're inserting/deleting before + * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) { $aComments = $pSheet->getComments(); - $aNewComments = array(); // the new array of all comments + $aNewComments = []; // the new array of all comments foreach ($aComments as $key => &$value) { // 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 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 integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param integer $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 $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param int $beforeRow Number of the row we're inserting/deleting before + * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) { $aHyperlinkCollection = $pSheet->getHyperlinkCollection(); ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aHyperlinkCollection, array('self','cellReverseSort')) : - uksort($aHyperlinkCollection, array('self','cellSort')); + uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : + uksort($aHyperlinkCollection, ['self', 'cellSort']); foreach ($aHyperlinkCollection as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); @@ -244,17 +247,17 @@ class ReferenceHelper * * @param Worksheet $pSheet The worksheet that we're editing * @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 integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param integer $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 $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param int $beforeRow Number of the row we're inserting/deleting before + * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) { $aDataValidationCollection = $pSheet->getDataValidationCollection(); ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aDataValidationCollection, array('self','cellReverseSort')) : - uksort($aDataValidationCollection, array('self','cellSort')); + uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : + uksort($aDataValidationCollection, ['self', 'cellSort']); foreach ($aDataValidationCollection as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); @@ -270,15 +273,15 @@ class ReferenceHelper * * @param Worksheet $pSheet The worksheet that we're editing * @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 integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param integer $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 $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param int $beforeRow Number of the row we're inserting/deleting before + * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) { $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) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $aNewMergeCells[$newReference] = $newReference; @@ -291,17 +294,17 @@ class ReferenceHelper * * @param Worksheet $pSheet The worksheet that we're editing * @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 integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param integer $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 $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param int $beforeRow Number of the row we're inserting/deleting before + * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) { $aProtectedCells = $pSheet->getProtectedCells(); ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aProtectedCells, array('self','cellReverseSort')) : - uksort($aProtectedCells, array('self','cellSort')); + uksort($aProtectedCells, ['self', 'cellReverseSort']) : + uksort($aProtectedCells, ['self', 'cellSort']); foreach ($aProtectedCells as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); if ($key != $newReference) { @@ -316,10 +319,10 @@ class ReferenceHelper * * @param Worksheet $pSheet The worksheet that we're editing * @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 integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param integer $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 $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param int $beforeRow Number of the row we're inserting/deleting before + * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ 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 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 integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param integer $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 $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param int $beforeRow Number of the row we're inserting/deleting before + * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ 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 * * @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 integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param int $pNumCols Number of columns 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 * @throws Exception */ @@ -385,14 +388,14 @@ class ReferenceHelper $aCellCollection = $pSheet->getCellCollection(); // Get coordinates of $pBefore - $beforeColumn = 'A'; - $beforeRow = 1; + $beforeColumn = 'A'; + $beforeRow = 1; list($beforeColumn, $beforeRow) = Cell::coordinateFromString($pBefore); $beforeColumnIndex = Cell::columnIndexFromString($beforeColumn); // Clear cells if we are removing columns or rows - $highestColumn = $pSheet->getHighestColumn(); - $highestRow = $pSheet->getHighestRow(); + $highestColumn = $pSheet->getHighestColumn(); + $highestRow = $pSheet->getHighestRow(); // 1. Clear column strips if we are removing columns if ($pNumCols < 0 && $beforeColumnIndex - 2 + $pNumCols > 0) { @@ -431,12 +434,12 @@ class ReferenceHelper $cell = $pSheet->getCell($cellID); $cellIndex = Cell::columnIndexFromString($cell->getColumn()); - if ($cellIndex-1 + $pNumCols < 0) { + if ($cellIndex - 1 + $pNumCols < 0) { continue; } // 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. if (($cellIndex >= $beforeColumnIndex) && ($cell->getRow() >= $beforeRow)) { @@ -466,8 +469,8 @@ class ReferenceHelper } // Duplicate styles for the newly inserted cells - $highestColumn = $pSheet->getHighestColumn(); - $highestRow = $pSheet->getHighestRow(); + $highestColumn = $pSheet->getHighestColumn(); + $highestRow = $pSheet->getHighestRow(); if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) { for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { @@ -480,7 +483,7 @@ class ReferenceHelper for ($j = $beforeColumnIndex - 1; $j <= $beforeColumnIndex - 2 + $pNumCols; ++$j) { $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); if ($conditionalStyles) { - $cloned = array(); + $cloned = []; foreach ($conditionalStyles as $conditionalStyle) { $cloned[] = clone $conditionalStyle; } @@ -502,7 +505,7 @@ class ReferenceHelper for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) { $pSheet->getCell(Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); if ($conditionalStyles) { - $cloned = array(); + $cloned = []; foreach ($conditionalStyles as $conditionalStyle) { $cloned[] = clone $conditionalStyle; } @@ -565,23 +568,23 @@ class ReferenceHelper // Shuffle columns in autofilter range if ($pNumCols > 0) { // For insert, we shuffle from end to beginning to avoid overwriting - $startColID = Cell::stringFromColumnIndex($startCol-1); - $toColID = Cell::stringFromColumnIndex($startCol+$pNumCols-1); + $startColID = Cell::stringFromColumnIndex($startCol - 1); + $toColID = Cell::stringFromColumnIndex($startCol + $pNumCols - 1); $endColID = Cell::stringFromColumnIndex($rangeEnd[0]); $startColRef = $startCol; $endColRef = $rangeEnd[0]; - $toColRef = $rangeEnd[0]+$pNumCols; + $toColRef = $rangeEnd[0] + $pNumCols; do { - $autoFilter->shiftColumn(Cell::stringFromColumnIndex($endColRef-1), Cell::stringFromColumnIndex($toColRef-1)); + $autoFilter->shiftColumn(Cell::stringFromColumnIndex($endColRef - 1), Cell::stringFromColumnIndex($toColRef - 1)); --$endColRef; --$toColRef; } while ($startColRef <= $endColRef); } else { // For delete, we shuffle from beginning to end to avoid overwriting - $startColID = Cell::stringFromColumnIndex($startCol-1); - $toColID = Cell::stringFromColumnIndex($startCol+$pNumCols-1); + $startColID = Cell::stringFromColumnIndex($startCol - 1); + $toColID = Cell::stringFromColumnIndex($startCol + $pNumCols - 1); $endColID = Cell::stringFromColumnIndex($rangeEnd[0]); do { $autoFilter->shiftColumn($startColID, $toColID); @@ -635,8 +638,8 @@ class ReferenceHelper * @param int $pNumCols Number of columns to insert * @param int $pNumRows Number of rows to insert * @param string $sheetName Worksheet name/title - * @return string Updated formula * @throws Exception + * @return string Updated formula */ 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) if ($i = !$i) { $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) - $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) { foreach ($matches as $match) { - $fromString = ($match[2] > '') ? $match[2].'!' : ''; - $fromString .= $match[3].':'.$match[4]; - $modified3 = substr($this->updateCellReference('$A'.$match[3], $pBefore, $pNumCols, $pNumRows), 2); - $modified4 = substr($this->updateCellReference('$A'.$match[4], $pBefore, $pNumCols, $pNumRows), 2); + $fromString = ($match[2] > '') ? $match[2] . '!' : ''; + $fromString .= $match[3] . ':' . $match[4]; + $modified3 = substr($this->updateCellReference('$A' . $match[3], $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)) { - $toString = ($match[2] > '') ? $match[2].'!' : ''; - $toString .= $modified3.':'.$modified4; + $toString = ($match[2] > '') ? $match[2] . '!' : ''; + $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 $column = 100000; $row = 10000000 + trim($match[3], '$'); - $cellIndex = $column.$row; + $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString); - $cellTokens[$cellIndex] = '/(? 0) { foreach ($matches as $match) { - $fromString = ($match[2] > '') ? $match[2].'!' : ''; - $fromString .= $match[3].':'.$match[4]; - $modified3 = substr($this->updateCellReference($match[3].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); - $modified4 = substr($this->updateCellReference($match[4].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); + $fromString = ($match[2] > '') ? $match[2] . '!' : ''; + $fromString .= $match[3] . ':' . $match[4]; + $modified3 = substr($this->updateCellReference($match[3] . '$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)) { - $toString = ($match[2] > '') ? $match[2].'!' : ''; - $toString .= $modified3.':'.$modified4; + $toString = ($match[2] > '') ? $match[2] . '!' : ''; + $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 $column = Cell::columnIndexFromString(trim($match[3], '$')) + 100000; $row = 10000000; - $cellIndex = $column.$row; + $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString); - $cellTokens[$cellIndex] = '/(? 0) { foreach ($matches as $match) { - $fromString = ($match[2] > '') ? $match[2].'!' : ''; - $fromString .= $match[3].':'.$match[4]; + $fromString = ($match[2] > '') ? $match[2] . '!' : ''; + $fromString .= $match[3] . ':' . $match[4]; $modified3 = $this->updateCellReference($match[3], $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)) { - $toString = ($match[2] > '') ? $match[2].'!' : ''; - $toString .= $modified3.':'.$modified4; + $toString = ($match[2] > '') ? $match[2] . '!' : ''; + $toString .= $modified3 . ':' . $modified4; 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 $column = Cell::columnIndexFromString(trim($column, '$')) + 100000; $row = trim($row, '$') + 10000000; - $cellIndex = $column.$row; + $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString); - $cellTokens[$cellIndex] = '/(? 0) { foreach ($matches as $match) { - $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3]; $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); if ($match[3] !== $modified3) { if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { - $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3; 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 @@ -744,7 +747,7 @@ class ReferenceHelper $cellIndex = $row . $column; $newCellTokens[$cellIndex] = preg_quote($toString); - $cellTokens[$cellIndex] = '/(?getValue(); if (strpos($formula, $oldName) !== false) { $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); } } @@ -831,8 +834,8 @@ class ReferenceHelper * @param int $pBefore Insert before this one * @param int $pNumCols Number of columns to increment * @param int $pNumRows Number of rows to increment - * @return string Updated cell range * @throws Exception + * @return string Updated cell range */ private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { @@ -844,10 +847,10 @@ class ReferenceHelper $jc = count($range[$i]); for ($j = 0; $j < $jc; ++$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]; } 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]; } else { $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows); @@ -858,7 +861,7 @@ class ReferenceHelper // Recreate range string return Cell::buildRange($range); } 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 $pNumCols Number of columns to increment * @param int $pNumRows Number of rows to increment - * @return string Updated cell reference * @throws Exception + * @return string Updated cell reference */ private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { @@ -887,18 +890,18 @@ class ReferenceHelper // Create new column reference if ($updateColumn) { - $newColumn = Cell::stringFromColumnIndex(Cell::columnIndexFromString($newColumn) - 1 + $pNumCols); + $newColumn = Cell::stringFromColumnIndex(Cell::columnIndexFromString($newColumn) - 1 + $pNumCols); } // Create new row reference if ($updateRow) { - $newRow = $newRow + $pNumRows; + $newRow = $newRow + $pNumRows; } // Return new reference return $newColumn . $newRow; } 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() { - throw new Exception("Cloning a Singleton is not allowed!"); + throw new Exception('Cloning a Singleton is not allowed!'); } } diff --git a/src/PhpSpreadsheet/RichText.php b/src/PhpSpreadsheet/RichText.php index 8bbba5da..fc5242b8 100644 --- a/src/PhpSpreadsheet/RichText.php +++ b/src/PhpSpreadsheet/RichText.php @@ -42,12 +42,12 @@ class RichText implements IComparable public function __construct(Cell $pCell = null) { // Initialise variables - $this->richTextElements = array(); + $this->richTextElements = []; // Rich-Text string attached to cell? if ($pCell !== null) { // Add cell text and style - if ($pCell->getValue() != "") { + if ($pCell->getValue() != '') { $objRun = new RichText\Run($pCell->getValue()); $objRun->setFont(clone $pCell->getParent()->getStyle($pCell->getCoordinate())->getFont()); $this->addText($objRun); @@ -68,6 +68,7 @@ class RichText implements IComparable public function addText(RichText\ITextElement $pText = null) { $this->richTextElements[] = $pText; + return $this; } @@ -75,13 +76,14 @@ class RichText implements IComparable * Create text * * @param string $pText Text - * @return RichText\TextElement * @throws Exception + * @return RichText\TextElement */ public function createText($pText = '') { $objText = new RichText\TextElement($pText); $this->addText($objText); + return $objText; } @@ -89,13 +91,14 @@ class RichText implements IComparable * Create text run * * @param string $pText Text - * @return RichText\Run * @throws Exception + * @return RichText\Run */ public function createTextRun($pText = '') { $objText = new RichText\Run($pText); $this->addText($objText); + return $objText; } @@ -151,6 +154,7 @@ class RichText implements IComparable } else { throw new Exception("Invalid \PhpSpreadsheet\RichText\ITextElement[] array passed."); } + return $this; } diff --git a/src/PhpSpreadsheet/RichText/Run.php b/src/PhpSpreadsheet/RichText/Run.php index 83a79e9c..ab059340 100644 --- a/src/PhpSpreadsheet/RichText/Run.php +++ b/src/PhpSpreadsheet/RichText/Run.php @@ -63,6 +63,7 @@ class Run extends TextElement implements ITextElement public function setFont(\PhpSpreadsheet\Style\Font $pFont = null) { $this->font = $pFont; + return $this; } diff --git a/src/PhpSpreadsheet/RichText/TextElement.php b/src/PhpSpreadsheet/RichText/TextElement.php index 99be025a..f7789930 100644 --- a/src/PhpSpreadsheet/RichText/TextElement.php +++ b/src/PhpSpreadsheet/RichText/TextElement.php @@ -61,6 +61,7 @@ class TextElement implements ITextElement public function setText($pText = '') { $this->text = $pText; + return $this; } diff --git a/src/PhpSpreadsheet/Settings.php b/src/PhpSpreadsheet/Settings.php index 177ae6cb..df960b9f 100644 --- a/src/PhpSpreadsheet/Settings.php +++ b/src/PhpSpreadsheet/Settings.php @@ -28,28 +28,26 @@ class Settings { /** constants */ /** Available Zip library classes */ - const PCLZIP = '\\PhpSpreadsheet\\Shared\\ZipArchive'; + const PCLZIP = '\\PhpSpreadsheet\\Shared\\ZipArchive'; const ZIPARCHIVE = '\\ZipArchive'; /** Optional Chart Rendering libraries */ const CHART_RENDERER_JPGRAPH = 'JpGraph'; /** Optional PDF Rendering libraries */ - const PDF_RENDERER_TCPDF = 'TcPDF'; + const PDF_RENDERER_TCPDF = 'TcPDF'; const PDF_RENDERER_DOMPDF = 'DomPDF'; - const PDF_RENDERER_MPDF = 'MPDF'; + const PDF_RENDERER_MPDF = 'MPDF'; - - private static $chartRenderers = array( + private static $chartRenderers = [ self::CHART_RENDERER_JPGRAPH, - ); + ]; - private static $pdfRenderers = array( + private static $pdfRenderers = [ self::PDF_RENDERER_TCPDF, self::PDF_RENDERER_DOMPDF, self::PDF_RENDERER_MPDF, - ); - + ]; /** * Name of the class used for Zip file management @@ -60,7 +58,6 @@ class Settings */ private static $zipClass = self::ZIPARCHIVE; - /** * Name of the external Library used for rendering charts * e.g. @@ -77,7 +74,6 @@ class Settings */ private static $chartRendererPath; - /** * Name of the external Library used for rendering PDF files * e.g. @@ -106,19 +102,20 @@ class Settings * * @param string $zipClass The Zip handler class that PhpSpreadsheet should use for Zip file management * e.g. \PhpSpreadsheet\Settings::PCLZip or \PhpSpreadsheet\Settings::ZipArchive - * @return boolean Success or failure + * @return bool Success or failure */ public static function setZipClass($zipClass) { if (($zipClass === self::PCLZIP) || ($zipClass === self::ZIPARCHIVE)) { self::$zipClass = $zipClass; + return true; } + return false; } - /** * Return the name of the Zip handler Class that PhpSpreadsheet is configured to use (PCLZip or ZipArchive) * or Zip file management @@ -132,7 +129,6 @@ class Settings return self::$zipClass; } - /** * Return the name of the method that is currently configured for cell cacheing * @@ -143,7 +139,6 @@ class Settings return CachedObjectStorageFactory::getCacheStorageMethod(); } - /** * Return the name of the class that is currently being used for cell cacheing * @@ -154,32 +149,29 @@ class Settings return CachedObjectStorageFactory::getCacheStorageClass(); } - /** * Set the method that should be used for cell cacheing * * @param string $method Name of 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); } - /** * 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") - * @return boolean Success or failure + * @return bool Success or failure */ public static function setLocale($locale = 'en_us') { return Calculation::getInstance()->setLocale($locale); } - /** * 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 * @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) { if (!self::setChartRendererName($libraryName)) { return false; } + return self::setChartRendererPath($libraryBaseDir); } - /** * Identify to PhpSpreadsheet the external library to use for rendering charts * * @param string $libraryName Internal reference name of the library * e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH * - * @return boolean Success or failure + * @return bool Success or failure */ public static function setChartRendererName($libraryName) { @@ -216,12 +208,11 @@ class Settings return true; } - /** * Tell PhpSpreadsheet where to find the external library to use for rendering charts * * @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) { @@ -233,11 +224,10 @@ class Settings return true; } - /** * 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 * e.g. \PhpSpreadsheet\Settings::CHART_RENDERER_JPGRAPH */ @@ -246,11 +236,10 @@ class Settings return self::$chartRendererName; } - /** * 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 */ public static function getChartRendererPath() @@ -258,7 +247,6 @@ class Settings return self::$chartRendererPath; } - /** * 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 * @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) { if (!self::setPdfRendererName($libraryName)) { return false; } + return self::setPdfRendererPath($libraryBaseDir); } - /** * Identify to PhpSpreadsheet the external library to use for rendering PDF files * @@ -287,7 +275,7 @@ class Settings * \PhpSpreadsheet\Settings::PDF_RENDERER_DOMPDF * or \PhpSpreadsheet\Settings::PDF_RENDERER_MPDF * - * @return boolean Success or failure + * @return bool Success or failure */ public static function setPdfRendererName($libraryName) { @@ -299,12 +287,11 @@ class Settings return true; } - /** * 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 - * @return boolean Success or failure + * @return bool Success or failure */ public static function setPdfRendererPath($libraryBaseDir) { @@ -316,11 +303,10 @@ class Settings return true; } - /** * 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 * e.g. \PhpSpreadsheet\Settings::PDF_RENDERER_TCPDF, * \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 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 */ public static function getPdfRendererPath() diff --git a/src/PhpSpreadsheet/Shared/CodePage.php b/src/PhpSpreadsheet/Shared/CodePage.php index 937b5331..4802a67a 100644 --- a/src/PhpSpreadsheet/Shared/CodePage.php +++ b/src/PhpSpreadsheet/Shared/CodePage.php @@ -32,9 +32,9 @@ class CodePage * Convert Microsoft Code Page Identifier to Code Page Name which iconv * and mbstring understands * - * @param integer $codePage Microsoft Code Page Indentifier - * @return string Code Page Name + * @param int $codePage Microsoft Code Page Indentifier * @throws \PhpSpreadsheet\Exception + * @return string Code Page Name */ public static function numberToName($codePage = 1252) { diff --git a/src/PhpSpreadsheet/Shared/Date.php b/src/PhpSpreadsheet/Shared/Date.php index d1e89165..6b6bb50a 100644 --- a/src/PhpSpreadsheet/Shared/Date.php +++ b/src/PhpSpreadsheet/Shared/Date.php @@ -85,23 +85,25 @@ class Date /** * Set the Excel calendar (Windows 1900 or Mac 1904) * - * @param integer $baseDate Excel base date (1900 or 1904) - * @return boolean Success or failure + * @param int $baseDate Excel base date (1900 or 1904) + * @return bool Success or failure */ public static function setExcelCalendar($baseDate) { if (($baseDate == self::CALENDAR_WINDOWS_1900) || ($baseDate == self::CALENDAR_MAC_1904)) { self::$excelCalendar = $baseDate; + return true; } + return false; } /** * 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() { @@ -112,15 +114,17 @@ class Date * 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 - * @return boolean Success or failure * @throws \Exception + * @return bool Success or failure */ public static function setDefaultTimezone($timeZone) { if ($timeZone = self::validateTimeZone($timeZone)) { self::$defaultTimeZone = $timeZone; + return true; } + return false; } @@ -134,6 +138,7 @@ class Date if (self::$defaultTimeZone === null) { self::$defaultTimeZone = new \DateTimeZone('UTC'); } + return self::$defaultTimeZone; } @@ -141,8 +146,8 @@ class Date * Validate a timezone * * @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 + * @return \DateTimeZone The timezone as a timezone object */ 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 * - * @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, * if you don't want to treat it as a UTC value * Use the default (UST) unless you absolutely need a conversion - * @return \DateTime PHP date/time object * @throws \Exception + * @return \DateTime PHP date/time object */ public static function excelToDateTimeObject($excelTimestamp = 0, $timeZone = null) { @@ -188,6 +193,7 @@ class Date $seconds = round($partDay * 60); $interval = '+' . $days . ' days'; + return $baseDate->modify($interval) ->setTime($hours, $minutes, $seconds); } @@ -195,12 +201,12 @@ class Date /** * 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, * if you don't want to treat it as a UTC value * Use the default (UST) unless you absolutely need a conversion - * @return integer Unix timetamp for this date/time * @throws \Exception + * @return int Unix timetamp for this date/time */ 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 * * @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 */ public static function PHPToExcel($dateValue = 0) @@ -257,19 +263,20 @@ class Date if (!is_numeric($dateValue)) { return false; } + return self::DateTimeToExcel(new \DateTime('@' . $dateValue)); } /** * formattedPHPToExcel * - * @param integer $year - * @param integer $month - * @param integer $day - * @param integer $hours - * @param integer $minutes - * @param integer $seconds - * @return integer Excel date/time value + * @param int $year + * @param int $month + * @param int $day + * @param int $hours + * @param int $minutes + * @param int $seconds + * @return int Excel date/time value */ public static function formattedPHPToExcel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0) { @@ -306,12 +313,11 @@ class Date return (float) $excelDate + $excelTime; } - /** * Is a given cell a date/time? * * @param \PhpSpreadsheet\Cell $pCell - * @return boolean + * @return bool */ public static function isDateTime(\PhpSpreadsheet\Cell $pCell) { @@ -322,26 +328,24 @@ class Date ); } - /** * Is a given number format a date/time? * * @param \PhpSpreadsheet\Style\NumberFormat $pFormat - * @return boolean + * @return bool */ public static function isDateTimeFormat(\PhpSpreadsheet\Style\NumberFormat $pFormat) { return self::isDateTimeFormatCode($pFormat->getFormatCode()); } - private static $possibleDateFormatCharacters = 'eymdHs'; /** * Is a given number format code a date/time? * * @param string $pFormatCode - * @return boolean + * @return bool */ public static function isDateTimeFormatCode($pFormatCode = '') { @@ -387,7 +391,7 @@ class Date return false; } // 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 don't want to test for any of our characters within the quoted blocks if (strpos($pFormatCode, '"') !== false) { @@ -395,12 +399,14 @@ class Date foreach (explode('"', $pFormatCode) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) if (($segMatcher = !$segMatcher) && - (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i', $subVal))) { + (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $subVal))) { return true; } } + return false; } + return true; } @@ -408,12 +414,11 @@ class Date return false; } - /** * 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' - * @return float|FALSE Excel date/time serial value + * @return float|false Excel date/time serial value */ public static function stringToExcel($dateValue = '') { @@ -437,6 +442,7 @@ class Date } $dateValueNew += $timeValue; } + return $dateValueNew; } @@ -444,7 +450,7 @@ class Date * Converts a month name (either a long or a short name) to a month number * * @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) { @@ -455,6 +461,7 @@ class Date } ++$monthIndex; } + return $month; } @@ -462,7 +469,7 @@ class Date * Strips an ordinal froma numeric value * * @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) { @@ -470,6 +477,7 @@ class Date if (is_numeric($strippedDayValue)) { return (integer) $strippedDayValue; } + return $day; } } diff --git a/src/PhpSpreadsheet/Shared/Drawing.php b/src/PhpSpreadsheet/Shared/Drawing.php index f4cec48f..597f9ddc 100644 --- a/src/PhpSpreadsheet/Shared/Drawing.php +++ b/src/PhpSpreadsheet/Shared/Drawing.php @@ -141,7 +141,7 @@ class Drawing */ 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) { // Load the image into a string - $file = fopen($p_sFile, "rb"); + $file = fopen($p_sFile, 'rb'); $read = fread($file, 10); - while (!feof($file) && ($read<>"")) { + while (!feof($file) && ($read != '')) { $read .= fread($file, 1024); } - $temp = unpack("H*", $read); + $temp = unpack('H*', $read); $hex = $temp[1]; $header = substr($hex, 0, 108); // Process the header // 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 $header_parts = str_split($header, 2); // 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 - $height = hexdec($header_parts[23].$header_parts[22]); + $height = hexdec($header_parts[23] . $header_parts[22]); // Unset the header params unset($header_parts); @@ -208,11 +208,11 @@ class Drawing // Calculate if padding at the end-line is needed // Divided by two to keep overview. // 1 byte = 2 HEX-chars - $body_size = (strlen($body)/2); - $header_size = ($width*$height); + $body_size = (strlen($body) / 2); + $header_size = ($width * $height); // 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 // Calculate the next DWORD-position in the body @@ -222,14 +222,14 @@ class Drawing // If padding needed, ignore image-padding // Shift i to the ending of the current 32-bit-block if ($usePadding) { - $i += $width%4; + $i += $width % 4; } // Reset horizontal position $x = 0; // Raise the height-position (bottom-up) - $y++; + ++$y; // Reached the image-height? Break the for-loop if ($y > $height) { @@ -239,17 +239,17 @@ class Drawing // Calculation of the RGB-pixel (defined as BGR in image-data) // Define $i_pos as absolute position in the body - $i_pos = $i * 2; - $r = hexdec($body[$i_pos+4].$body[$i_pos+5]); - $g = hexdec($body[$i_pos+2].$body[$i_pos+3]); - $b = hexdec($body[$i_pos].$body[$i_pos+1]); + $i_pos = $i * 2; + $r = hexdec($body[$i_pos + 4] . $body[$i_pos + 5]); + $g = hexdec($body[$i_pos + 2] . $body[$i_pos + 3]); + $b = hexdec($body[$i_pos] . $body[$i_pos + 1]); // Calculate and draw the pixel - $color = imagecolorallocate($image, $r, $g, $b); - imagesetpixel($image, $x, $height-$y, $color); + $color = imagecolorallocate($image, $r, $g, $b); + imagesetpixel($image, $x, $height - $y, $color); // Raise the horizontal position - $x++; + ++$x; } // Unset the body / free the memory diff --git a/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php b/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php index 0fa4407a..492d07b1 100644 --- a/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php +++ b/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php @@ -38,7 +38,7 @@ class SpgrContainer * * @var array */ - private $children = array(); + private $children = []; /** * Set parent Shape Group Container @@ -86,10 +86,10 @@ class SpgrContainer */ public function getAllSpContainers() { - $allSpContainers = array(); + $allSpContainers = []; foreach ($this->children as $child) { - if ($child instanceof SpgrContainer) { + if ($child instanceof self) { $allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers()); } else { $allSpContainers[] = $child; diff --git a/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php b/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php index b91efe53..e773d24f 100644 --- a/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php +++ b/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php @@ -36,7 +36,7 @@ class SpContainer /** * Is this a group shape? * - * @var boolean + * @var bool */ private $spgr = false; @@ -57,7 +57,7 @@ class SpContainer /** * Shape index (usually group shape has index 0, and the rest: 1,2,3...) * - * @var boolean + * @var bool */ private $spId; @@ -133,7 +133,7 @@ class SpContainer /** * Set whether this is a group shape * - * @param boolean $value + * @param bool $value */ public function setSpgr($value = false) { @@ -143,7 +143,7 @@ class SpContainer /** * Get whether this is a group shape * - * @return boolean + * @return bool */ public function getSpgr() { @@ -232,6 +232,7 @@ class SpContainer if (isset($this->OPT[$property])) { return $this->OPT[$property]; } + return null; } diff --git a/src/PhpSpreadsheet/Shared/Escher/DggContainer.php b/src/PhpSpreadsheet/Shared/Escher/DggContainer.php index b0970829..3b573661 100644 --- a/src/PhpSpreadsheet/Shared/Escher/DggContainer.php +++ b/src/PhpSpreadsheet/Shared/Escher/DggContainer.php @@ -59,14 +59,14 @@ class DggContainer * * @var array */ - private $OPT = array(); + private $OPT = []; /** * Array of identifier clusters containg information about the maximum shape identifiers * * @var array */ - private $IDCLs = array(); + private $IDCLs = []; /** * Get maximum shape index of all shapes in all drawings (plus one) @@ -170,6 +170,7 @@ class DggContainer if (isset($this->OPT[$property])) { return $this->OPT[$property]; } + return null; } diff --git a/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php b/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php index 92c2a686..8974d52f 100644 --- a/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php +++ b/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php @@ -31,7 +31,7 @@ class BstoreContainer * * @var array */ - private $BSECollection = array(); + private $BSECollection = []; /** * Add a BLIP Store Entry diff --git a/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php b/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php index 7a30efc0..382f1c6d 100644 --- a/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php +++ b/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php @@ -26,15 +26,15 @@ namespace PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; */ class BSE { - const BLIPTYPE_ERROR = 0x00; - const BLIPTYPE_UNKNOWN = 0x01; - const BLIPTYPE_EMF = 0x02; - const BLIPTYPE_WMF = 0x03; - const BLIPTYPE_PICT = 0x04; - const BLIPTYPE_JPEG = 0x05; - const BLIPTYPE_PNG = 0x06; - const BLIPTYPE_DIB = 0x07; - const BLIPTYPE_TIFF = 0x11; + const BLIPTYPE_ERROR = 0x00; + const BLIPTYPE_UNKNOWN = 0x01; + const BLIPTYPE_EMF = 0x02; + const BLIPTYPE_WMF = 0x03; + const BLIPTYPE_PICT = 0x04; + const BLIPTYPE_JPEG = 0x05; + const BLIPTYPE_PNG = 0x06; + const BLIPTYPE_DIB = 0x07; + const BLIPTYPE_TIFF = 0x11; const BLIPTYPE_CMYKJPEG = 0x12; /** diff --git a/src/PhpSpreadsheet/Shared/Excel5.php b/src/PhpSpreadsheet/Shared/Excel5.php index 4b695cfb..e8635b12 100644 --- a/src/PhpSpreadsheet/Shared/Excel5.php +++ b/src/PhpSpreadsheet/Shared/Excel5.php @@ -33,8 +33,8 @@ class Excel5 * * @param \PhpSpreadsheet\Worksheet $sheet The sheet * @param string $col The column - * @return integer The width in pixels - */ + * @return int The width in pixels + */ public static function sizeCol($sheet, $col = 'A') { // 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. * * @param \PhpSpreadsheet\Worksheet $sheet The sheet - * @param integer $row The row index (1-based) - * @return integer The width in pixels + * @param int $row The row index (1-based) + * @return int The width in pixels */ public static function sizeRow($sheet, $row = 1) { @@ -117,10 +117,10 @@ class Excel5 * * @param \PhpSpreadsheet\Worksheet $sheet * @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 integer $endOffsetX Offset within end cell measured in 1/1024 of the cell width - * @return integer Horizontal measured in pixels + * @param int $endOffsetX Offset within end cell measured in 1/1024 of the cell width + * @return int Horizontal measured in pixels */ 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 * * @param \PhpSpreadsheet\Worksheet $sheet - * @param integer $startRow (1-based) - * @param integer $startOffsetY Offset within start cell measured in 1/256 of the cell height - * @param integer $endRow (1-based) - * @param integer $endOffsetY Offset within end cell measured in 1/256 of the cell height - * @return integer Vertical distance measured in pixels + * @param int $startRow (1-based) + * @param int $startOffsetY Offset within start cell measured in 1/256 of the cell height + * @param int $endRow (1-based) + * @param int $endOffsetY Offset within end cell measured in 1/256 of the cell height + * @return int Vertical distance measured in pixels */ 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 string $coordinates E.g. 'A1' - * @param integer $offsetX Horizontal offset in pixels - * @param integer $offsetY Vertical offset in pixels - * @param integer $width Width in pixels - * @param integer $height Height in pixels + * @param int $offsetX Horizontal offset in pixels + * @param int $offsetY Vertical offset in pixels + * @param int $width Width in pixels + * @param int $height Height in pixels * @return array */ public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height) @@ -233,8 +233,8 @@ class Excel5 $y1 = $offsetY; // Initialise end cell to the same as the start cell - $col_end = $col_start; // Col containing lower right corner of object - $row_end = $row_start; // Row containing bottom 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 // Zero the specified offset if greater than the cell dimensions if ($x1 >= self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start))) { @@ -244,8 +244,8 @@ class Excel5 $y1 = 0; } - $width = $width + $x1 -1; - $height = $height + $y1 -1; + $width = $width + $x1 - 1; + $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image 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) { return; } - if (self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) == 0) { + if (self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) == 0) { return; } if (self::sizeRow($sheet, $row_start + 1) == 0) { return; } - if (self::sizeRow($sheet, $row_end + 1) == 0) { + if (self::sizeRow($sheet, $row_end + 1) == 0) { return; } // Convert the pixel values to the percentage value expected by Excel - $x1 = $x1 / self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) * 1024; - $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 - $y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object + $x1 = $x1 / self::sizeCol($sheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) * 1024; + $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 + $y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object $startCoordinates = \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start) . ($row_start + 1); $endCoordinates = \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end) . ($row_end + 1); - $twoAnchor = array( + $twoAnchor = [ 'startCoordinates' => $startCoordinates, 'startOffsetX' => $x1, 'startOffsetY' => $y1, 'endCoordinates' => $endCoordinates, 'endOffsetX' => $x2, 'endOffsetY' => $y2, - ); + ]; return $twoAnchor; } diff --git a/src/PhpSpreadsheet/Shared/File.php b/src/PhpSpreadsheet/Shared/File.php index f94ec985..a50c4ec2 100644 --- a/src/PhpSpreadsheet/Shared/File.php +++ b/src/PhpSpreadsheet/Shared/File.php @@ -36,35 +36,32 @@ class File */ protected static $useUploadTempDirectory = false; - /** * 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) { self::$useUploadTempDirectory = (boolean) $useUploadTempDir; } - /** * 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() { return self::$useUploadTempDirectory; } - /** - * Verify if a file exists - * - * @param string $pFilename Filename - * @return bool - */ + * Verify if a file exists + * + * @param string $pFilename Filename + * @return bool + */ public static function fileExists($pFilename) { // Sick construction, but it seems that @@ -72,7 +69,7 @@ class File // doing the original file_exists on ZIP archives... if (strtolower(substr($pFilename, 0, 3)) == 'zip') { // 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); $zipClass = \PhpSpreadsheet\Settings::getZipClass(); @@ -80,6 +77,7 @@ class File if ($zip->open($zipFile) === true) { $returnValue = ($zip->getFromName($archiveFile) !== false); $zip->close(); + return $returnValue; } else { return false; @@ -168,6 +166,7 @@ class File $temp = tempnam(__FILE__, ''); if (file_exists($temp)) { unlink($temp); + return realpath(dirname($temp)); } diff --git a/src/PhpSpreadsheet/Shared/Font.php b/src/PhpSpreadsheet/Shared/Font.php index b1f41747..d1cb6fe6 100644 --- a/src/PhpSpreadsheet/Shared/Font.php +++ b/src/PhpSpreadsheet/Shared/Font.php @@ -29,96 +29,96 @@ namespace PhpSpreadsheet\Shared; class Font { /* Methods for resolving autosize value */ - const AUTOSIZE_METHOD_APPROX = 'approx'; - const AUTOSIZE_METHOD_EXACT = 'exact'; + const AUTOSIZE_METHOD_APPROX = 'approx'; + const AUTOSIZE_METHOD_EXACT = 'exact'; - private static $autoSizeMethods = array( + private static $autoSizeMethods = [ self::AUTOSIZE_METHOD_APPROX, self::AUTOSIZE_METHOD_EXACT, - ); + ]; /** Character set codes used by BIFF5-8 in Font records */ - const CHARSET_ANSI_LATIN = 0x00; - const CHARSET_SYSTEM_DEFAULT = 0x01; - const CHARSET_SYMBOL = 0x02; - const CHARSET_APPLE_ROMAN = 0x4D; - const CHARSET_ANSI_JAPANESE_SHIFTJIS = 0x80; - const CHARSET_ANSI_KOREAN_HANGUL = 0x81; - const CHARSET_ANSI_KOREAN_JOHAB = 0x82; - const CHARSET_ANSI_CHINESE_SIMIPLIFIED = 0x86; // gb2312 - const CHARSET_ANSI_CHINESE_TRADITIONAL = 0x88; // big5 - const CHARSET_ANSI_GREEK = 0xA1; - const CHARSET_ANSI_TURKISH = 0xA2; - const CHARSET_ANSI_VIETNAMESE = 0xA3; - const CHARSET_ANSI_HEBREW = 0xB1; - const CHARSET_ANSI_ARABIC = 0xB2; - const CHARSET_ANSI_BALTIC = 0xBA; - const CHARSET_ANSI_CYRILLIC = 0xCC; - const CHARSET_ANSI_THAI = 0xDD; - const CHARSET_ANSI_LATIN_II = 0xEE; - const CHARSET_OEM_LATIN_I = 0xFF; + const CHARSET_ANSI_LATIN = 0x00; + const CHARSET_SYSTEM_DEFAULT = 0x01; + const CHARSET_SYMBOL = 0x02; + const CHARSET_APPLE_ROMAN = 0x4D; + const CHARSET_ANSI_JAPANESE_SHIFTJIS = 0x80; + const CHARSET_ANSI_KOREAN_HANGUL = 0x81; + const CHARSET_ANSI_KOREAN_JOHAB = 0x82; + const CHARSET_ANSI_CHINESE_SIMIPLIFIED = 0x86; // gb2312 + const CHARSET_ANSI_CHINESE_TRADITIONAL = 0x88; // big5 + const CHARSET_ANSI_GREEK = 0xA1; + const CHARSET_ANSI_TURKISH = 0xA2; + const CHARSET_ANSI_VIETNAMESE = 0xA3; + const CHARSET_ANSI_HEBREW = 0xB1; + const CHARSET_ANSI_ARABIC = 0xB2; + const CHARSET_ANSI_BALTIC = 0xBA; + const CHARSET_ANSI_CYRILLIC = 0xCC; + const CHARSET_ANSI_THAI = 0xDD; + const CHARSET_ANSI_LATIN_II = 0xEE; + const CHARSET_OEM_LATIN_I = 0xFF; // XXX: Constants created! /** Font filenames */ - const ARIAL = 'arial.ttf'; - const ARIAL_BOLD = 'arialbd.ttf'; - const ARIAL_ITALIC = 'ariali.ttf'; - const ARIAL_BOLD_ITALIC = 'arialbi.ttf'; + const ARIAL = 'arial.ttf'; + const ARIAL_BOLD = 'arialbd.ttf'; + const ARIAL_ITALIC = 'ariali.ttf'; + const ARIAL_BOLD_ITALIC = 'arialbi.ttf'; - const CALIBRI = 'CALIBRI.TTF'; - const CALIBRI_BOLD = 'CALIBRIB.TTF'; - const CALIBRI_ITALIC = 'CALIBRII.TTF'; - const CALIBRI_BOLD_ITALIC = 'CALIBRIZ.TTF'; + const CALIBRI = 'CALIBRI.TTF'; + const CALIBRI_BOLD = 'CALIBRIB.TTF'; + const CALIBRI_ITALIC = 'CALIBRII.TTF'; + const CALIBRI_BOLD_ITALIC = 'CALIBRIZ.TTF'; - const COMIC_SANS_MS = 'comic.ttf'; - const COMIC_SANS_MS_BOLD = 'comicbd.ttf'; + const COMIC_SANS_MS = 'comic.ttf'; + const COMIC_SANS_MS_BOLD = 'comicbd.ttf'; - const COURIER_NEW = 'cour.ttf'; - const COURIER_NEW_BOLD = 'courbd.ttf'; - const COURIER_NEW_ITALIC = 'couri.ttf'; - const COURIER_NEW_BOLD_ITALIC = 'courbi.ttf'; + const COURIER_NEW = 'cour.ttf'; + const COURIER_NEW_BOLD = 'courbd.ttf'; + const COURIER_NEW_ITALIC = 'couri.ttf'; + const COURIER_NEW_BOLD_ITALIC = 'courbi.ttf'; - const GEORGIA = 'georgia.ttf'; - const GEORGIA_BOLD = 'georgiab.ttf'; - const GEORGIA_ITALIC = 'georgiai.ttf'; - const GEORGIA_BOLD_ITALIC = 'georgiaz.ttf'; + const GEORGIA = 'georgia.ttf'; + const GEORGIA_BOLD = 'georgiab.ttf'; + const GEORGIA_ITALIC = 'georgiai.ttf'; + const GEORGIA_BOLD_ITALIC = 'georgiaz.ttf'; - const IMPACT = 'impact.ttf'; + const IMPACT = 'impact.ttf'; - const LIBERATION_SANS = 'LiberationSans-Regular.ttf'; - const LIBERATION_SANS_BOLD = 'LiberationSans-Bold.ttf'; - const LIBERATION_SANS_ITALIC = 'LiberationSans-Italic.ttf'; - const LIBERATION_SANS_BOLD_ITALIC = 'LiberationSans-BoldItalic.ttf'; + const LIBERATION_SANS = 'LiberationSans-Regular.ttf'; + const LIBERATION_SANS_BOLD = 'LiberationSans-Bold.ttf'; + const LIBERATION_SANS_ITALIC = 'LiberationSans-Italic.ttf'; + const LIBERATION_SANS_BOLD_ITALIC = 'LiberationSans-BoldItalic.ttf'; - const LUCIDA_CONSOLE = 'lucon.ttf'; - const LUCIDA_SANS_UNICODE = 'l_10646.ttf'; + const LUCIDA_CONSOLE = 'lucon.ttf'; + const LUCIDA_SANS_UNICODE = 'l_10646.ttf'; - const MICROSOFT_SANS_SERIF = 'micross.ttf'; + const MICROSOFT_SANS_SERIF = 'micross.ttf'; - const PALATINO_LINOTYPE = 'pala.ttf'; - const PALATINO_LINOTYPE_BOLD = 'palab.ttf'; - const PALATINO_LINOTYPE_ITALIC = 'palai.ttf'; - const PALATINO_LINOTYPE_BOLD_ITALIC = 'palabi.ttf'; + const PALATINO_LINOTYPE = 'pala.ttf'; + const PALATINO_LINOTYPE_BOLD = 'palab.ttf'; + const PALATINO_LINOTYPE_ITALIC = 'palai.ttf'; + const PALATINO_LINOTYPE_BOLD_ITALIC = 'palabi.ttf'; - const SYMBOL = 'symbol.ttf'; + const SYMBOL = 'symbol.ttf'; - const TAHOMA = 'tahoma.ttf'; - const TAHOMA_BOLD = 'tahomabd.ttf'; + const TAHOMA = 'tahoma.ttf'; + const TAHOMA_BOLD = 'tahomabd.ttf'; - const TIMES_NEW_ROMAN = 'times.ttf'; - const TIMES_NEW_ROMAN_BOLD = 'timesbd.ttf'; - const TIMES_NEW_ROMAN_ITALIC = 'timesi.ttf'; - const TIMES_NEW_ROMAN_BOLD_ITALIC = 'timesbi.ttf'; + const TIMES_NEW_ROMAN = 'times.ttf'; + const TIMES_NEW_ROMAN_BOLD = 'timesbd.ttf'; + const TIMES_NEW_ROMAN_ITALIC = 'timesi.ttf'; + const TIMES_NEW_ROMAN_BOLD_ITALIC = 'timesbi.ttf'; - const TREBUCHET_MS = 'trebuc.ttf'; - const TREBUCHET_MS_BOLD = 'trebucbd.ttf'; - const TREBUCHET_MS_ITALIC = 'trebucit.ttf'; - const TREBUCHET_MS_BOLD_ITALIC = 'trebucbi.ttf'; + const TREBUCHET_MS = 'trebuc.ttf'; + const TREBUCHET_MS_BOLD = 'trebucbd.ttf'; + const TREBUCHET_MS_ITALIC = 'trebucit.ttf'; + const TREBUCHET_MS_BOLD_ITALIC = 'trebucbi.ttf'; - const VERDANA = 'verdana.ttf'; - const VERDANA_BOLD = 'verdanab.ttf'; - const VERDANA_ITALIC = 'verdanai.ttf'; - const VERDANA_BOLD_ITALIC = 'verdanaz.ttf'; + const VERDANA = 'verdana.ttf'; + const VERDANA_BOLD = 'verdanab.ttf'; + const VERDANA_ITALIC = 'verdanai.ttf'; + const VERDANA_BOLD_ITALIC = 'verdanaz.ttf'; /** * AutoSize method @@ -141,51 +141,51 @@ class Font * * @var array */ - public static $defaultColumnWidths = array( - 'Arial' => array( - 1 => array('px' => 24, 'width' => 12.00000000), - 2 => array('px' => 24, 'width' => 12.00000000), - 3 => array('px' => 32, 'width' => 10.66406250), - 4 => array('px' => 32, 'width' => 10.66406250), - 5 => array('px' => 40, 'width' => 10.00000000), - 6 => array('px' => 48, 'width' => 9.59765625), - 7 => array('px' => 48, 'width' => 9.59765625), - 8 => array('px' => 56, 'width' => 9.33203125), - 9 => array('px' => 64, 'width' => 9.14062500), - 10 => array('px' => 64, 'width' => 9.14062500), - ), - 'Calibri' => array( - 1 => array('px' => 24, 'width' => 12.00000000), - 2 => array('px' => 24, 'width' => 12.00000000), - 3 => array('px' => 32, 'width' => 10.66406250), - 4 => array('px' => 32, 'width' => 10.66406250), - 5 => array('px' => 40, 'width' => 10.00000000), - 6 => array('px' => 48, 'width' => 9.59765625), - 7 => array('px' => 48, 'width' => 9.59765625), - 8 => array('px' => 56, 'width' => 9.33203125), - 9 => array('px' => 56, 'width' => 9.33203125), - 10 => array('px' => 64, 'width' => 9.14062500), - 11 => array('px' => 64, 'width' => 9.14062500), - ), - 'Verdana' => array( - 1 => array('px' => 24, 'width' => 12.00000000), - 2 => array('px' => 24, 'width' => 12.00000000), - 3 => array('px' => 32, 'width' => 10.66406250), - 4 => array('px' => 32, 'width' => 10.66406250), - 5 => array('px' => 40, 'width' => 10.00000000), - 6 => array('px' => 48, 'width' => 9.59765625), - 7 => array('px' => 48, 'width' => 9.59765625), - 8 => array('px' => 64, 'width' => 9.14062500), - 9 => array('px' => 72, 'width' => 9.00000000), - 10 => array('px' => 72, 'width' => 9.00000000), - ), - ); + public static $defaultColumnWidths = [ + 'Arial' => [ + 1 => ['px' => 24, 'width' => 12.00000000], + 2 => ['px' => 24, 'width' => 12.00000000], + 3 => ['px' => 32, 'width' => 10.66406250], + 4 => ['px' => 32, 'width' => 10.66406250], + 5 => ['px' => 40, 'width' => 10.00000000], + 6 => ['px' => 48, 'width' => 9.59765625], + 7 => ['px' => 48, 'width' => 9.59765625], + 8 => ['px' => 56, 'width' => 9.33203125], + 9 => ['px' => 64, 'width' => 9.14062500], + 10 => ['px' => 64, 'width' => 9.14062500], + ], + 'Calibri' => [ + 1 => ['px' => 24, 'width' => 12.00000000], + 2 => ['px' => 24, 'width' => 12.00000000], + 3 => ['px' => 32, 'width' => 10.66406250], + 4 => ['px' => 32, 'width' => 10.66406250], + 5 => ['px' => 40, 'width' => 10.00000000], + 6 => ['px' => 48, 'width' => 9.59765625], + 7 => ['px' => 48, 'width' => 9.59765625], + 8 => ['px' => 56, 'width' => 9.33203125], + 9 => ['px' => 56, 'width' => 9.33203125], + 10 => ['px' => 64, 'width' => 9.14062500], + 11 => ['px' => 64, 'width' => 9.14062500], + ], + 'Verdana' => [ + 1 => ['px' => 24, 'width' => 12.00000000], + 2 => ['px' => 24, 'width' => 12.00000000], + 3 => ['px' => 32, 'width' => 10.66406250], + 4 => ['px' => 32, 'width' => 10.66406250], + 5 => ['px' => 40, 'width' => 10.00000000], + 6 => ['px' => 48, 'width' => 9.59765625], + 7 => ['px' => 48, 'width' => 9.59765625], + 8 => ['px' => 64, 'width' => 9.14062500], + 9 => ['px' => 72, 'width' => 9.00000000], + 10 => ['px' => 72, 'width' => 9.00000000], + ], + ]; /** * Set autoSize method * * @param string $pValue - * @return boolean Success or failure + * @return bool Success or failure */ public static function setAutoSizeMethod($pValue = self::AUTOSIZE_METHOD_APPROX) { @@ -238,9 +238,9 @@ class Font * * @param \PhpSpreadsheet\Style\Font $font Font object * @param \PhpSpreadsheet\RichText|string $cellText Text to calculate width - * @param integer $rotation Rotation angle - * @param \PhpSpreadsheet\Style\Font|NULL $defaultFont Font object - * @return integer Column width + * @param int $rotation Rotation angle + * @param \PhpSpreadsheet\Style\Font|null $defaultFont Font object + * @return int Column width */ public static function calculateColumnWidth(\PhpSpreadsheet\Style\Font $font, $cellText = '', $rotation = 0, \PhpSpreadsheet\Style\Font $defaultFont = null) { @@ -252,10 +252,11 @@ class Font // Special case if there are one or more newline characters ("\n") if (strpos($cellText, "\n") !== false) { $lineTexts = explode("\n", $cellText); - $lineWidths = array(); + $lineWidths = []; foreach ($lineTexts as $lineText) { $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont); } + return max($lineWidths); // width of longest line in cell } @@ -292,8 +293,8 @@ class Font * @param string $text * @param \PhpSpreadsheet\Style\Font * @param int $rotation - * @return int * @throws \PhpSpreadsheet\Exception + * @return int */ public static function getTextWidthPixelsExact($text, \PhpSpreadsheet\Style\Font $font, $rotation = 0) { @@ -307,13 +308,13 @@ class Font $textBox = imagettfbbox($font->getSize(), $rotation, $fontFile, $text); // Get corners positions - $lowerLeftCornerX = $textBox[0]; + $lowerLeftCornerX = $textBox[0]; // $lowerLeftCornerY = $textBox[1]; $lowerRightCornerX = $textBox[2]; // $lowerRightCornerY = $textBox[3]; $upperRightCornerX = $textBox[4]; // $upperRightCornerY = $textBox[5]; - $upperLeftCornerX = $textBox[6]; + $upperLeftCornerX = $textBox[6]; // $upperLeftCornerY = $textBox[7]; // Consider the rotation when calculating the width @@ -399,7 +400,7 @@ class Font */ public static function inchSizeToPixels($sizeInInch = 1) { - return ($sizeInInch * 96); + return $sizeInInch * 96; } /** @@ -410,7 +411,7 @@ class Font */ public static function centimeterSizeToPixels($sizeInCm = 1) { - return ($sizeInCm * 37.795275591); + return $sizeInCm * 37.795275591; } /** @@ -425,8 +426,8 @@ class Font throw new \PhpSpreadsheet\Exception('Valid directory to TrueType Font files not specified'); } - $name = $font->getName(); - $bold = $font->getBold(); + $name = $font->getName(); + $bold = $font->getBold(); $italic = $font->getItalic(); // Check if we can map font to true type font file @@ -511,7 +512,7 @@ class Font ); break; default: - throw new \PhpSpreadsheet\Exception('Unknown font name "'. $name .'". Cannot map to TrueType font file'); + throw new \PhpSpreadsheet\Exception('Unknown font name "' . $name . '". Cannot map to TrueType font file'); break; } @@ -553,7 +554,7 @@ class Font * For example, for Calibri 11 this is 9.140625 (64 px) * * @param \PhpSpreadsheet\Style\Font $font The workbooks default font - * @param boolean $pPixels true = return column width in pixels, false = return in OOXML units + * @param bool $pPixels true = return column width in pixels, false = return in OOXML units * @return mixed Column width */ public static function getDefaultColumnWidthByFont(\PhpSpreadsheet\Style\Font $font, $pPixels = false) diff --git a/src/PhpSpreadsheet/Shared/JAMA/CholeskyDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/CholeskyDecomposition.php index 3ad5dfa8..2f1d1579 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/CholeskyDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/CholeskyDecomposition.php @@ -3,7 +3,6 @@ namespace PhpSpreadsheet\Shared\JAMA; /** - * * Cholesky decomposition class * * For a symmetric, positive definite matrix A, the Cholesky decomposition @@ -22,21 +21,18 @@ class CholeskyDecomposition /** * Decomposition storage * @var array - * @access private */ - private $L = array(); + private $L = []; /** * Matrix row and column dimension * @var int - * @access private */ private $m; /** * Symmetric positive definite flag - * @var boolean - * @access private + * @var bool */ private $isspd = true; @@ -70,7 +66,7 @@ class CholeskyDecomposition } } - for ($k = $i+1; $k < $this->m; ++$k) { + for ($k = $i + 1; $k < $this->m; ++$k) { $this->L[$i][$k] = 0.0; } } @@ -82,7 +78,7 @@ class CholeskyDecomposition /** * Is the matrix symmetric and positive definite? * - * @return boolean + * @return bool */ public function isSPD() { @@ -111,7 +107,7 @@ class CholeskyDecomposition if ($B instanceof Matrix) { if ($B->getRowDimension() == $this->m) { if ($this->isspd) { - $X = $B->getArrayCopy(); + $X = $B->getArrayCopy(); $nx = $B->getColumnDimension(); for ($k = 0; $k < $this->m; ++$k) { diff --git a/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php index 55dfc749..932c66cb 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php @@ -3,7 +3,6 @@ namespace PhpSpreadsheet\Shared\JAMA; /** - * * Class to obtain eigenvalues and eigenvectors of a real matrix. * * If A is symmetric, then A = V*D*V' where the eigenvalue matrix D @@ -41,38 +40,36 @@ class EigenvalueDecomposition * Arrays for internal storage of eigenvalues. * @var array */ - private $d = array(); - private $e = array(); + private $d = []; + private $e = []; /** * Array for internal storage of eigenvectors. * @var array */ - private $V = array(); + private $V = []; /** - * Array for internal storage of nonsymmetric Hessenberg form. - * @var array - */ - private $H = array(); + * Array for internal storage of nonsymmetric Hessenberg form. + * @var array + */ + private $H = []; /** - * Working storage for nonsymmetric algorithm. - * @var array - */ + * Working storage for nonsymmetric algorithm. + * @var array + */ private $ort; /** - * Used for complex scalar division. - * @var float - */ + * Used for complex scalar division. + * @var float + */ private $cdivr; private $cdivi; /** * Symmetric Householder reduction to tridiagonal form. - * - * @access private */ private function tred2() { @@ -80,10 +77,10 @@ class EigenvalueDecomposition // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. - $this->d = $this->V[$this->n-1]; + $this->d = $this->V[$this->n - 1]; // Householder reduction to tridiagonal form. - for ($i = $this->n-1; $i > 0; --$i) { - $i_ = $i -1; + for ($i = $this->n - 1; $i > 0; --$i) { + $i_ = $i - 1; // Scale to avoid under/overflow. $h = $scale = 0.0; $scale += array_sum(array_map(abs, $this->d)); @@ -115,7 +112,7 @@ class EigenvalueDecomposition $f = $this->d[$j]; $this->V[$j][$i] = $f; $g = $this->e[$j] + $this->V[$j][$j] * $f; - for ($k = $j+1; $k <= $i_; ++$k) { + for ($k = $j + 1; $k <= $i_; ++$k) { $g += $this->V[$k][$j] * $this->d[$k]; $this->e[$k] += $this->V[$k][$j] * $f; } @@ -127,7 +124,7 @@ class EigenvalueDecomposition $f += $this->e[$j] * $this->d[$j]; } $hh = $f / (2 * $h); - for ($j=0; $j < $i; ++$j) { + for ($j = 0; $j < $i; ++$j) { $this->e[$j] -= $hh * $this->d[$j]; } for ($j = 0; $j < $i; ++$j) { @@ -136,7 +133,7 @@ class EigenvalueDecomposition for ($k = $j; $k <= $i_; ++$k) { $this->V[$k][$j] -= ($f * $this->e[$k] + $g * $this->d[$k]); } - $this->d[$j] = $this->V[$i-1][$j]; + $this->d[$j] = $this->V[$i - 1][$j]; $this->V[$i][$j] = 0.0; } } @@ -144,18 +141,18 @@ class EigenvalueDecomposition } // Accumulate transformations. - for ($i = 0; $i < $this->n-1; ++$i) { - $this->V[$this->n-1][$i] = $this->V[$i][$i]; + for ($i = 0; $i < $this->n - 1; ++$i) { + $this->V[$this->n - 1][$i] = $this->V[$i][$i]; $this->V[$i][$i] = 1.0; - $h = $this->d[$i+1]; + $h = $this->d[$i + 1]; if ($h != 0.0) { for ($k = 0; $k <= $i; ++$k) { - $this->d[$k] = $this->V[$k][$i+1] / $h; + $this->d[$k] = $this->V[$k][$i + 1] / $h; } for ($j = 0; $j <= $i; ++$j) { $g = 0.0; for ($k = 0; $k <= $i; ++$k) { - $g += $this->V[$k][$i+1] * $this->V[$k][$j]; + $g += $this->V[$k][$i + 1] * $this->V[$k][$j]; } for ($k = 0; $k <= $i; ++$k) { $this->V[$k][$j] -= $g * $this->d[$k]; @@ -163,13 +160,13 @@ class EigenvalueDecomposition } } for ($k = 0; $k <= $i; ++$k) { - $this->V[$k][$i+1] = 0.0; + $this->V[$k][$i + 1] = 0.0; } } - $this->d = $this->V[$this->n-1]; - $this->V[$this->n-1] = array_fill(0, $j, 0.0); - $this->V[$this->n-1][$this->n-1] = 1.0; + $this->d = $this->V[$this->n - 1]; + $this->V[$this->n - 1] = array_fill(0, $j, 0.0); + $this->V[$this->n - 1][$this->n - 1] = 1.0; $this->e[0] = 0.0; } @@ -180,18 +177,16 @@ class EigenvalueDecomposition * Bowdler, Martin, Reinsch, and Wilkinson, Handbook for * Auto. Comp., Vol.ii-Linear Algebra, and the corresponding * Fortran subroutine in EISPACK. - * - * @access private */ private function tql2() { for ($i = 1; $i < $this->n; ++$i) { - $this->e[$i-1] = $this->e[$i]; + $this->e[$i - 1] = $this->e[$i]; } - $this->e[$this->n-1] = 0.0; + $this->e[$this->n - 1] = 0.0; $f = 0.0; $tst1 = 0.0; - $eps = pow(2.0, -52.0); + $eps = pow(2.0, -52.0); for ($l = 0; $l < $this->n; ++$l) { // Find small subdiagonal element @@ -212,14 +207,14 @@ class EigenvalueDecomposition $iter += 1; // Compute implicit shift $g = $this->d[$l]; - $p = ($this->d[$l+1] - $g) / (2.0 * $this->e[$l]); + $p = ($this->d[$l + 1] - $g) / (2.0 * $this->e[$l]); $r = hypo($p, 1.0); if ($p < 0) { $r *= -1; } $this->d[$l] = $this->e[$l] / ($p + $r); - $this->d[$l+1] = $this->e[$l] * ($p + $r); - $dl1 = $this->d[$l+1]; + $this->d[$l + 1] = $this->e[$l] * ($p + $r); + $dl1 = $this->d[$l + 1]; $h = $g - $this->d[$l]; for ($i = $l + 2; $i < $this->n; ++$i) { $this->d[$i] -= $h; @@ -231,22 +226,22 @@ class EigenvalueDecomposition $c2 = $c3 = $c; $el1 = $this->e[$l + 1]; $s = $s2 = 0.0; - for ($i = $m-1; $i >= $l; --$i) { + for ($i = $m - 1; $i >= $l; --$i) { $c3 = $c2; $c2 = $c; $s2 = $s; - $g = $c * $this->e[$i]; - $h = $c * $p; - $r = hypo($p, $this->e[$i]); - $this->e[$i+1] = $s * $r; + $g = $c * $this->e[$i]; + $h = $c * $p; + $r = hypo($p, $this->e[$i]); + $this->e[$i + 1] = $s * $r; $s = $this->e[$i] / $r; $c = $p / $r; $p = $c * $this->d[$i] - $s * $g; - $this->d[$i+1] = $h + $s * ($c * $g + $s * $this->d[$i]); + $this->d[$i + 1] = $h + $s * ($c * $g + $s * $this->d[$i]); // Accumulate transformation. for ($k = 0; $k < $this->n; ++$k) { - $h = $this->V[$k][$i+1]; - $this->V[$k][$i+1] = $s * $this->V[$k][$i] + $c * $h; + $h = $this->V[$k][$i + 1]; + $this->V[$k][$i + 1] = $s * $this->V[$k][$i] + $c * $h; $this->V[$k][$i] = $c * $this->V[$k][$i] - $s * $h; } } @@ -264,7 +259,7 @@ class EigenvalueDecomposition for ($i = 0; $i < $this->n - 1; ++$i) { $k = $i; $p = $this->d[$i]; - for ($j = $i+1; $j < $this->n; ++$j) { + for ($j = $i + 1; $j < $this->n; ++$j) { if ($this->d[$j] < $p) { $k = $j; $p = $this->d[$j]; @@ -289,25 +284,23 @@ class EigenvalueDecomposition * by Martin and Wilkinson, Handbook for Auto. Comp., * Vol.ii-Linear Algebra, and the corresponding * Fortran subroutines in EISPACK. - * - * @access private */ private function orthes() { - $low = 0; - $high = $this->n-1; + $low = 0; + $high = $this->n - 1; - for ($m = $low+1; $m <= $high-1; ++$m) { + for ($m = $low + 1; $m <= $high - 1; ++$m) { // Scale column. $scale = 0.0; for ($i = $m; $i <= $high; ++$i) { - $scale = $scale + abs($this->H[$i][$m-1]); + $scale = $scale + abs($this->H[$i][$m - 1]); } if ($scale != 0.0) { // Compute Householder transformation. $h = 0.0; for ($i = $high; $i >= $m; --$i) { - $this->ort[$i] = $this->H[$i][$m-1] / $scale; + $this->ort[$i] = $this->H[$i][$m - 1] / $scale; $h += $this->ort[$i] * $this->ort[$i]; } $g = sqrt($h); @@ -339,7 +332,7 @@ class EigenvalueDecomposition } } $this->ort[$m] = $scale * $this->ort[$m]; - $this->H[$m][$m-1] = $scale * $g; + $this->H[$m][$m - 1] = $scale * $g; } } @@ -349,10 +342,10 @@ class EigenvalueDecomposition $this->V[$i][$j] = ($i == $j ? 1.0 : 0.0); } } - for ($m = $high-1; $m >= $low+1; --$m) { - if ($this->H[$m][$m-1] != 0.0) { - for ($i = $m+1; $i <= $high; ++$i) { - $this->ort[$i] = $this->H[$i][$m-1]; + for ($m = $high - 1; $m >= $low + 1; --$m) { + if ($this->H[$m][$m - 1] != 0.0) { + for ($i = $m + 1; $i <= $high; ++$i) { + $this->ort[$i] = $this->H[$i][$m - 1]; } for ($j = $m; $j <= $high; ++$j) { $g = 0.0; @@ -360,7 +353,7 @@ class EigenvalueDecomposition $g += $this->ort[$i] * $this->V[$i][$j]; } // Double division avoids possible underflow - $g = ($g / $this->ort[$m]) / $this->H[$m][$m-1]; + $g = ($g / $this->ort[$m]) / $this->H[$m][$m - 1]; for ($i = $m; $i <= $high; ++$i) { $this->V[$i][$j] += $g * $this->ort[$i]; } @@ -371,8 +364,6 @@ class EigenvalueDecomposition /** * Performs complex division. - * - * @access private */ private function cdiv($xr, $xi, $yr, $yi) { @@ -396,14 +387,12 @@ class EigenvalueDecomposition * by Martin and Wilkinson, Handbook for Auto. Comp., * Vol.ii-Linear Algebra, and the corresponding * Fortran subroutine in EISPACK. - * - * @access private */ private function hqr2() { // Initialize $nn = $this->n; - $n = $nn - 1; + $n = $nn - 1; $low = 0; $high = $nn - 1; $eps = pow(2.0, -52.0); @@ -417,7 +406,7 @@ class EigenvalueDecomposition $this->d[$i] = $this->H[$i][$i]; $this->e[$i] = 0.0; } - for ($j = max($i-1, 0); $j < $nn; ++$j) { + for ($j = max($i - 1, 0); $j < $nn; ++$j) { $norm = $norm + abs($this->H[$i][$j]); } } @@ -428,11 +417,11 @@ class EigenvalueDecomposition // Look for single small sub-diagonal element $l = $n; while ($l > $low) { - $s = abs($this->H[$l-1][$l-1]) + abs($this->H[$l][$l]); + $s = abs($this->H[$l - 1][$l - 1]) + abs($this->H[$l][$l]); if ($s == 0.0) { $s = $norm; } - if (abs($this->H[$l][$l-1]) < $eps * $s) { + if (abs($this->H[$l][$l - 1]) < $eps * $s) { break; } --$l; @@ -446,13 +435,13 @@ class EigenvalueDecomposition --$n; $iter = 0; // Two roots found - } elseif ($l == $n-1) { - $w = $this->H[$n][$n-1] * $this->H[$n-1][$n]; - $p = ($this->H[$n-1][$n-1] - $this->H[$n][$n]) / 2.0; + } elseif ($l == $n - 1) { + $w = $this->H[$n][$n - 1] * $this->H[$n - 1][$n]; + $p = ($this->H[$n - 1][$n - 1] - $this->H[$n][$n]) / 2.0; $q = $p * $p + $w; $z = sqrt(abs($q)); $this->H[$n][$n] = $this->H[$n][$n] + $exshift; - $this->H[$n-1][$n-1] = $this->H[$n-1][$n-1] + $exshift; + $this->H[$n - 1][$n - 1] = $this->H[$n - 1][$n - 1] + $exshift; $x = $this->H[$n][$n]; // Real pair if ($q >= 0) { @@ -461,14 +450,14 @@ class EigenvalueDecomposition } else { $z = $p - $z; } - $this->d[$n-1] = $x + $z; - $this->d[$n] = $this->d[$n-1]; + $this->d[$n - 1] = $x + $z; + $this->d[$n] = $this->d[$n - 1]; if ($z != 0.0) { $this->d[$n] = $x - $w / $z; } - $this->e[$n-1] = 0.0; + $this->e[$n - 1] = 0.0; $this->e[$n] = 0.0; - $x = $this->H[$n][$n-1]; + $x = $this->H[$n][$n - 1]; $s = abs($x) + abs($z); $p = $x / $s; $q = $z / $s; @@ -476,28 +465,28 @@ class EigenvalueDecomposition $p = $p / $r; $q = $q / $r; // Row modification - for ($j = $n-1; $j < $nn; ++$j) { - $z = $this->H[$n-1][$j]; - $this->H[$n-1][$j] = $q * $z + $p * $this->H[$n][$j]; + for ($j = $n - 1; $j < $nn; ++$j) { + $z = $this->H[$n - 1][$j]; + $this->H[$n - 1][$j] = $q * $z + $p * $this->H[$n][$j]; $this->H[$n][$j] = $q * $this->H[$n][$j] - $p * $z; } // Column modification for ($i = 0; $i <= $n; ++$i) { - $z = $this->H[$i][$n-1]; - $this->H[$i][$n-1] = $q * $z + $p * $this->H[$i][$n]; + $z = $this->H[$i][$n - 1]; + $this->H[$i][$n - 1] = $q * $z + $p * $this->H[$i][$n]; $this->H[$i][$n] = $q * $this->H[$i][$n] - $p * $z; } // Accumulate transformations for ($i = $low; $i <= $high; ++$i) { - $z = $this->V[$i][$n-1]; - $this->V[$i][$n-1] = $q * $z + $p * $this->V[$i][$n]; + $z = $this->V[$i][$n - 1]; + $this->V[$i][$n - 1] = $q * $z + $p * $this->V[$i][$n]; $this->V[$i][$n] = $q * $this->V[$i][$n] - $p * $z; } // Complex pair } else { - $this->d[$n-1] = $x + $p; + $this->d[$n - 1] = $x + $p; $this->d[$n] = $x + $p; - $this->e[$n-1] = $z; + $this->e[$n - 1] = $z; $this->e[$n] = -$z; } $n = $n - 2; @@ -509,8 +498,8 @@ class EigenvalueDecomposition $y = 0.0; $w = 0.0; if ($l < $n) { - $y = $this->H[$n-1][$n-1]; - $w = $this->H[$n][$n-1] * $this->H[$n-1][$n]; + $y = $this->H[$n - 1][$n - 1]; + $w = $this->H[$n][$n - 1] * $this->H[$n - 1][$n]; } // Wilkinson's original ad hoc shift if ($iter == 10) { @@ -518,7 +507,7 @@ class EigenvalueDecomposition for ($i = $low; $i <= $n; ++$i) { $this->H[$i][$i] -= $x; } - $s = abs($this->H[$n][$n-1]) + abs($this->H[$n-1][$n-2]); + $s = abs($this->H[$n][$n - 1]) + abs($this->H[$n - 1][$n - 2]); $x = $y = 0.75 * $s; $w = -0.4375 * $s * $s; } @@ -547,9 +536,9 @@ class EigenvalueDecomposition $z = $this->H[$m][$m]; $r = $x - $z; $s = $y - $z; - $p = ($r * $s - $w) / $this->H[$m+1][$m] + $this->H[$m][$m+1]; - $q = $this->H[$m+1][$m+1] - $z - $r - $s; - $r = $this->H[$m+2][$m+1]; + $p = ($r * $s - $w) / $this->H[$m + 1][$m] + $this->H[$m][$m + 1]; + $q = $this->H[$m + 1][$m + 1] - $z - $r - $s; + $r = $this->H[$m + 2][$m + 1]; $s = abs($p) + abs($q) + abs($r); $p = $p / $s; $q = $q / $s; @@ -557,25 +546,25 @@ class EigenvalueDecomposition if ($m == $l) { break; } - if (abs($this->H[$m][$m-1]) * (abs($q) + abs($r)) < - $eps * (abs($p) * (abs($this->H[$m-1][$m-1]) + abs($z) + abs($this->H[$m+1][$m+1])))) { + if (abs($this->H[$m][$m - 1]) * (abs($q) + abs($r)) < + $eps * (abs($p) * (abs($this->H[$m - 1][$m - 1]) + abs($z) + abs($this->H[$m + 1][$m + 1])))) { break; } --$m; } for ($i = $m + 2; $i <= $n; ++$i) { - $this->H[$i][$i-2] = 0.0; - if ($i > $m+2) { - $this->H[$i][$i-3] = 0.0; + $this->H[$i][$i - 2] = 0.0; + if ($i > $m + 2) { + $this->H[$i][$i - 3] = 0.0; } } // Double QR step involving rows l:n and columns m:n - for ($k = $m; $k <= $n-1; ++$k) { - $notlast = ($k != $n-1); + for ($k = $m; $k <= $n - 1; ++$k) { + $notlast = ($k != $n - 1); if ($k != $m) { - $p = $this->H[$k][$k-1]; - $q = $this->H[$k+1][$k-1]; - $r = ($notlast ? $this->H[$k+2][$k-1] : 0.0); + $p = $this->H[$k][$k - 1]; + $q = $this->H[$k + 1][$k - 1]; + $r = ($notlast ? $this->H[$k + 2][$k - 1] : 0.0); $x = abs($p) + abs($q) + abs($r); if ($x != 0.0) { $p = $p / $x; @@ -592,9 +581,9 @@ class EigenvalueDecomposition } if ($s != 0) { if ($k != $m) { - $this->H[$k][$k-1] = -$s * $x; + $this->H[$k][$k - 1] = -$s * $x; } elseif ($l != $m) { - $this->H[$k][$k-1] = -$this->H[$k][$k-1]; + $this->H[$k][$k - 1] = -$this->H[$k][$k - 1]; } $p = $p + $s; $x = $p / $s; @@ -604,33 +593,33 @@ class EigenvalueDecomposition $r = $r / $p; // Row modification for ($j = $k; $j < $nn; ++$j) { - $p = $this->H[$k][$j] + $q * $this->H[$k+1][$j]; + $p = $this->H[$k][$j] + $q * $this->H[$k + 1][$j]; if ($notlast) { - $p = $p + $r * $this->H[$k+2][$j]; - $this->H[$k+2][$j] = $this->H[$k+2][$j] - $p * $z; + $p = $p + $r * $this->H[$k + 2][$j]; + $this->H[$k + 2][$j] = $this->H[$k + 2][$j] - $p * $z; } $this->H[$k][$j] = $this->H[$k][$j] - $p * $x; - $this->H[$k+1][$j] = $this->H[$k+1][$j] - $p * $y; + $this->H[$k + 1][$j] = $this->H[$k + 1][$j] - $p * $y; } // Column modification - for ($i = 0; $i <= min($n, $k+3); ++$i) { - $p = $x * $this->H[$i][$k] + $y * $this->H[$i][$k+1]; + for ($i = 0; $i <= min($n, $k + 3); ++$i) { + $p = $x * $this->H[$i][$k] + $y * $this->H[$i][$k + 1]; if ($notlast) { - $p = $p + $z * $this->H[$i][$k+2]; - $this->H[$i][$k+2] = $this->H[$i][$k+2] - $p * $r; + $p = $p + $z * $this->H[$i][$k + 2]; + $this->H[$i][$k + 2] = $this->H[$i][$k + 2] - $p * $r; } $this->H[$i][$k] = $this->H[$i][$k] - $p; - $this->H[$i][$k+1] = $this->H[$i][$k+1] - $p * $q; + $this->H[$i][$k + 1] = $this->H[$i][$k + 1] - $p * $q; } // Accumulate transformations for ($i = $low; $i <= $high; ++$i) { - $p = $x * $this->V[$i][$k] + $y * $this->V[$i][$k+1]; + $p = $x * $this->V[$i][$k] + $y * $this->V[$i][$k + 1]; if ($notlast) { - $p = $p + $z * $this->V[$i][$k+2]; - $this->V[$i][$k+2] = $this->V[$i][$k+2] - $p * $r; + $p = $p + $z * $this->V[$i][$k + 2]; + $this->V[$i][$k + 2] = $this->V[$i][$k + 2] - $p * $r; } $this->V[$i][$k] = $this->V[$i][$k] - $p; - $this->V[$i][$k+1] = $this->V[$i][$k+1] - $p * $q; + $this->V[$i][$k + 1] = $this->V[$i][$k + 1] - $p * $q; } } // ($s != 0) } // k loop @@ -642,14 +631,14 @@ class EigenvalueDecomposition return; } - for ($n = $nn-1; $n >= 0; --$n) { + for ($n = $nn - 1; $n >= 0; --$n) { $p = $this->d[$n]; $q = $this->e[$n]; // Real vector if ($q == 0) { $l = $n; $this->H[$n][$n] = 1.0; - for ($i = $n-1; $i >= 0; --$i) { + for ($i = $n - 1; $i >= 0; --$i) { $w = $this->H[$i][$i] - $p; $r = 0.0; for ($j = $l; $j <= $n; ++$j) { @@ -668,15 +657,15 @@ class EigenvalueDecomposition } // Solve real equations } else { - $x = $this->H[$i][$i+1]; - $y = $this->H[$i+1][$i]; + $x = $this->H[$i][$i + 1]; + $y = $this->H[$i + 1][$i]; $q = ($this->d[$i] - $p) * ($this->d[$i] - $p) + $this->e[$i] * $this->e[$i]; $t = ($x * $s - $z * $r) / $q; $this->H[$i][$n] = $t; if (abs($x) > abs($z)) { - $this->H[$i+1][$n] = (-$r - $w * $t) / $x; + $this->H[$i + 1][$n] = (-$r - $w * $t) / $x; } else { - $this->H[$i+1][$n] = (-$s - $y * $t) / $z; + $this->H[$i + 1][$n] = (-$s - $y * $t) / $z; } } // Overflow control @@ -690,24 +679,24 @@ class EigenvalueDecomposition } // Complex vector } elseif ($q < 0) { - $l = $n-1; + $l = $n - 1; // Last vector component imaginary so matrix is triangular - if (abs($this->H[$n][$n-1]) > abs($this->H[$n-1][$n])) { - $this->H[$n-1][$n-1] = $q / $this->H[$n][$n-1]; - $this->H[$n-1][$n] = -($this->H[$n][$n] - $p) / $this->H[$n][$n-1]; + if (abs($this->H[$n][$n - 1]) > abs($this->H[$n - 1][$n])) { + $this->H[$n - 1][$n - 1] = $q / $this->H[$n][$n - 1]; + $this->H[$n - 1][$n] = -($this->H[$n][$n] - $p) / $this->H[$n][$n - 1]; } else { - $this->cdiv(0.0, -$this->H[$n-1][$n], $this->H[$n-1][$n-1] - $p, $q); - $this->H[$n-1][$n-1] = $this->cdivr; - $this->H[$n-1][$n] = $this->cdivi; + $this->cdiv(0.0, -$this->H[$n - 1][$n], $this->H[$n - 1][$n - 1] - $p, $q); + $this->H[$n - 1][$n - 1] = $this->cdivr; + $this->H[$n - 1][$n] = $this->cdivi; } - $this->H[$n][$n-1] = 0.0; + $this->H[$n][$n - 1] = 0.0; $this->H[$n][$n] = 1.0; - for ($i = $n-2; $i >= 0; --$i) { + for ($i = $n - 2; $i >= 0; --$i) { // double ra,sa,vr,vi; $ra = 0.0; $sa = 0.0; for ($j = $l; $j <= $n; ++$j) { - $ra = $ra + $this->H[$i][$j] * $this->H[$j][$n-1]; + $ra = $ra + $this->H[$i][$j] * $this->H[$j][$n - 1]; $sa = $sa + $this->H[$i][$j] * $this->H[$j][$n]; } $w = $this->H[$i][$i] - $p; @@ -719,35 +708,35 @@ class EigenvalueDecomposition $l = $i; if ($this->e[$i] == 0) { $this->cdiv(-$ra, -$sa, $w, $q); - $this->H[$i][$n-1] = $this->cdivr; - $this->H[$i][$n] = $this->cdivi; + $this->H[$i][$n - 1] = $this->cdivr; + $this->H[$i][$n] = $this->cdivi; } else { // Solve complex equations - $x = $this->H[$i][$i+1]; - $y = $this->H[$i+1][$i]; + $x = $this->H[$i][$i + 1]; + $y = $this->H[$i + 1][$i]; $vr = ($this->d[$i] - $p) * ($this->d[$i] - $p) + $this->e[$i] * $this->e[$i] - $q * $q; $vi = ($this->d[$i] - $p) * 2.0 * $q; if ($vr == 0.0 & $vi == 0.0) { $vr = $eps * $norm * (abs($w) + abs($q) + abs($x) + abs($y) + abs($z)); } $this->cdiv($x * $r - $z * $ra + $q * $sa, $x * $s - $z * $sa - $q * $ra, $vr, $vi); - $this->H[$i][$n-1] = $this->cdivr; - $this->H[$i][$n] = $this->cdivi; + $this->H[$i][$n - 1] = $this->cdivr; + $this->H[$i][$n] = $this->cdivi; if (abs($x) > (abs($z) + abs($q))) { - $this->H[$i+1][$n-1] = (-$ra - $w * $this->H[$i][$n-1] + $q * $this->H[$i][$n]) / $x; - $this->H[$i+1][$n] = (-$sa - $w * $this->H[$i][$n] - $q * $this->H[$i][$n-1]) / $x; + $this->H[$i + 1][$n - 1] = (-$ra - $w * $this->H[$i][$n - 1] + $q * $this->H[$i][$n]) / $x; + $this->H[$i + 1][$n] = (-$sa - $w * $this->H[$i][$n] - $q * $this->H[$i][$n - 1]) / $x; } else { - $this->cdiv(-$r - $y * $this->H[$i][$n-1], -$s - $y * $this->H[$i][$n], $z, $q); - $this->H[$i+1][$n-1] = $this->cdivr; - $this->H[$i+1][$n] = $this->cdivi; + $this->cdiv(-$r - $y * $this->H[$i][$n - 1], -$s - $y * $this->H[$i][$n], $z, $q); + $this->H[$i + 1][$n - 1] = $this->cdivr; + $this->H[$i + 1][$n] = $this->cdivi; } } // Overflow control - $t = max(abs($this->H[$i][$n-1]), abs($this->H[$i][$n])); + $t = max(abs($this->H[$i][$n - 1]), abs($this->H[$i][$n])); if (($eps * $t) * $t > 1) { for ($j = $i; $j <= $n; ++$j) { - $this->H[$j][$n-1] = $this->H[$j][$n-1] / $t; - $this->H[$j][$n] = $this->H[$j][$n] / $t; + $this->H[$j][$n - 1] = $this->H[$j][$n - 1] / $t; + $this->H[$j][$n] = $this->H[$j][$n] / $t; } } } // end else @@ -765,7 +754,7 @@ class EigenvalueDecomposition } // Back transformation to get eigenvectors of original matrix - for ($j = $nn-1; $j >= $low; --$j) { + for ($j = $nn - 1; $j >= $low; --$j) { for ($i = $low; $i <= $high; ++$i) { $z = 0.0; for ($k = $low; $k <= min($j, $high); ++$k) { @@ -779,7 +768,6 @@ class EigenvalueDecomposition /** * Constructor: Check for symmetry, then construct the eigenvalue decomposition * - * @access public * @param A Square matrix * @return Structure to access D and V. */ @@ -803,7 +791,7 @@ class EigenvalueDecomposition $this->tql2(); } else { $this->H = $this->A; - $this->ort = array(); + $this->ort = []; // Reduce to Hessenberg form. $this->orthes(); // Reduce Hessenberg to real Schur form. @@ -814,7 +802,6 @@ class EigenvalueDecomposition /** * Return the eigenvector matrix * - * @access public * @return V */ public function getV() @@ -825,7 +812,6 @@ class EigenvalueDecomposition /** * Return the real parts of the eigenvalues * - * @access public * @return real(diag(D)) */ public function getRealEigenvalues() @@ -836,7 +822,6 @@ class EigenvalueDecomposition /** * Return the imaginary parts of the eigenvalues * - * @access public * @return imag(diag(D)) */ public function getImagEigenvalues() @@ -847,7 +832,6 @@ class EigenvalueDecomposition /** * Return the block diagonal eigenvalue matrix * - * @access public * @return D */ public function getD() @@ -861,6 +845,7 @@ class EigenvalueDecomposition $o = ($this->e[$i] > 0) ? $i + 1 : $i - 1; $D[$i][$o] = $this->e[$i]; } + return new Matrix($D); } } diff --git a/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php index 4edd2b45..bff3c6f9 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php @@ -3,7 +3,6 @@ namespace PhpSpreadsheet\Shared\JAMA; /** - * * For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n * unit lower triangular matrix L, an n-by-n upper triangular matrix U, * and a permutation vector piv of length m so that A(piv,:) = L*U. @@ -22,14 +21,14 @@ namespace PhpSpreadsheet\Shared\JAMA; */ class LUDecomposition { - const MATRIX_SINGULAR_EXCEPTION = "Can only perform operation on singular matrix."; - const MATRIX_SQUARE_EXCEPTION = "Mismatched Row dimension"; + const MATRIX_SINGULAR_EXCEPTION = 'Can only perform operation on singular matrix.'; + const MATRIX_SQUARE_EXCEPTION = 'Mismatched Row dimension'; /** * Decomposition storage * @var array */ - private $LU = array(); + private $LU = []; /** * Row dimension. @@ -53,7 +52,7 @@ class LUDecomposition * Internal storage of pivot vector. * @var array */ - private $piv = array(); + private $piv = []; /** * LU Decomposition constructor. @@ -66,13 +65,13 @@ class LUDecomposition if ($A instanceof Matrix) { // Use a "left-looking", dot-product, Crout/Doolittle algorithm. $this->LU = $A->getArray(); - $this->m = $A->getRowDimension(); - $this->n = $A->getColumnDimension(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); for ($i = 0; $i < $this->m; ++$i) { $this->piv[$i] = $i; } $this->pivsign = 1; - $LUrowi = $LUcolj = array(); + $LUrowi = $LUcolj = []; // Outer loop. for ($j = 0; $j < $this->n; ++$j) { @@ -93,7 +92,7 @@ class LUDecomposition } // Find pivot and exchange if necessary. $p = $j; - for ($i = $j+1; $i < $this->m; ++$i) { + for ($i = $j + 1; $i < $this->m; ++$i) { if (abs($LUcolj[$i]) > abs($LUcolj[$p])) { $p = $i; } @@ -111,7 +110,7 @@ class LUDecomposition } // Compute multipliers. if (($j < $this->m) && ($this->LU[$j][$j] != 0.0)) { - for ($i = $j+1; $i < $this->m; ++$i) { + for ($i = $j + 1; $i < $this->m; ++$i) { $this->LU[$i][$j] /= $this->LU[$j][$j]; } } @@ -139,6 +138,7 @@ class LUDecomposition } } } + return new Matrix($L); } // function getL() @@ -158,6 +158,7 @@ class LUDecomposition } } } + return new Matrix($U); } // function getU() @@ -193,6 +194,7 @@ class LUDecomposition return false; } } + return true; } // function isNonsingular() @@ -208,6 +210,7 @@ class LUDecomposition for ($j = 0; $j < $this->n; ++$j) { $d *= $this->LU[$j][$j]; } + return $d; } else { throw new \PhpSpreadsheet\Calculation\Exception(Matrix::MATRIX_DIMENSION_EXCEPTION); @@ -228,17 +231,17 @@ class LUDecomposition if ($this->isNonsingular()) { // Copy right hand side with pivoting $nx = $B->getColumnDimension(); - $X = $B->getMatrix($this->piv, 0, $nx-1); + $X = $B->getMatrix($this->piv, 0, $nx - 1); // Solve L*Y = B(piv,:) for ($k = 0; $k < $this->n; ++$k) { - for ($i = $k+1; $i < $this->n; ++$i) { + for ($i = $k + 1; $i < $this->n; ++$i) { for ($j = 0; $j < $nx; ++$j) { $X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k]; } } } // Solve U*X = Y; - for ($k = $this->n-1; $k >= 0; --$k) { + for ($k = $this->n - 1; $k >= 0; --$k) { for ($j = 0; $j < $nx; ++$j) { $X->A[$k][$j] /= $this->LU[$k][$k]; } @@ -248,6 +251,7 @@ class LUDecomposition } } } + return $X; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::MATRIX_SINGULAR_EXCEPTION); diff --git a/src/PhpSpreadsheet/Shared/JAMA/Matrix.php b/src/PhpSpreadsheet/Shared/JAMA/Matrix.php index bd384123..028be1a3 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/Matrix.php +++ b/src/PhpSpreadsheet/Shared/JAMA/Matrix.php @@ -15,25 +15,23 @@ namespace PhpSpreadsheet\Shared\JAMA; */ class Matrix { - const POLYMORPHIC_ARGUMENT_EXCEPTION = "Invalid argument pattern for polymorphic function."; - const ARGUMENT_TYPE_EXCEPTION = "Invalid argument type."; - const ARGUMENT_BOUNDS_EXCEPTION = "Invalid argument range."; - const MATRIX_DIMENSION_EXCEPTION = "Matrix dimensions are not equal."; - const ARRAY_LENGTH_EXCEPTION = "Array length must be a multiple of m."; + const POLYMORPHIC_ARGUMENT_EXCEPTION = 'Invalid argument pattern for polymorphic function.'; + const ARGUMENT_TYPE_EXCEPTION = 'Invalid argument type.'; + const ARGUMENT_BOUNDS_EXCEPTION = 'Invalid argument range.'; + const MATRIX_DIMENSION_EXCEPTION = 'Matrix dimensions are not equal.'; + const ARRAY_LENGTH_EXCEPTION = 'Array length must be a multiple of m.'; /** * Matrix storage * * @var array - * @access public */ - public $A = array(); + public $A = []; /** * Matrix row dimension * * @var int - * @access private */ private $m; @@ -41,7 +39,6 @@ class Matrix * Matrix column dimension * * @var int - * @access private */ private $n; @@ -54,7 +51,7 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { //Rectangular matrix - m x n initialized from 2D array @@ -159,7 +156,7 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { //A($i0...; $j0...) @@ -175,12 +172,13 @@ class Matrix } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_BOUNDS_EXCEPTION); } - $R = new Matrix($m, $n); + $R = new self($m, $n); for ($i = $i0; $i < $this->m; ++$i) { for ($j = $j0; $j < $this->n; ++$j) { $R->set($i, $j, $this->A[$i][$j]); } } + return $R; break; //A($i0...$iF; $j0...$jF) @@ -196,12 +194,13 @@ class Matrix } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_BOUNDS_EXCEPTION); } - $R = new Matrix($m+1, $n+1); + $R = new self($m + 1, $n + 1); for ($i = $i0; $i <= $iF; ++$i) { for ($j = $j0; $j <= $jF; ++$j) { $R->set($i - $i0, $j - $j0, $this->A[$i][$j]); } } + return $R; break; //$R = array of row indices; $C = array of column indices @@ -217,12 +216,13 @@ class Matrix } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_BOUNDS_EXCEPTION); } - $R = new Matrix($m, $n); + $R = new self($m, $n); for ($i = 0; $i < $m; ++$i) { for ($j = 0; $j < $n; ++$j) { $R->set($i - $i0, $j - $j0, $this->A[$RL[$i]][$CL[$j]]); } } + return $R; break; //$RL = array of row indices; $CL = array of column indices @@ -238,12 +238,13 @@ class Matrix } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_BOUNDS_EXCEPTION); } - $R = new Matrix($m, $n); + $R = new self($m, $n); for ($i = 0; $i < $m; ++$i) { for ($j = 0; $j < $n; ++$j) { $R->set($i, $j, $this->A[$RL[$i]][$CL[$j]]); } } + return $R; break; //A($i0...$iF); $CL = array of column indices @@ -259,12 +260,13 @@ class Matrix } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_BOUNDS_EXCEPTION); } - $R = new Matrix($m, $n); + $R = new self($m, $n); for ($i = $i0; $i < $iF; ++$i) { for ($j = 0; $j < $n; ++$j) { $R->set($i - $i0, $j, $this->A[$RL[$i]][$j]); } } + return $R; break; //$RL = array of row indices @@ -280,12 +282,13 @@ class Matrix } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_BOUNDS_EXCEPTION); } - $R = new Matrix($m, $n+1); + $R = new self($m, $n + 1); for ($i = 0; $i < $m; ++$i) { for ($j = $j0; $j <= $jF; ++$j) { $R->set($i, $j - $j0, $this->A[$RL[$i]][$j]); } } + return $R; break; default: @@ -302,11 +305,11 @@ class Matrix * * Is matrix B the same size? * @param Matrix $B Matrix B - * @return boolean + * @return bool */ public function checkMatrixDimensions($B = null) { - if ($B instanceof Matrix) { + if ($B instanceof self) { if (($this->m == $B->getRowDimension()) && ($this->n == $B->getColumnDimension())) { return true; } else { @@ -356,10 +359,11 @@ class Matrix */ public function diagonal($m = null, $n = null, $c = 1) { - $R = new Matrix($m, $n); + $R = new self($m, $n); for ($i = 0; $i < $m; ++$i) { $R->set($i, $i, $c); } + return $R; } @@ -413,12 +417,13 @@ class Matrix */ public function transpose() { - $R = new Matrix($this->n, $this->m); + $R = new self($this->n, $this->m); for ($i = 0; $i < $this->m; ++$i) { for ($j = 0; $j < $this->n; ++$j) { $R->set($j, $i, $this->A[$i][$j]); } } + return $R; } // function transpose() @@ -435,6 +440,7 @@ class Matrix for ($i = 0; $i < $n; ++$i) { $s += $this->A[$i][$i]; } + return $s; } @@ -459,18 +465,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -482,6 +488,7 @@ class Matrix $M->set($i, $j, $M->get($i, $j) + $this->A[$i][$j]); } } + return $M; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -499,18 +506,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -536,6 +543,7 @@ class Matrix } } } + return $this; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -553,18 +561,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -576,6 +584,7 @@ class Matrix $M->set($i, $j, $M->get($i, $j) - $this->A[$i][$j]); } } + return $M; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -593,18 +602,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -630,6 +639,7 @@ class Matrix } } } + return $this; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -648,18 +658,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -671,6 +681,7 @@ class Matrix $M->set($i, $j, $M->get($i, $j) * $this->A[$i][$j]); } } + return $M; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -689,18 +700,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -726,6 +737,7 @@ class Matrix } } } + return $this; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -744,18 +756,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -786,13 +798,13 @@ class Matrix } } } + return $M; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); } } - /** * arrayRightDivideEquals * @@ -805,18 +817,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -828,13 +840,13 @@ class Matrix $this->A[$i][$j] = $this->A[$i][$j] / $M->get($i, $j); } } + return $M; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); } } - /** * arrayLeftDivide * @@ -847,18 +859,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -870,13 +882,13 @@ class Matrix $M->set($i, $j, $M->get($i, $j) / $this->A[$i][$j]); } } + return $M; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); } } - /** * arrayLeftDivideEquals * @@ -889,18 +901,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -912,13 +924,13 @@ class Matrix $this->A[$i][$j] = $M->get($i, $j) / $this->A[$i][$j]; } } + return $M; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); } } - /** * times * @@ -929,18 +941,18 @@ class Matrix public function times() { if (func_num_args() > 0) { - $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $args = func_get_args(); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $B = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } if ($this->n == $B->m) { - $C = new Matrix($this->m, $B->n); + $C = new self($this->m, $B->n); for ($j = 0; $j < $B->n; ++$j) { for ($k = 0; $k < $this->n; ++$k) { $Bcolj[$k] = $B->A[$k][$j]; @@ -954,55 +966,61 @@ class Matrix $C->A[$i][$j] = $s; } } + return $C; } else { throw new \PhpSpreadsheet\Calculation\Exception(JAMAError(MatrixDimensionMismatch)); } break; case 'array': - $B = new Matrix($args[0]); + $B = new self($args[0]); if ($this->n == $B->m) { - $C = new Matrix($this->m, $B->n); + $C = new self($this->m, $B->n); for ($i = 0; $i < $C->m; ++$i) { for ($j = 0; $j < $C->n; ++$j) { - $s = "0"; + $s = '0'; for ($k = 0; $k < $C->n; ++$k) { $s += $this->A[$i][$k] * $B->A[$k][$j]; } $C->A[$i][$j] = $s; } } + return $C; } else { throw new \PhpSpreadsheet\Calculation\Exception(JAMAError(MatrixDimensionMismatch)); } + return $M; break; case 'integer': - $C = new Matrix($this->A); + $C = new self($this->A); for ($i = 0; $i < $C->m; ++$i) { for ($j = 0; $j < $C->n; ++$j) { $C->A[$i][$j] *= $args[0]; } } + return $C; break; case 'double': - $C = new Matrix($this->m, $this->n); + $C = new self($this->m, $this->n); for ($i = 0; $i < $C->m; ++$i) { for ($j = 0; $j < $C->n; ++$j) { $C->A[$i][$j] = $args[0] * $this->A[$i][$j]; } } + return $C; break; case 'float': - $C = new Matrix($this->A); + $C = new self($this->A); for ($i = 0; $i < $C->m; ++$i) { for ($j = 0; $j < $C->n; ++$j) { $C->A[$i][$j] *= $args[0]; } } + return $C; break; default: @@ -1025,18 +1043,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -1062,6 +1080,7 @@ class Matrix } } } + return $this; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -1079,18 +1098,18 @@ class Matrix { if (func_num_args() > 0) { $args = func_get_args(); - $match = implode(",", array_map('gettype', $args)); + $match = implode(',', array_map('gettype', $args)); switch ($match) { case 'object': - if ($args[0] instanceof Matrix) { + if ($args[0] instanceof self) { $M = $args[0]; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::ARGUMENT_TYPE_EXCEPTION); } break; case 'array': - $M = new Matrix($args[0]); + $M = new self($args[0]); break; default: throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -1099,9 +1118,10 @@ class Matrix $this->checkMatrixDimensions($M); for ($i = 0; $i < $this->m; ++$i) { for ($j = 0; $j < $this->n; ++$j) { - $this->A[$i][$j] = trim($this->A[$i][$j], '"').trim($M->get($i, $j), '"'); + $this->A[$i][$j] = trim($this->A[$i][$j], '"') . trim($M->get($i, $j), '"'); } } + return $this; } else { throw new \PhpSpreadsheet\Calculation\Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); @@ -1118,9 +1138,11 @@ class Matrix { if ($this->m == $this->n) { $LU = new LUDecomposition($this); + return $LU->solve($B); } else { $QR = new QRDecomposition($this); + return $QR->solve($B); } } @@ -1144,6 +1166,7 @@ class Matrix public function det() { $L = new LUDecomposition($this); + return $L->det(); } } diff --git a/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php index 92461460..f22904b9 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php @@ -3,7 +3,6 @@ namespace PhpSpreadsheet\Shared\JAMA; /** - * * For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n * orthogonal matrix Q and an n-by-n upper triangular matrix R so that * A = Q*R. @@ -20,32 +19,31 @@ namespace PhpSpreadsheet\Shared\JAMA; */ class QRDecomposition { - const MATRIX_RANK_EXCEPTION = "Can only perform operation on full-rank matrix."; + const MATRIX_RANK_EXCEPTION = 'Can only perform operation on full-rank matrix.'; /** * Array for internal storage of decomposition. * @var array */ - private $QR = array(); + private $QR = []; /** * Row dimension. - * @var integer + * @var int */ private $m; /** - * Column dimension. - * @var integer - */ + * Column dimension. + * @var int + */ private $n; /** * Array for internal storage of diagonal of R. * @var array */ - private $Rdiag = array(); - + private $Rdiag = []; /** * QR Decomposition computed by Householder reflections. @@ -58,8 +56,8 @@ class QRDecomposition if ($A instanceof Matrix) { // Initialize. $this->QR = $A->getArrayCopy(); - $this->m = $A->getRowDimension(); - $this->n = $A->getColumnDimension(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); // Main loop. for ($k = 0; $k < $this->n; ++$k) { // Compute 2-norm of k-th column without under/overflow. @@ -77,12 +75,12 @@ class QRDecomposition } $this->QR[$k][$k] += 1.0; // Apply transformation to remaining columns. - for ($j = $k+1; $j < $this->n; ++$j) { + for ($j = $k + 1; $j < $this->n; ++$j) { $s = 0.0; for ($i = $k; $i < $this->m; ++$i) { $s += $this->QR[$i][$k] * $this->QR[$i][$j]; } - $s = -$s/$this->QR[$k][$k]; + $s = -$s / $this->QR[$k][$k]; for ($i = $k; $i < $this->m; ++$i) { $this->QR[$i][$j] += $s * $this->QR[$i][$k]; } @@ -95,11 +93,10 @@ class QRDecomposition } } // function __construct() - /** * Is the matrix full rank? * - * @return boolean true if R, and hence A, has full rank, else false. + * @return bool true if R, and hence A, has full rank, else false. */ public function isFullRank() { @@ -108,6 +105,7 @@ class QRDecomposition return false; } } + return true; } // function isFullRank() @@ -127,6 +125,7 @@ class QRDecomposition } } } + return new Matrix($H); } // function getH() @@ -148,6 +147,7 @@ class QRDecomposition } } } + return new Matrix($R); } // function getR() @@ -158,7 +158,7 @@ class QRDecomposition */ public function getQ() { - for ($k = $this->n-1; $k >= 0; --$k) { + for ($k = $this->n - 1; $k >= 0; --$k) { for ($i = 0; $i < $this->m; ++$i) { $Q[$i][$k] = 0.0; } @@ -169,7 +169,7 @@ class QRDecomposition for ($i = $k; $i < $this->m; ++$i) { $s += $this->QR[$i][$k] * $Q[$i][$j]; } - $s = -$s/$this->QR[$k][$k]; + $s = -$s / $this->QR[$k][$k]; for ($i = $k; $i < $this->m; ++$i) { $Q[$i][$j] += $s * $this->QR[$i][$k]; } @@ -200,7 +200,7 @@ class QRDecomposition if ($this->isFullRank()) { // Copy right hand side $nx = $B->getColumnDimension(); - $X = $B->getArrayCopy(); + $X = $B->getArrayCopy(); // Compute Y = transpose(Q)*B for ($k = 0; $k < $this->n; ++$k) { for ($j = 0; $j < $nx; ++$j) { @@ -208,25 +208,26 @@ class QRDecomposition for ($i = $k; $i < $this->m; ++$i) { $s += $this->QR[$i][$k] * $X[$i][$j]; } - $s = -$s/$this->QR[$k][$k]; + $s = -$s / $this->QR[$k][$k]; for ($i = $k; $i < $this->m; ++$i) { $X[$i][$j] += $s * $this->QR[$i][$k]; } } } // Solve R*X = Y; - for ($k = $this->n-1; $k >= 0; --$k) { + for ($k = $this->n - 1; $k >= 0; --$k) { for ($j = 0; $j < $nx; ++$j) { $X[$k][$j] /= $this->Rdiag[$k]; } for ($i = 0; $i < $k; ++$i) { for ($j = 0; $j < $nx; ++$j) { - $X[$i][$j] -= $X[$k][$j]* $this->QR[$i][$k]; + $X[$i][$j] -= $X[$k][$j] * $this->QR[$i][$k]; } } } $X = new Matrix($X); - return ($X->getMatrix(0, $this->n-1, 0, $nx)); + + return $X->getMatrix(0, $this->n - 1, 0, $nx); } else { throw new \PhpSpreadsheet\Calculation\Exception(self::MATRIX_RANK_EXCEPTION); } diff --git a/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php index 7bd6ddbc..55fb249e 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php @@ -3,7 +3,6 @@ namespace PhpSpreadsheet\Shared\JAMA; /** - * * For an m-by-n matrix A with m >= n, the singular value decomposition is * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and * an n-by-n orthogonal matrix V so that A = U*S*V'. @@ -25,19 +24,19 @@ class SingularValueDecomposition * Internal storage of U. * @var array */ - private $U = array(); + private $U = []; /** * Internal storage of V. * @var array */ - private $V = array(); + private $V = []; /** * Internal storage of singular values. * @var array */ - private $s = array(); + private $s = []; /** * Row dimension. @@ -65,11 +64,11 @@ class SingularValueDecomposition $A = $Arg->getArrayCopy(); $this->m = $Arg->getRowDimension(); $this->n = $Arg->getColumnDimension(); - $nu = min($this->m, $this->n); - $e = array(); - $work = array(); - $wantu = true; - $wantv = true; + $nu = min($this->m, $this->n); + $e = []; + $work = []; + $wantu = true; + $wantv = true; $nct = min($this->m - 1, $this->n); $nrt = max(0, min($this->n - 2, $this->m)); @@ -130,27 +129,27 @@ class SingularValueDecomposition $e[$k] = hypo($e[$k], $e[$i]); } if ($e[$k] != 0.0) { - if ($e[$k+1] < 0.0) { + if ($e[$k + 1] < 0.0) { $e[$k] = -$e[$k]; } for ($i = $k + 1; $i < $this->n; ++$i) { $e[$i] /= $e[$k]; } - $e[$k+1] += 1.0; + $e[$k + 1] += 1.0; } $e[$k] = -$e[$k]; - if (($k+1 < $this->m) and ($e[$k] != 0.0)) { + if (($k + 1 < $this->m) and ($e[$k] != 0.0)) { // Apply the transformation. - for ($i = $k+1; $i < $this->m; ++$i) { + for ($i = $k + 1; $i < $this->m; ++$i) { $work[$i] = 0.0; } - for ($j = $k+1; $j < $this->n; ++$j) { - for ($i = $k+1; $i < $this->m; ++$i) { + for ($j = $k + 1; $j < $this->n; ++$j) { + for ($i = $k + 1; $i < $this->m; ++$i) { $work[$i] += $e[$j] * $A[$i][$j]; } } for ($j = $k + 1; $j < $this->n; ++$j) { - $t = -$e[$j] / $e[$k+1]; + $t = -$e[$j] / $e[$k + 1]; for ($i = $k + 1; $i < $this->m; ++$i) { $A[$i][$j] += $t * $work[$i]; } @@ -172,12 +171,12 @@ class SingularValueDecomposition $this->s[$nct] = $A[$nct][$nct]; } if ($this->m < $p) { - $this->s[$p-1] = 0.0; + $this->s[$p - 1] = 0.0; } if ($nrt + 1 < $p) { - $e[$nrt] = $A[$nrt][$p-1]; + $e[$nrt] = $A[$nrt][$p - 1]; } - $e[$p-1] = 0.0; + $e[$p - 1] = 0.0; // If required, generate U. if ($wantu) { for ($j = $nct; $j < $nu; ++$j) { @@ -221,9 +220,9 @@ class SingularValueDecomposition for ($j = $k + 1; $j < $nu; ++$j) { $t = 0; for ($i = $k + 1; $i < $this->n; ++$i) { - $t += $this->V[$i][$k]* $this->V[$i][$j]; + $t += $this->V[$i][$k] * $this->V[$i][$j]; } - $t = -$t / $this->V[$k+1][$k]; + $t = -$t / $this->V[$k + 1][$k]; for ($i = $k + 1; $i < $this->n; ++$i) { $this->V[$i][$j] += $t * $this->V[$i][$k]; } @@ -237,9 +236,9 @@ class SingularValueDecomposition } // Main iteration loop for the singular values. - $pp = $p - 1; + $pp = $p - 1; $iter = 0; - $eps = pow(2.0, -52.0); + $eps = pow(2.0, -52.0); while ($p > 0) { // Here is where a test for too many iterations would go. @@ -255,7 +254,7 @@ class SingularValueDecomposition if ($k == -1) { break; } - if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) { + if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k + 1]))) { $e[$k] = 0.0; break; } @@ -267,7 +266,7 @@ class SingularValueDecomposition if ($ks == $k) { break; } - $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.); + $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks - 1]) : 0.); if (abs($this->s[$ks]) <= $eps * $t) { $this->s[$ks] = 0.0; break; @@ -275,7 +274,7 @@ class SingularValueDecomposition } if ($ks == $k) { $kase = 3; - } elseif ($ks == $p-1) { + } elseif ($ks == $p - 1) { $kase = 1; } else { $kase = 2; @@ -288,21 +287,21 @@ class SingularValueDecomposition switch ($kase) { // Deflate negligible s(p). case 1: - $f = $e[$p-2]; - $e[$p-2] = 0.0; + $f = $e[$p - 2]; + $e[$p - 2] = 0.0; for ($j = $p - 2; $j >= $k; --$j) { - $t = hypo($this->s[$j], $f); + $t = hypo($this->s[$j], $f); $cs = $this->s[$j] / $t; $sn = $f / $t; $this->s[$j] = $t; if ($j != $k) { - $f = -$sn * $e[$j-1]; - $e[$j-1] = $cs * $e[$j-1]; + $f = -$sn * $e[$j - 1]; + $e[$j - 1] = $cs * $e[$j - 1]; } if ($wantv) { for ($i = 0; $i < $this->n; ++$i) { - $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1]; - $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1]; + $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p - 1]; + $this->V[$i][$p - 1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p - 1]; $this->V[$i][$j] = $t; } } @@ -310,8 +309,8 @@ class SingularValueDecomposition break; // Split at negligible s(k). case 2: - $f = $e[$k-1]; - $e[$k-1] = 0.0; + $f = $e[$k - 1]; + $e[$k - 1] = 0.0; for ($j = $k; $j < $p; ++$j) { $t = hypo($this->s[$j], $f); $cs = $this->s[$j] / $t; @@ -321,8 +320,8 @@ class SingularValueDecomposition $e[$j] = $cs * $e[$j]; if ($wantu) { for ($i = 0; $i < $this->m; ++$i) { - $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1]; - $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1]; + $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k - 1]; + $this->U[$i][$k - 1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k - 1]; $this->U[$i][$j] = $t; } } @@ -331,14 +330,14 @@ class SingularValueDecomposition // Perform one qr step. case 3: // Calculate the shift. - $scale = max(max(max(max(abs($this->s[$p-1]), abs($this->s[$p-2])), abs($e[$p-2])), abs($this->s[$k])), abs($e[$k])); - $sp = $this->s[$p-1] / $scale; - $spm1 = $this->s[$p-2] / $scale; - $epm1 = $e[$p-2] / $scale; - $sk = $this->s[$k] / $scale; - $ek = $e[$k] / $scale; - $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0; - $c = ($sp * $epm1) * ($sp * $epm1); + $scale = max(max(max(max(abs($this->s[$p - 1]), abs($this->s[$p - 2])), abs($e[$p - 2])), abs($this->s[$k])), abs($e[$k])); + $sp = $this->s[$p - 1] / $scale; + $spm1 = $this->s[$p - 2] / $scale; + $epm1 = $e[$p - 2] / $scale; + $sk = $this->s[$k] / $scale; + $ek = $e[$k] / $scale; + $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0; + $c = ($sp * $epm1) * ($sp * $epm1); $shift = 0.0; if (($b != 0.0) || ($c != 0.0)) { $shift = sqrt($b * $b + $c); @@ -350,41 +349,41 @@ class SingularValueDecomposition $f = ($sk + $sp) * ($sk - $sp) + $shift; $g = $sk * $ek; // Chase zeros. - for ($j = $k; $j < $p-1; ++$j) { - $t = hypo($f, $g); - $cs = $f/$t; - $sn = $g/$t; + for ($j = $k; $j < $p - 1; ++$j) { + $t = hypo($f, $g); + $cs = $f / $t; + $sn = $g / $t; if ($j != $k) { - $e[$j-1] = $t; + $e[$j - 1] = $t; } $f = $cs * $this->s[$j] + $sn * $e[$j]; $e[$j] = $cs * $e[$j] - $sn * $this->s[$j]; - $g = $sn * $this->s[$j+1]; - $this->s[$j+1] = $cs * $this->s[$j+1]; + $g = $sn * $this->s[$j + 1]; + $this->s[$j + 1] = $cs * $this->s[$j + 1]; if ($wantv) { for ($i = 0; $i < $this->n; ++$i) { - $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1]; - $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1]; + $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j + 1]; + $this->V[$i][$j + 1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j + 1]; $this->V[$i][$j] = $t; } } $t = hypo($f, $g); - $cs = $f/$t; - $sn = $g/$t; + $cs = $f / $t; + $sn = $g / $t; $this->s[$j] = $t; - $f = $cs * $e[$j] + $sn * $this->s[$j+1]; - $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1]; - $g = $sn * $e[$j+1]; - $e[$j+1] = $cs * $e[$j+1]; + $f = $cs * $e[$j] + $sn * $this->s[$j + 1]; + $this->s[$j + 1] = -$sn * $e[$j] + $cs * $this->s[$j + 1]; + $g = $sn * $e[$j + 1]; + $e[$j + 1] = $cs * $e[$j + 1]; if ($wantu && ($j < $this->m - 1)) { for ($i = 0; $i < $this->m; ++$i) { - $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1]; - $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1]; + $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j + 1]; + $this->U[$i][$j + 1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j + 1]; $this->U[$i][$j] = $t; } } } - $e[$p-2] = $f; + $e[$p - 2] = $f; $iter = $iter + 1; break; // Convergence. @@ -400,23 +399,23 @@ class SingularValueDecomposition } // Order the singular values. while ($k < $pp) { - if ($this->s[$k] >= $this->s[$k+1]) { + if ($this->s[$k] >= $this->s[$k + 1]) { break; } $t = $this->s[$k]; - $this->s[$k] = $this->s[$k+1]; - $this->s[$k+1] = $t; + $this->s[$k] = $this->s[$k + 1]; + $this->s[$k + 1] = $t; if ($wantv and ($k < $this->n - 1)) { for ($i = 0; $i < $this->n; ++$i) { - $t = $this->V[$i][$k+1]; - $this->V[$i][$k+1] = $this->V[$i][$k]; + $t = $this->V[$i][$k + 1]; + $this->V[$i][$k + 1] = $this->V[$i][$k]; $this->V[$i][$k] = $t; } } - if ($wantu and ($k < $this->m-1)) { + if ($wantu and ($k < $this->m - 1)) { for ($i = 0; $i < $this->m; ++$i) { - $t = $this->U[$i][$k+1]; - $this->U[$i][$k+1] = $this->U[$i][$k]; + $t = $this->U[$i][$k + 1]; + $this->U[$i][$k + 1] = $this->U[$i][$k]; $this->U[$i][$k] = $t; } } @@ -429,11 +428,9 @@ class SingularValueDecomposition } // end while } // end constructor - /** * Return the left singular vectors * - * @access public * @return U */ public function getU() @@ -441,11 +438,9 @@ class SingularValueDecomposition return new Matrix($this->U, $this->m, min($this->m + 1, $this->n)); } - /** * Return the right singular vectors * - * @access public * @return V */ public function getV() @@ -453,11 +448,9 @@ class SingularValueDecomposition return new Matrix($this->V); } - /** * Return the one-dimensional array of singular values * - * @access public * @return diagonal of S. */ public function getSingularValues() @@ -465,11 +458,9 @@ class SingularValueDecomposition return $this->s; } - /** * Return the diagonal matrix of singular values * - * @access public * @return S */ public function getS() @@ -480,14 +471,13 @@ class SingularValueDecomposition } $S[$i][$i] = $this->s[$i]; } + return new Matrix($S); } - /** * Two norm * - * @access public * @return max(S) */ public function norm2() @@ -495,11 +485,9 @@ class SingularValueDecomposition return $this->s[0]; } - /** * Two norm condition number * - * @access public * @return max(S)/min(S) */ public function cond() @@ -507,11 +495,9 @@ class SingularValueDecomposition return $this->s[0] / $this->s[min($this->m, $this->n) - 1]; } - /** * Effective numerical matrix rank * - * @access public * @return Number of nonnegligible singular values. */ public function rank() @@ -524,6 +510,7 @@ class SingularValueDecomposition ++$r; } } + return $r; } } diff --git a/src/PhpSpreadsheet/Shared/JAMA/utils/Error.php b/src/PhpSpreadsheet/Shared/JAMA/utils/Error.php index 48bc8936..37440487 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/utils/Error.php +++ b/src/PhpSpreadsheet/Shared/JAMA/utils/Error.php @@ -1,6 +1,5 @@ -* @author Christian Schmidt -* @category PhpSpreadsheet -*/ + * OLE package base class. + * + * @author Xavier Noguer + * @author Christian Schmidt + * @category PhpSpreadsheet + */ class OLE { - const OLE_PPS_TYPE_ROOT = 5; - const OLE_PPS_TYPE_DIR = 1; - const OLE_PPS_TYPE_FILE = 2; + const OLE_PPS_TYPE_ROOT = 5; + const OLE_PPS_TYPE_DIR = 1; + const OLE_PPS_TYPE_FILE = 2; const OLE_DATA_SIZE_SMALL = 0x1000; - const OLE_LONG_INT_SIZE = 4; - const OLE_PPS_SIZE = 0x80; + const OLE_LONG_INT_SIZE = 4; + const OLE_PPS_SIZE = 0x80; /** * The file handle for reading an OLE container * @var resource - */ + */ public $_file_handle; /** - * Array of PPS's found on the OLE container - * @var array - */ - public $_list = array(); + * Array of PPS's found on the OLE container + * @var array + */ + public $_list = []; /** * Root directory of OLE container * @var OLE_PPS_Root - */ + */ public $root; /** * Big Block Allocation Table * @var array (blockId => nextBlockId) - */ + */ public $bbat; /** * Short Block Allocation Table * @var array (blockId => nextBlockId) - */ + */ public $sbat; /** * Size of big blocks. This is usually 512. * @var int number of octets per block. - */ + */ public $bigBlockSize; /** * Size of small blocks. This is usually 64. * @var int number of octets per block - */ + */ public $smallBlockSize; /** @@ -93,12 +92,12 @@ class OLE * * @acces public * @param string $file - * @return mixed true on success, PEAR_Error on failure * @throws \PhpSpreadsheet\Reader\Exception - */ + * @return mixed true on success, PEAR_Error on failure + */ public function read($file) { - $fh = fopen($file, "r"); + $fh = fopen($file, 'r'); if (!$fh) { throw new \PhpSpreadsheet\Reader\Exception("Can't open file $file"); } @@ -111,11 +110,11 @@ class OLE fseek($fh, 28); if (fread($fh, 2) != "\xFE\xFF") { // This shouldn't be a problem in practice - throw new \PhpSpreadsheet\Reader\Exception("Only Little-Endian encoding is supported."); + throw new \PhpSpreadsheet\Reader\Exception('Only Little-Endian encoding is supported.'); } // Size of blocks and short blocks in bytes $this->bigBlockSize = pow(2, self::_readInt2($fh)); - $this->smallBlockSize = pow(2, self::_readInt2($fh)); + $this->smallBlockSize = pow(2, self::_readInt2($fh)); // Skip UID, revision number and version number fseek($fh, 44); @@ -137,11 +136,11 @@ class OLE $mbatFirstBlockId = self::_readInt4($fh); // Number of blocks in Master Block Allocation Table $mbbatBlockCount = self::_readInt4($fh); - $this->bbat = array(); + $this->bbat = []; // Remaining 4 * 109 bytes of current block is beginning of Master // Block Allocation Table - $mbatBlocks = array(); + $mbatBlocks = []; for ($i = 0; $i < 109; ++$i) { $mbatBlocks[] = self::_readInt4($fh); } @@ -168,7 +167,7 @@ class OLE } // Read short block allocation table (SBAT) - $this->sbat = array(); + $this->sbat = []; $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4; $sbatFh = $this->getStream($sbatFirstBlockId); for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) { @@ -184,7 +183,6 @@ class OLE /** * @param int block id * @param int byte offset from beginning of file - * @access public */ public function _getBlockOffset($blockId) { @@ -192,11 +190,11 @@ class OLE } /** - * Returns a stream for use with fread() etc. External callers should - * use \PhpSpreadsheet\Shared\OLE\PPS\File::getStream(). - * @param int|PPS block id or PPS - * @return resource read-only stream - */ + * Returns a stream for use with fread() etc. External callers should + * use \PhpSpreadsheet\Shared\OLE\PPS\File::getStream(). + * @param int|PPS block id or PPS + * @return resource read-only stream + */ public function getStream($blockIdOrPps) { static $isRegistered = false; @@ -218,6 +216,7 @@ class OLE } else { $path .= '&blockId=' . $blockIdOrPps; } + return fopen($path, 'r'); } @@ -225,11 +224,11 @@ class OLE * Reads a signed char. * @param resource file handle * @return int - * @access public */ private static function _readInt1($fh) { - list(, $tmp) = unpack("c", fread($fh, 1)); + list(, $tmp) = unpack('c', fread($fh, 1)); + return $tmp; } @@ -237,11 +236,11 @@ class OLE * Reads an unsigned short (2 octets). * @param resource file handle * @return int - * @access public */ private static function _readInt2($fh) { - list(, $tmp) = unpack("v", fread($fh, 2)); + list(, $tmp) = unpack('v', fread($fh, 2)); + return $tmp; } @@ -249,22 +248,21 @@ class OLE * Reads an unsigned long (4 octets). * @param resource file handle * @return int - * @access public */ private static function _readInt4($fh) { - list(, $tmp) = unpack("V", fread($fh, 4)); + list(, $tmp) = unpack('V', fread($fh, 4)); + return $tmp; } /** - * Gets information about all PPS's on the OLE container from the PPS WK's - * creates an OLE_PPS object for each one. - * - * @access public - * @param integer the block id of the first block - * @return mixed true on success, PEAR_Error on failure - */ + * Gets information about all PPS's on the OLE container from the PPS WK's + * creates an OLE_PPS object for each one. + * + * @param int the block id of the first block + * @return mixed true on success, PEAR_Error on failure + */ public function _readPpsWks($blockId) { $fh = $this->getStream($blockId); @@ -274,15 +272,15 @@ class OLE $nameLength = self::_readInt2($fh); $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2); // Simple conversion from UTF-16LE to ISO-8859-1 - $name = str_replace("\x00", "", $nameUtf16); + $name = str_replace("\x00", '', $nameUtf16); $type = self::_readInt1($fh); switch ($type) { case self::OLE_PPS_TYPE_ROOT: - $pps = new OLE\PPS_Root(null, null, array()); + $pps = new OLE\PPS_Root(null, null, []); $this->root = $pps; break; case self::OLE_PPS_TYPE_DIR: - $pps = new OLE\PPS(null, null, null, null, null, null, null, null, null, array()); + $pps = new OLE\PPS(null, null, null, null, null, null, null, null, null, []); break; case self::OLE_PPS_TYPE_FILE: $pps = new OLE\PPS\File($name); @@ -291,11 +289,11 @@ class OLE continue; } fseek($fh, 1, SEEK_CUR); - $pps->Type = $type; - $pps->Name = $name; + $pps->Type = $type; + $pps->Name = $name; $pps->PrevPps = self::_readInt4($fh); $pps->NextPps = self::_readInt4($fh); - $pps->DirPps = self::_readInt4($fh); + $pps->DirPps = self::_readInt4($fh); fseek($fh, 20, SEEK_CUR); $pps->Time1st = self::OLE2LocalDate(fread($fh, 8)); $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8)); @@ -314,8 +312,8 @@ class OLE // Initialize $pps->children on directories foreach ($this->_list as $pps) { if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) { - $nos = array($pps->DirPps); - $pps->children = array(); + $nos = [$pps->DirPps]; + $pps->children = []; while ($nos) { $no = array_pop($nos); if ($no != -1) { @@ -332,13 +330,12 @@ class OLE } /** - * It checks whether the PPS tree is complete (all PPS's read) - * starting with the given PPS (not necessarily root) - * - * @access public - * @param integer $index The index of the PPS from which we are checking - * @return boolean Whether the PPS tree for the given PPS is complete - */ + * It checks whether the PPS tree is complete (all PPS's read) + * starting with the given PPS (not necessarily root) + * + * @param int $index The index of the PPS from which we are checking + * @return bool Whether the PPS tree for the given PPS is complete + */ public function _ppsTreeComplete($index) { return isset($this->_list[$index]) && @@ -352,60 +349,58 @@ class OLE } /** - * Checks whether a PPS is a File PPS or not. - * If there is no PPS for the index given, it will return false. - * - * @access public - * @param integer $index The index for the PPS - * @return bool true if it's a File PPS, false otherwise - */ + * Checks whether a PPS is a File PPS or not. + * If there is no PPS for the index given, it will return false. + * + * @param int $index The index for the PPS + * @return bool true if it's a File PPS, false otherwise + */ public function isFile($index) { if (isset($this->_list[$index])) { - return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE); + return $this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE; } + return false; } /** - * Checks whether a PPS is a Root PPS or not. - * If there is no PPS for the index given, it will return false. - * - * @access public - * @param integer $index The index for the PPS. - * @return bool true if it's a Root PPS, false otherwise - */ + * Checks whether a PPS is a Root PPS or not. + * If there is no PPS for the index given, it will return false. + * + * @param int $index The index for the PPS. + * @return bool true if it's a Root PPS, false otherwise + */ public function isRoot($index) { if (isset($this->_list[$index])) { - return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT); + return $this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT; } + return false; } /** - * Gives the total number of PPS's found in the OLE container. - * - * @access public - * @return integer The total number of PPS's found in the OLE container - */ + * Gives the total number of PPS's found in the OLE container. + * + * @return int The total number of PPS's found in the OLE container + */ public function ppsTotal() { return count($this->_list); } /** - * Gets data from a PPS - * If there is no PPS for the index given, it will return an empty string. - * - * @access public - * @param integer $index The index for the PPS - * @param integer $position The position from which to start reading - * (relative to the PPS) - * @param integer $length The amount of bytes to read (at most) - * @return string The binary string containing the data requested - * @see OLE_PPS_File::getStream() - */ + * Gets data from a PPS + * If there is no PPS for the index given, it will return an empty string. + * + * @param int $index The index for the PPS + * @param int $position The position from which to start reading + * (relative to the PPS) + * @param int $length The amount of bytes to read (at most) + * @return string The binary string containing the data requested + * @see OLE_PPS_File::getStream() + */ public function getData($index, $position, $length) { // if position is not valid return empty string @@ -415,51 +410,52 @@ class OLE $fh = $this->getStream($this->_list[$index]); $data = stream_get_contents($fh, $length, $position); fclose($fh); + return $data; } /** - * Gets the data length from a PPS - * If there is no PPS for the index given, it will return 0. - * - * @access public - * @param integer $index The index for the PPS - * @return integer The amount of bytes in data the PPS has - */ + * Gets the data length from a PPS + * If there is no PPS for the index given, it will return 0. + * + * @param int $index The index for the PPS + * @return int The amount of bytes in data the PPS has + */ public function getDataLength($index) { if (isset($this->_list[$index])) { return $this->_list[$index]->Size; } + return 0; } /** - * Utility function to transform ASCII text to Unicode - * - * @access public - * @static - * @param string $ascii The ASCII string to transform - * @return string The string in Unicode - */ + * Utility function to transform ASCII text to Unicode + * + * @static + * @param string $ascii The ASCII string to transform + * @return string The string in Unicode + */ public static function ascToUcs($ascii) { $rawname = ''; for ($i = 0; $i < strlen($ascii); ++$i) { - $rawname .= $ascii{$i} . "\x00"; + $rawname .= $ascii{$i} + . "\x00"; } + return $rawname; } /** - * Utility function - * Returns a string for the OLE container with the date given - * - * @access public - * @static - * @param integer $date A timestamp - * @return string The string for the OLE container - */ + * Utility function + * Returns a string for the OLE container with the date given + * + * @static + * @param int $date A timestamp + * @return string The string for the OLE container + */ public static function localDateToOLE($date = null) { if (!isset($date)) { @@ -472,7 +468,7 @@ class OLE // days from 1-1-1601 until the beggining of UNIX era $days = 134774; // calculate seconds - $big_date = $days*24*3600 + gmmktime(date("H", $date), date("i", $date), date("s", $date), date("m", $date), date("d", $date), date("Y", $date)); + $big_date = $days * 24 * 3600 + gmmktime(date('H', $date), date('i', $date), date('s', $date), date('m', $date), date('d', $date), date('Y', $date)); // multiply just to make MS happy $big_date *= 10000000; @@ -493,21 +489,21 @@ class OLE $res .= pack('c', $hex); $high_part /= 0x100; } + return $res; } /** - * Returns a timestamp from an OLE container's date - * - * @access public - * @static - * @param integer $string A binary string with the encoded date - * @return string The timestamp corresponding to the string - */ + * Returns a timestamp from an OLE container's date + * + * @static + * @param int $string A binary string with the encoded date + * @return string The timestamp corresponding to the string + */ public static function OLE2LocalDate($string) { if (strlen($string) != 8) { - return new PEAR_Error("Expecting 8 byte string"); + return new PEAR_Error('Expecting 8 byte string'); } // factor used for separating numbers into 4 bytes parts @@ -524,6 +520,7 @@ class OLE // translate to seconds from beggining of UNIX era $big_date -= $days * 24 * 3600; + return floor($big_date); } } diff --git a/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php b/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php index 89a64f08..444203b7 100644 --- a/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php +++ b/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php @@ -67,6 +67,7 @@ class ChainedBlockStream if ($options & STREAM_REPORT_ERRORS) { trigger_error('Only reading is supported', E_USER_WARNING); } + return false; } @@ -76,6 +77,7 @@ class ChainedBlockStream if ($options & STREAM_REPORT_ERRORS) { trigger_error('OLE stream not found', E_USER_WARNING); } + return false; } $this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']]; @@ -113,7 +115,6 @@ class ChainedBlockStream /** * Implements support for fclose(). - * */ public function stream_close() // @codingStandardsIgnoreLine { @@ -134,6 +135,7 @@ class ChainedBlockStream } $s = substr($this->data, $this->pos, $count); $this->pos += $count; + return $s; } @@ -176,6 +178,7 @@ class ChainedBlockStream } else { return false; } + return true; } @@ -186,9 +189,9 @@ class ChainedBlockStream */ public function stream_stat() // @codingStandardsIgnoreLine { - return array( + return [ 'size' => strlen($this->data), - ); + ]; } // Methods used by stream_wrapper_register() that are not implemented: diff --git a/src/PhpSpreadsheet/Shared/OLE/PPS.php b/src/PhpSpreadsheet/Shared/OLE/PPS.php index 7651cd62..4fe28c9b 100644 --- a/src/PhpSpreadsheet/Shared/OLE/PPS.php +++ b/src/PhpSpreadsheet/Shared/OLE/PPS.php @@ -22,120 +22,118 @@ namespace PhpSpreadsheet\Shared\OLE; // // $Id: PPS.php,v 1.7 2007/02/13 21:00:42 schmidt Exp $ - /** -* Class for creating PPS's for OLE containers -* -* @author Xavier Noguer -* @category PhpSpreadsheet -*/ + * Class for creating PPS's for OLE containers + * + * @author Xavier Noguer + * @category PhpSpreadsheet + */ class PPS { /** - * The PPS index - * @var integer - */ + * The PPS index + * @var int + */ public $No; /** - * The PPS name (in Unicode) - * @var string - */ + * The PPS name (in Unicode) + * @var string + */ public $Name; /** - * The PPS type. Dir, Root or File - * @var integer - */ + * The PPS type. Dir, Root or File + * @var int + */ public $Type; /** - * The index of the previous PPS - * @var integer - */ + * The index of the previous PPS + * @var int + */ public $PrevPps; /** - * The index of the next PPS - * @var integer - */ + * The index of the next PPS + * @var int + */ public $NextPps; /** - * The index of it's first child if this is a Dir or Root PPS - * @var integer - */ + * The index of it's first child if this is a Dir or Root PPS + * @var int + */ public $DirPps; /** - * A timestamp - * @var integer - */ + * A timestamp + * @var int + */ public $Time1st; /** - * A timestamp - * @var integer - */ + * A timestamp + * @var int + */ public $Time2nd; /** - * Starting block (small or big) for this PPS's data inside the container - * @var integer - */ + * Starting block (small or big) for this PPS's data inside the container + * @var int + */ public $startBlock; /** - * The size of the PPS's data (in bytes) - * @var integer - */ + * The size of the PPS's data (in bytes) + * @var int + */ public $Size; /** - * The PPS's data (only used if it's not using a temporary file) - * @var string - */ + * The PPS's data (only used if it's not using a temporary file) + * @var string + */ public $_data; /** - * Array of child PPS's (only used by Root and Dir PPS's) - * @var array - */ - public $children = array(); + * Array of child PPS's (only used by Root and Dir PPS's) + * @var array + */ + public $children = []; /** - * Pointer to OLE container - * @var OLE - */ + * Pointer to OLE container + * @var OLE + */ public $ole; /** - * The constructor - * - * @access public - * @param integer $No The PPS index - * @param string $name The PPS name - * @param integer $type The PPS type. Dir, Root or File - * @param integer $prev The index of the previous PPS - * @param integer $next The index of the next PPS - * @param integer $dir The index of it's first child if this is a Dir or Root PPS - * @param integer $time_1st A timestamp - * @param integer $time_2nd A timestamp - * @param string $data The (usually binary) source data of the PPS - * @param array $children Array containing children PPS for this PPS - */ + * The constructor + * + * @param int $No The PPS index + * @param string $name The PPS name + * @param int $type The PPS type. Dir, Root or File + * @param int $prev The index of the previous PPS + * @param int $next The index of the next PPS + * @param int $dir The index of it's first child if this is a Dir or Root PPS + * @param int $time_1st A timestamp + * @param int $time_2nd A timestamp + * @param string $data The (usually binary) source data of the PPS + * @param array $children Array containing children PPS for this PPS + */ public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children) { - $this->No = $No; - $this->Name = $name; - $this->Type = $type; + $this->No = $No; + $this->Name = $name; + $this->Type = $type; $this->PrevPps = $prev; $this->NextPps = $next; - $this->DirPps = $dir; + $this->DirPps = $dir; $this->Time1st = $time_1st; $this->Time2nd = $time_2nd; - $this->_data = $data; - $this->children = $children; + $this->_data = $data; + $this->children = $children; if ($data != '') { $this->Size = strlen($data); } else { @@ -144,11 +142,10 @@ class PPS } /** - * Returns the amount of data saved for this PPS - * - * @access public - * @return integer The amount of data (in bytes) - */ + * Returns the amount of data saved for this PPS + * + * @return int The amount of data (in bytes) + */ public function getDataLen() { if (!isset($this->_data)) { @@ -164,21 +161,20 @@ class PPS } /** - * Returns a string with the PPS's WK (What is a WK?) - * - * @access public - * @return string The binary string - */ + * Returns a string with the PPS's WK (What is a WK?) + * + * @return string The binary string + */ public function _getPpsWk() { $ret = str_pad($this->Name, 64, "\x00"); - $ret .= pack("v", strlen($this->Name) + 2) // 66 - . pack("c", $this->Type) // 67 - . pack("c", 0x00) //UK // 68 - . pack("V", $this->PrevPps) //Prev // 72 - . pack("V", $this->NextPps) //Next // 76 - . pack("V", $this->DirPps) //Dir // 80 + $ret .= pack('v', strlen($this->Name) + 2) // 66 + . pack('c', $this->Type) // 67 + . pack('c', 0x00) //UK // 68 + . pack('V', $this->PrevPps) //Prev // 72 + . pack('V', $this->NextPps) //Next // 76 + . pack('V', $this->DirPps) //Dir // 80 . "\x00\x09\x02\x00" // 84 . "\x00\x00\x00\x00" // 88 . "\xc0\x00\x00\x00" // 92 @@ -186,21 +182,20 @@ class PPS . "\x00\x00\x00\x00" // 100 . \PhpSpreadsheet\Shared\OLE::localDateToOLE($this->Time1st) // 108 . \PhpSpreadsheet\Shared\OLE::localDateToOLE($this->Time2nd) // 116 - . pack("V", isset($this->startBlock) ? $this->startBlock : 0) // 120 - . pack("V", $this->Size) // 124 - . pack("V", 0); // 128 + . pack('V', isset($this->startBlock) ? $this->startBlock : 0) // 120 + . pack('V', $this->Size) // 124 + . pack('V', 0); // 128 return $ret; } /** - * Updates index and pointers to previous, next and children PPS's for this - * PPS. I don't think it'll work with Dir PPS's. - * - * @access public - * @param array &$raList Reference to the array of PPS's for the whole OLE - * container - * @return integer The index for this PPS - */ + * Updates index and pointers to previous, next and children PPS's for this + * PPS. I don't think it'll work with Dir PPS's. + * + * @param array &$raList Reference to the array of PPS's for the whole OLE + * container + * @return int The index for this PPS + */ public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0) { if (!is_array($to_save) || (empty($to_save))) { @@ -208,23 +203,24 @@ class PPS } elseif (count($to_save) == 1) { $cnt = count($raList); // If the first entry, it's the root... Don't clone it! - $raList[$cnt] = ( $depth == 0 ) ? $to_save[0] : clone $to_save[0]; + $raList[$cnt] = ($depth == 0) ? $to_save[0] : clone $to_save[0]; $raList[$cnt]->No = $cnt; $raList[$cnt]->PrevPps = 0xFFFFFFFF; $raList[$cnt]->NextPps = 0xFFFFFFFF; - $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } else { - $iPos = floor(count($to_save) / 2); + $iPos = floor(count($to_save) / 2); $aPrev = array_slice($to_save, 0, $iPos); $aNext = array_slice($to_save, $iPos + 1); - $cnt = count($raList); + $cnt = count($raList); // If the first entry, it's the root... Don't clone it! - $raList[$cnt] = ( $depth == 0 ) ? $to_save[$iPos] : clone $to_save[$iPos]; + $raList[$cnt] = ($depth == 0) ? $to_save[$iPos] : clone $to_save[$iPos]; $raList[$cnt]->No = $cnt; $raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++); $raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++); - $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } + return $cnt; } } diff --git a/src/PhpSpreadsheet/Shared/OLE/PPS/File.php b/src/PhpSpreadsheet/Shared/OLE/PPS/File.php index 21fd7b5d..62946c5c 100644 --- a/src/PhpSpreadsheet/Shared/OLE/PPS/File.php +++ b/src/PhpSpreadsheet/Shared/OLE/PPS/File.php @@ -22,44 +22,40 @@ namespace PhpSpreadsheet\Shared\OLE\PPS; // // $Id: File.php,v 1.11 2007/02/13 21:00:42 schmidt Exp $ - /** -* Class for creating File PPS's for OLE containers -* -* @author Xavier Noguer -* @category PhpSpreadsheet -*/ + * Class for creating File PPS's for OLE containers + * + * @author Xavier Noguer + * @category PhpSpreadsheet + */ class File extends \PhpSpreadsheet\Shared\OLE\PPS { /** - * The constructor - * - * @access public - * @param string $name The name of the file (in Unicode) - * @see OLE::ascToUcs() - */ + * The constructor + * + * @param string $name The name of the file (in Unicode) + * @see OLE::ascToUcs() + */ public function __construct($name) { - parent::__construct(null, $name, \PhpSpreadsheet\Shared\OLE::OLE_PPS_TYPE_FILE, null, null, null, null, null, '', array()); + parent::__construct(null, $name, \PhpSpreadsheet\Shared\OLE::OLE_PPS_TYPE_FILE, null, null, null, null, null, '', []); } /** - * Initialization method. Has to be called right after OLE_PPS_File(). - * - * @access public - * @return mixed true on success - */ + * Initialization method. Has to be called right after OLE_PPS_File(). + * + * @return mixed true on success + */ public function init() { return true; } /** - * Append data to PPS - * - * @access public - * @param string $data The data to append - */ + * Append data to PPS + * + * @param string $data The data to append + */ public function append($data) { $this->_data .= $data; diff --git a/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php b/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php index 4296cb48..4230489e 100644 --- a/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php +++ b/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php @@ -22,16 +22,14 @@ namespace PhpSpreadsheet\Shared\OLE\PPS; // // $Id: Root.php,v 1.9 2005/04/23 21:53:49 dufuz Exp $ - /** -* Class for creating Root PPS's for OLE containers -* -* @author Xavier Noguer -* @category PhpSpreadsheet -*/ + * Class for creating Root PPS's for OLE containers + * + * @author Xavier Noguer + * @category PhpSpreadsheet + */ class Root extends \PhpSpreadsheet\Shared\OLE\PPS { - /** * Directory for temporary files * @var string @@ -39,8 +37,8 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS protected $tempDirectory = null; /** - * @param integer $time_1st A timestamp - * @param integer $time_2nd A timestamp + * @param int $time_1st A timestamp + * @param int $time_2nd A timestamp */ public function __construct($time_1st, $time_2nd, $raChild) { @@ -50,25 +48,24 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS } /** - * Method for saving the whole OLE container (including files). - * In fact, if called with an empty argument (or '-'), it saves to a - * temporary file and then outputs it's contents to stdout. - * If a resource pointer to a stream created by fopen() is passed - * it will be used, but you have to close such stream by yourself. - * - * @param string|resource $filename The name of the file or stream where to save the OLE container. - * @access public - * @return mixed true on success - * @throws \PhpSpreadsheet\Writer\Exception - */ + * Method for saving the whole OLE container (including files). + * In fact, if called with an empty argument (or '-'), it saves to a + * temporary file and then outputs it's contents to stdout. + * If a resource pointer to a stream created by fopen() is passed + * it will be used, but you have to close such stream by yourself. + * + * @param string|resource $filename The name of the file or stream where to save the OLE container. + * @throws \PhpSpreadsheet\Writer\Exception + * @return mixed true on success + */ public function save($filename) { // Initial Setting for saving - $this->_BIG_BLOCK_SIZE = pow( + $this->_BIG_BLOCK_SIZE = pow( 2, (isset($this->_BIG_BLOCK_SIZE))? self::adjust2($this->_BIG_BLOCK_SIZE) : 9 ); - $this->_SMALL_BLOCK_SIZE= pow( + $this->_SMALL_BLOCK_SIZE = pow( 2, (isset($this->_SMALL_BLOCK_SIZE))? self::adjust2($this->_SMALL_BLOCK_SIZE) : 6 ); @@ -79,20 +76,20 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS if ($this->tempDirectory === null) { $this->tempDirectory = \PhpSpreadsheet\Shared\File::sysGetTempDir(); } - $this->_tmp_filename = tempnam($this->tempDirectory, "OLE_PPS_Root"); - $this->_FILEH_ = fopen($this->_tmp_filename, "w+b"); + $this->_tmp_filename = tempnam($this->tempDirectory, 'OLE_PPS_Root'); + $this->_FILEH_ = fopen($this->_tmp_filename, 'w+b'); if ($this->_FILEH_ == false) { throw new \PhpSpreadsheet\Writer\Exception("Can't create temporary file."); } } else { - $this->_FILEH_ = fopen($filename, "wb"); + $this->_FILEH_ = fopen($filename, 'wb'); } if ($this->_FILEH_ == false) { throw new \PhpSpreadsheet\Writer\Exception("Can't open $filename. It may be in use or protected."); } // Make an array of PPS's (for Save) - $aList = array(); - \PhpSpreadsheet\Shared\OLE\PPS::_savePpsSetPnt($aList, array($this)); + $aList = []; + \PhpSpreadsheet\Shared\OLE\PPS::_savePpsSetPnt($aList, [$this]); // calculate values for header list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo); // Save Header @@ -116,16 +113,15 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS } /** - * Calculate some numbers - * - * @access public - * @param array $raList Reference to an array of PPS's - * @return array The array of numbers - */ + * Calculate some numbers + * + * @param array $raList Reference to an array of PPS's + * @return array The array of numbers + */ public function _calcSize(&$raList) { // Calculate Basic Setting - list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0); + list($iSBDcnt, $iBBcnt, $iPPScnt) = [0, 0, 0]; $iSmallLen = 0; $iSBcnt = 0; $iCount = count($raList); @@ -144,37 +140,36 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE; $iSlCnt = floor($this->_BIG_BLOCK_SIZE / \PhpSpreadsheet\Shared\OLE::OLE_LONG_INT_SIZE); $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0); - $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) + - (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0)); + $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) + + (($iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0)); $iCnt = count($raList); $iBdCnt = $this->_BIG_BLOCK_SIZE / \PhpSpreadsheet\Shared\OLE::OLE_PPS_SIZE; - $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0)); + $iPPScnt = (floor($iCnt / $iBdCnt) + (($iCnt % $iBdCnt)? 1: 0)); - return array($iSBDcnt, $iBBcnt, $iPPScnt); + return [$iSBDcnt, $iBBcnt, $iPPScnt]; } /** - * Helper function for caculating a magic value for block sizes - * - * @access public - * @param integer $i2 The argument - * @see save() - * @return integer - */ + * Helper function for caculating a magic value for block sizes + * + * @param int $i2 The argument + * @see save() + * @return int + */ private static function adjust2($i2) { - $iWk = log($i2)/log(2); - return ($iWk > floor($iWk))? floor($iWk)+1:$iWk; + $iWk = log($i2) / log(2); + + return ($iWk > floor($iWk))? floor($iWk) + 1:$iWk; } /** - * Save OLE header - * - * @access public - * @param integer $iSBDcnt - * @param integer $iBBcnt - * @param integer $iPPScnt - */ + * Save OLE header + * + * @param int $iSBDcnt + * @param int $iBBcnt + * @param int $iPPScnt + */ public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt) { $FILE = $this->_FILEH_; @@ -187,7 +182,7 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS $iAll = $iBBcnt + $iPPScnt + $iSBDcnt; $iAllW = $iAll; $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); - $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); + $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt)? 1: 0); // Calculate BD count if ($iBdCnt > $i1stBdL) { @@ -195,8 +190,8 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS ++$iBdExL; ++$iAllW; $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); - $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); - if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) { + $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt)? 1: 0); + if ($iBdCnt <= ($iBdExL * $iBlCnt + $i1stBdL)) { break; } } @@ -210,51 +205,50 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" - . pack("v", 0x3b) - . pack("v", 0x03) - . pack("v", -2) - . pack("v", 9) - . pack("v", 6) - . pack("v", 0) + . pack('v', 0x3b) + . pack('v', 0x03) + . pack('v', -2) + . pack('v', 9) + . pack('v', 6) + . pack('v', 0) . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" - . pack("V", $iBdCnt) - . pack("V", $iBBcnt+$iSBDcnt) //ROOT START - . pack("V", 0) - . pack("V", 0x1000) - . pack("V", $iSBDcnt ? 0 : -2) //Small Block Depot - . pack("V", $iSBDcnt) + . pack('V', $iBdCnt) + . pack('V', $iBBcnt + $iSBDcnt) //ROOT START + . pack('V', 0) + . pack('V', 0x1000) + . pack('V', $iSBDcnt ? 0 : -2) //Small Block Depot + . pack('V', $iSBDcnt) ); // Extra BDList Start, Count if ($iBdCnt < $i1stBdL) { fwrite( $FILE, - pack("V", -2) // Extra BDList Start - . pack("V", 0)// Extra BDList Count + pack('V', -2) // Extra BDList Start + . pack('V', 0)// Extra BDList Count ); } else { - fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL)); + fwrite($FILE, pack('V', $iAll + $iBdCnt) . pack('V', $iBdExL)); } // BDList for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) { - fwrite($FILE, pack("V", $iAll+$i)); + fwrite($FILE, pack('V', $iAll + $i)); } if ($i < $i1stBdL) { $jB = $i1stBdL - $i; for ($j = 0; $j < $jB; ++$j) { - fwrite($FILE, (pack("V", -1))); + fwrite($FILE, (pack('V', -1))); } } } /** - * Saving big data (PPS's with data bigger than \PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL) - * - * @access public - * @param integer $iStBlk - * @param array &$raList Reference to array of PPS's - */ + * Saving big data (PPS's with data bigger than \PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL) + * + * @param int $iStBlk + * @param array &$raList Reference to array of PPS's + */ public function _saveBigData($iStBlk, &$raList) { $FILE = $this->_FILEH_; @@ -297,11 +291,10 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS } /** - * get small data (PPS's with data smaller than \PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL) - * - * @access public - * @param array &$raList Reference to array of PPS's - */ + * get small data (PPS's with data smaller than \PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL) + * + * @param array &$raList Reference to array of PPS's + */ public function _makeSmallData(&$raList) { $sRes = ''; @@ -321,9 +314,9 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS // Add to SBD $jB = $iSmbCnt - 1; for ($j = 0; $j < $jB; ++$j) { - fwrite($FILE, pack("V", $j+$iSmBlk+1)); + fwrite($FILE, pack('V', $j + $iSmBlk + 1)); } - fwrite($FILE, pack("V", -2)); + fwrite($FILE, pack('V', -2)); //// Add to Data String(this will be written for RootEntry) //if ($raList[$i]->_PPS_FILE) { @@ -347,18 +340,18 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS if ($iSmBlk % $iSbCnt) { $iB = $iSbCnt - ($iSmBlk % $iSbCnt); for ($i = 0; $i < $iB; ++$i) { - fwrite($FILE, pack("V", -1)); + fwrite($FILE, pack('V', -1)); } } + return $sRes; } /** - * Saves all the PPS's WKs - * - * @access public - * @param array $raList Reference to an array with all PPS's - */ + * Saves all the PPS's WKs + * + * @param array $raList Reference to an array with all PPS's + */ public function _savePps(&$raList) { // Save each PPS WK @@ -375,13 +368,12 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS } /** - * Saving Big Block Depot - * - * @access public - * @param integer $iSbdSize - * @param integer $iBsize - * @param integer $iPpsCnt - */ + * Saving Big Block Depot + * + * @param int $iSbdSize + * @param int $iBsize + * @param int $iPpsCnt + */ public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt) { $FILE = $this->_FILEH_; @@ -393,15 +385,15 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS $iAll = $iBsize + $iPpsCnt + $iSbdSize; $iAllW = $iAll; $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); - $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); + $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt)? 1: 0); // Calculate BD count - if ($iBdCnt >$i1stBdL) { + if ($iBdCnt > $i1stBdL) { while (1) { ++$iBdExL; ++$iAllW; $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); - $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); - if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) { + $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt)? 1: 0); + if ($iBdCnt <= ($iBdExL * $iBbCnt + $i1stBdL)) { break; } } @@ -411,55 +403,55 @@ class Root extends \PhpSpreadsheet\Shared\OLE\PPS // Set for SBD if ($iSbdSize > 0) { for ($i = 0; $i < ($iSbdSize - 1); ++$i) { - fwrite($FILE, pack("V", $i+1)); + fwrite($FILE, pack('V', $i + 1)); } - fwrite($FILE, pack("V", -2)); + fwrite($FILE, pack('V', -2)); } // Set for B for ($i = 0; $i < ($iBsize - 1); ++$i) { - fwrite($FILE, pack("V", $i+$iSbdSize+1)); + fwrite($FILE, pack('V', $i + $iSbdSize + 1)); } - fwrite($FILE, pack("V", -2)); + fwrite($FILE, pack('V', -2)); // Set for PPS for ($i = 0; $i < ($iPpsCnt - 1); ++$i) { - fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1)); + fwrite($FILE, pack('V', $i + $iSbdSize + $iBsize + 1)); } - fwrite($FILE, pack("V", -2)); + fwrite($FILE, pack('V', -2)); // Set for BBD itself ( 0xFFFFFFFD : BBD) for ($i = 0; $i < $iBdCnt; ++$i) { - fwrite($FILE, pack("V", 0xFFFFFFFD)); + fwrite($FILE, pack('V', 0xFFFFFFFD)); } // Set for ExtraBDList for ($i = 0; $i < $iBdExL; ++$i) { - fwrite($FILE, pack("V", 0xFFFFFFFC)); + fwrite($FILE, pack('V', 0xFFFFFFFC)); } // Adjust for Block if (($iAllW + $iBdCnt) % $iBbCnt) { $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt)); for ($i = 0; $i < $iBlock; ++$i) { - fwrite($FILE, pack("V", -1)); + fwrite($FILE, pack('V', -1)); } } // Extra BDList if ($iBdCnt > $i1stBdL) { - $iN=0; - $iNb=0; + $iN = 0; + $iNb = 0; for ($i = $i1stBdL; $i < $iBdCnt; $i++, ++$iN) { if ($iN >= ($iBbCnt - 1)) { $iN = 0; ++$iNb; - fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb)); + fwrite($FILE, pack('V', $iAll + $iBdCnt + $iNb)); } - fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i)); + fwrite($FILE, pack('V', $iBsize + $iSbdSize + $iPpsCnt + $i)); } - if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) { + if (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)) { $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)); for ($i = 0; $i < $iB; ++$i) { - fwrite($FILE, pack("V", -1)); + fwrite($FILE, pack('V', -1)); } } - fwrite($FILE, pack("V", -2)); + fwrite($FILE, pack('V', -2)); } } } diff --git a/src/PhpSpreadsheet/Shared/OLERead.php b/src/PhpSpreadsheet/Shared/OLERead.php index 5927d63b..d46ddf91 100644 --- a/src/PhpSpreadsheet/Shared/OLERead.php +++ b/src/PhpSpreadsheet/Shared/OLERead.php @@ -2,7 +2,7 @@ namespace PhpSpreadsheet\Shared; -/** +/* * PhpSpreadsheet * * Copyright (c) 2006 - 2016 PhpSpreadsheet @@ -35,40 +35,37 @@ class OLERead private $data = ''; // OLE identifier - const IDENTIFIER_OLE = IDENTIFIER_OLE; + const IDENTIFIER_OLE = IDENTIFIER_OLE; // Size of a sector = 512 bytes - const BIG_BLOCK_SIZE = 0x200; + const BIG_BLOCK_SIZE = 0x200; // Size of a short sector = 64 bytes - const SMALL_BLOCK_SIZE = 0x40; + const SMALL_BLOCK_SIZE = 0x40; // Size of a directory entry always = 128 bytes - const PROPERTY_STORAGE_BLOCK_SIZE = 0x80; + const PROPERTY_STORAGE_BLOCK_SIZE = 0x80; // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams - const SMALL_BLOCK_THRESHOLD = 0x1000; + const SMALL_BLOCK_THRESHOLD = 0x1000; // header offsets - const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c; - const ROOT_START_BLOCK_POS = 0x30; - const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c; - const EXTENSION_BLOCK_POS = 0x44; - const NUM_EXTENSION_BLOCK_POS = 0x48; - const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c; + const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c; + const ROOT_START_BLOCK_POS = 0x30; + const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c; + const EXTENSION_BLOCK_POS = 0x44; + const NUM_EXTENSION_BLOCK_POS = 0x48; + const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c; // property storage offsets (directory offsets) - const SIZE_OF_NAME_POS = 0x40; - const TYPE_POS = 0x42; - const START_BLOCK_POS = 0x74; - const SIZE_POS = 0x78; - - - - public $wrkbook = null; - public $summaryInformation = null; - public $documentSummaryInformation = null; + const SIZE_OF_NAME_POS = 0x40; + const TYPE_POS = 0x42; + const START_BLOCK_POS = 0x74; + const SIZE_POS = 0x78; + public $wrkbook = null; + public $summaryInformation = null; + public $documentSummaryInformation = null; /** * Read the file @@ -80,7 +77,7 @@ class OLERead { // Check if file exists and is readable if (!is_readable($sFileName)) { - throw new \PhpSpreadsheet\Reader\Exception("Could not open " . $sFileName . " for reading! File does not exist, or it is not readable."); + throw new \PhpSpreadsheet\Reader\Exception('Could not open ' . $sFileName . ' for reading! File does not exist, or it is not readable.'); } // Get the file identifier @@ -110,18 +107,18 @@ class OLERead // Total number of sectors used by MSAT $this->numExtensionBlocks = self::getInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS); - $bigBlockDepotBlocks = array(); + $bigBlockDepotBlocks = []; $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS; $bbdBlocks = $this->numBigBlockDepotBlocks; if ($this->numExtensionBlocks != 0) { - $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS)/4; + $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS) / 4; } for ($i = 0; $i < $bbdBlocks; ++$i) { - $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); - $pos += 4; + $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); + $pos += 4; } for ($j = 0; $j < $this->numExtensionBlocks; ++$j) { @@ -145,8 +142,8 @@ class OLERead for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) { $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE; - $this->bigBlockChain .= substr($this->data, $pos, 4*$bbs); - $pos += 4*$bbs; + $this->bigBlockChain .= substr($this->data, $pos, 4 * $bbs); + $pos += 4 * $bbs; } $pos = 0; @@ -155,10 +152,10 @@ class OLERead while ($sbdBlock != -2) { $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE; - $this->smallBlockChain .= substr($this->data, $pos, 4*$bbs); - $pos += 4*$bbs; + $this->smallBlockChain .= substr($this->data, $pos, 4 * $bbs); + $pos += 4 * $bbs; - $sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock*4); + $sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock * 4); } // read the directory stream @@ -187,10 +184,10 @@ class OLERead $block = $this->props[$stream]['startBlock']; while ($block != -2) { - $pos = $block * self::SMALL_BLOCK_SIZE; + $pos = $block * self::SMALL_BLOCK_SIZE; $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE); - $block = self::getInt4d($this->smallBlockChain, $block*4); + $block = self::getInt4d($this->smallBlockChain, $block * 4); } return $streamData; @@ -209,7 +206,7 @@ class OLERead while ($block != -2) { $pos = ($block + 1) * self::BIG_BLOCK_SIZE; $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); - $block = self::getInt4d($this->bigBlockChain, $block*4); + $block = self::getInt4d($this->bigBlockChain, $block * 4); } return $streamData; @@ -230,8 +227,9 @@ class OLERead while ($block != -2) { $pos = ($block + 1) * self::BIG_BLOCK_SIZE; $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); - $block = self::getInt4d($this->bigBlockChain, $block*4); + $block = self::getInt4d($this->bigBlockChain, $block * 4); } + return $data; } @@ -249,7 +247,7 @@ class OLERead $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE); // size in bytes of name - $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS+1]) << 8); + $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS + 1]) << 8); // type of entry $type = ord($d[self::TYPE_POS]); @@ -260,14 +258,14 @@ class OLERead $size = self::getInt4d($d, self::SIZE_POS); - $name = str_replace("\x00", "", substr($d, 0, $nameSize)); + $name = str_replace("\x00", '', substr($d, 0, $nameSize)); - $this->props[] = array( + $this->props[] = [ 'name' => $name, 'type' => $type, 'startBlock' => $startBlock, - 'size' => $size - ); + 'size' => $size, + ]; // tmp helper to simplify checks $upName = strtoupper($name); @@ -282,13 +280,13 @@ class OLERead // Summary information if ($name == chr(5) . 'SummaryInformation') { -// echo 'Summary Information
'; + // echo 'Summary Information
'; $this->summaryInformation = count($this->props) - 1; } // Additional Document Summary information if ($name == chr(5) . 'DocumentSummaryInformation') { -// echo 'Document Summary Information
'; + // echo 'Document Summary Information
'; $this->documentSummaryInformation = count($this->props) - 1; } @@ -315,6 +313,7 @@ class OLERead } else { $_ord_24 = ($_or_24 & 127) << 24; } + return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; } } diff --git a/src/PhpSpreadsheet/Shared/PCLZip/PclZip.php b/src/PhpSpreadsheet/Shared/PCLZip/PclZip.php index 7e1b7699..9c6ab98b 100644 --- a/src/PhpSpreadsheet/Shared/PCLZip/PclZip.php +++ b/src/PhpSpreadsheet/Shared/PCLZip/PclZip.php @@ -86,7 +86,7 @@ if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { // -------------------------------------------------------------------------------- // ----- Global variables -$g_pclzip_version = "2.8.2"; +$g_pclzip_version = '2.8.2'; // ----- Error codes // -1 : Unable to open file in binary write mode @@ -220,7 +220,7 @@ class PclZip // ----- Tests the zlib if (!function_exists('gzopen')) { - die('Abort '.basename(__FILE__).' : Missing zlib extensions'); + die('Abort ' . basename(__FILE__) . ' : Missing zlib extensions'); } // ----- Set the attributes @@ -272,13 +272,13 @@ class PclZip // -------------------------------------------------------------------------------- public function create($p_filelist) { - $v_result=1; + $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Set default values - $v_options = array(); + $v_options = []; $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; // ----- Look for variable options arguments @@ -291,12 +291,12 @@ class PclZip // ----- Remove from the options list the first argument array_shift($v_arg_list); - $v_size--; + --$v_size; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, [ PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', @@ -306,9 +306,9 @@ class PclZip PCLZIP_OPT_COMMENT => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + PCLZIP_OPT_TEMP_FILE_OFF => 'optional', //, PCLZIP_OPT_CRYPT => 'optional' - )); + ]); if ($v_result != 1) { return 0; } @@ -323,7 +323,8 @@ class PclZip if ($v_size == 2) { $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; } elseif ($v_size > 2) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Invalid number / type of arguments'); + return 0; } } @@ -333,10 +334,10 @@ class PclZip $this->privOptionDefaultThreshold($v_options); // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); + $v_string_list = []; + $v_att_list = []; + $v_filedescr_list = []; + $p_result_list = []; // ----- Look if the $p_filelist is really an array if (is_array($p_filelist)) { @@ -354,7 +355,8 @@ class PclZip $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); } else { // ----- Invalid variable type for $p_filelist - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Invalid variable type p_filelist'); + return 0; } @@ -369,14 +371,14 @@ class PclZip } // ----- For each file in the list check the attributes - $v_supported_attributes = array( + $v_supported_attributes = [ PCLZIP_ATT_FILE_NAME => 'mandatory', PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', PCLZIP_ATT_FILE_MTIME => 'optional', PCLZIP_ATT_FILE_CONTENT => 'optional', - PCLZIP_ATT_FILE_COMMENT => 'optional' - ); + PCLZIP_ATT_FILE_COMMENT => 'optional', + ]; foreach ($v_att_list as $v_entry) { $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); if ($v_result != 1) { @@ -438,13 +440,13 @@ class PclZip // -------------------------------------------------------------------------------- public function add($p_filelist) { - $v_result=1; + $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Set default values - $v_options = array(); + $v_options = []; $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; // ----- Look for variable options arguments @@ -457,12 +459,12 @@ class PclZip // ----- Remove form the options list the first argument array_shift($v_arg_list); - $v_size--; + --$v_size; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, [ PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', @@ -474,9 +476,9 @@ class PclZip PCLZIP_OPT_PREPEND_COMMENT => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + PCLZIP_OPT_TEMP_FILE_OFF => 'optional', //, PCLZIP_OPT_CRYPT => 'optional' - )); + ]); if ($v_result != 1) { return 0; } @@ -492,7 +494,7 @@ class PclZip $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; } elseif ($v_size > 2) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Invalid number / type of arguments'); // ----- Return return 0; @@ -504,10 +506,10 @@ class PclZip $this->privOptionDefaultThreshold($v_options); // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); + $v_string_list = []; + $v_att_list = []; + $v_filedescr_list = []; + $p_result_list = []; // ----- Look if the $p_filelist is really an array if (is_array($p_filelist)) { @@ -525,7 +527,8 @@ class PclZip $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); } else { // ----- Invalid variable type for $p_filelist - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '" . gettype($p_filelist) . "' for p_filelist"); + return 0; } @@ -537,14 +540,14 @@ class PclZip } // ----- For each file in the list check the attributes - $v_supported_attributes = array( + $v_supported_attributes = [ PCLZIP_ATT_FILE_NAME => 'mandatory', PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', PCLZIP_ATT_FILE_MTIME => 'optional', PCLZIP_ATT_FILE_CONTENT => 'optional', PCLZIP_ATT_FILE_COMMENT => 'optional', - ); + ]; foreach ($v_att_list as $v_entry) { $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); if ($v_result != 1) { @@ -612,21 +615,22 @@ class PclZip // -------------------------------------------------------------------------------- public function listContent() { - $v_result=1; + $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { - return(0); + return 0; } // ----- Call the extracting fct - $p_list = array(); + $p_list = []; if (($v_result = $this->privList($p_list)) != 1) { unset($p_list); - return(0); + + return 0; } // ----- Return @@ -668,21 +672,21 @@ class PclZip // -------------------------------------------------------------------------------- public function extract() { - $v_result=1; + $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { - return(0); + return 0; } // ----- Set default values - $v_options = array(); + $v_options = []; // $v_path = "./"; $v_path = ''; - $v_remove_path = ""; + $v_remove_path = ''; $v_remove_all_path = false; // ----- Look for variable options arguments @@ -699,7 +703,7 @@ class PclZip // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, [ PCLZIP_OPT_PATH => 'optional', PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', @@ -718,8 +722,8 @@ class PclZip PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); + PCLZIP_OPT_TEMP_FILE_OFF => 'optional', + ]); if ($v_result != 1) { return 0; } @@ -753,7 +757,7 @@ class PclZip $v_remove_path = $v_arg_list[1]; } elseif ($v_size > 2) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Invalid number / type of arguments'); // ----- Return return 0; @@ -767,11 +771,12 @@ class PclZip // ----- Trace // ----- Call the extracting fct - $p_list = array(); + $p_list = []; $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options); if ($v_result < 1) { unset($p_list); - return(0); + + return 0; } // ----- Return @@ -779,7 +784,6 @@ class PclZip } // -------------------------------------------------------------------------------- - // -------------------------------------------------------------------------------- // Function : // extractByIndex($p_index, $p_path="./", $p_remove_path="") @@ -819,21 +823,21 @@ class PclZip //function extractByIndex($p_index, options...) public function extractByIndex($p_index) { - $v_result=1; + $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { - return(0); + return 0; } // ----- Set default values - $v_options = array(); + $v_options = []; // $v_path = "./"; $v_path = ''; - $v_remove_path = ""; + $v_remove_path = ''; $v_remove_all_path = false; // ----- Look for variable options arguments @@ -849,12 +853,12 @@ class PclZip // ----- Remove form the options list the first argument array_shift($v_arg_list); - $v_size--; + --$v_size; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, [ PCLZIP_OPT_PATH => 'optional', PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', @@ -868,8 +872,8 @@ class PclZip PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); + PCLZIP_OPT_TEMP_FILE_OFF => 'optional', + ]); if ($v_result != 1) { return 0; } @@ -908,7 +912,7 @@ class PclZip $v_remove_path = $v_arg_list[1]; } elseif ($v_size > 2) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Invalid number / type of arguments'); // ----- Return return 0; @@ -921,9 +925,9 @@ class PclZip // ----- Trick // Here I want to reuse extractByRule(), so I need to parse the $p_index // with privParseOptions() - $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); - $v_options_trick = array(); - $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, array (PCLZIP_OPT_BY_INDEX => 'optional')); + $v_arg_trick = [PCLZIP_OPT_BY_INDEX, $p_index]; + $v_options_trick = []; + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, [PCLZIP_OPT_BY_INDEX => 'optional']); if ($v_result != 1) { return 0; } @@ -934,7 +938,7 @@ class PclZip // ----- Call the extracting fct if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { - return(0); + return 0; } // ----- Return @@ -962,18 +966,18 @@ class PclZip // -------------------------------------------------------------------------------- public function delete() { - $v_result=1; + $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { - return(0); + return 0; } // ----- Set default values - $v_options = array(); + $v_options = []; // ----- Look for variable options arguments $v_size = func_num_args(); @@ -984,14 +988,14 @@ class PclZip $v_arg_list = func_get_args(); // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, [ PCLZIP_OPT_BY_NAME => 'optional', PCLZIP_OPT_BY_EREG => 'optional', PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional' - )); + PCLZIP_OPT_BY_INDEX => 'optional', + ]); if ($v_result != 1) { - return 0; + return 0; } } @@ -999,11 +1003,12 @@ class PclZip $this->privDisableMagicQuotes(); // ----- Call the delete fct - $v_list = array(); + $v_list = []; if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { $this->privSwapBackMagicQuotes(); unset($v_list); - return(0); + + return 0; } // ----- Magic quotes trick @@ -1022,7 +1027,6 @@ class PclZip // -------------------------------------------------------------------------------- public function deleteByIndex($p_index) { - $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); // ----- Return @@ -1056,11 +1060,12 @@ class PclZip // ----- Check archive if (!$this->privCheckFormat()) { $this->privSwapBackMagicQuotes(); - return(0); + + return 0; } // ----- Default properties - $v_prop = array(); + $v_prop = []; $v_prop['comment'] = ''; $v_prop['nb'] = 0; $v_prop['status'] = 'not_exist'; @@ -1072,16 +1077,17 @@ class PclZip $this->privSwapBackMagicQuotes(); // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in binary read mode'); // ----- Return return 0; } // ----- Read the central directory informations - $v_central_dir = array(); + $v_central_dir = []; if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privSwapBackMagicQuotes(); + return 0; } @@ -1131,7 +1137,7 @@ class PclZip // TBC : Should also check the archive format if (!is_file($p_archive)) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '" . $p_archive . "'"); $v_result = PCLZIP_ERR_MISSING_FILE; } else { // ----- Duplicate the archive @@ -1140,7 +1146,7 @@ class PclZip } else { // ----- Invalid variable // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Invalid variable type p_archive_to_add'); $v_result = PCLZIP_ERR_INVALID_PARAMETER; } @@ -1172,7 +1178,7 @@ class PclZip // ----- Check archive if (!$this->privCheckFormat()) { - return(0); + return 0; } // ----- Look if the $p_archive_to_add is a PclZip object @@ -1182,14 +1188,14 @@ class PclZip } elseif (is_string($p_archive_to_add)) { // ----- Look if the $p_archive_to_add is a string (so a filename) // ----- Create a temporary archive - $v_object_archive = new PclZip($p_archive_to_add); + $v_object_archive = new self($p_archive_to_add); // ----- Merge the archive $v_result = $this->privMerge($v_object_archive); } else { // ----- Invalid variable // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Invalid variable type p_archive_to_add'); $v_result = PCLZIP_ERR_INVALID_PARAMETER; } @@ -1198,8 +1204,6 @@ class PclZip } // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- // Function : errorCode() // Description : @@ -1208,9 +1212,9 @@ class PclZip public function errorCode() { if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorCode()); + return PclErrorCode(); } else { - return($this->error_code); + return $this->error_code; } } // -------------------------------------------------------------------------------- @@ -1222,7 +1226,7 @@ class PclZip // -------------------------------------------------------------------------------- public function errorName($p_with_code = false) { - $v_name = array( + $v_name = [ PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', @@ -1244,7 +1248,7 @@ class PclZip PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION', - ); + ]; if (isset($v_name[$this->error_code])) { $v_value = $v_name[$this->error_code]; @@ -1253,9 +1257,9 @@ class PclZip } if ($p_with_code) { - return($v_value.' ('.$this->error_code.')'); + return $v_value . ' (' . $this->error_code . ')'; } else { - return($v_value); + return $v_value; } } // -------------------------------------------------------------------------------- @@ -1268,26 +1272,23 @@ class PclZip public function errorInfo($p_full = false) { if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorString()); + return PclErrorString(); } else { if ($p_full) { - return($this->errorName(true)." : ".$this->error_string); + return $this->errorName(true) . ' : ' . $this->error_string; } else { - return($this->error_string." [code ".$this->error_code."]"); + return $this->error_string . ' [code ' . $this->error_code . ']'; } } } // -------------------------------------------------------------------------------- - // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** // ***** ***** // ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- // Function : privCheckFormat() // Description : @@ -1315,15 +1316,17 @@ class PclZip // ----- Look if the file exits if (!is_file($this->zipname)) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); - return(false); + self::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '" . $this->zipname . "'"); + + return false; } // ----- Check that the file is readeable if (!is_readable($this->zipname)) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); - return(false); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '" . $this->zipname . "'"); + + return false; } // ----- Check the magic code @@ -1357,18 +1360,18 @@ class PclZip // -------------------------------------------------------------------------------- public function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options = false) { - $v_result=1; + $v_result = 1; // ----- Read the options - $i=0; - while ($i<$p_size) { + $i = 0; + while ($i < $p_size) { // ----- Check if the option is supported if (!isset($v_requested_options[$p_options_list[$i]])) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '" . $p_options_list[$i] . "' for this method"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Look for next option @@ -1378,49 +1381,53 @@ class PclZip case PCLZIP_OPT_REMOVE_PATH: case PCLZIP_OPT_ADD_PATH: // ----- Check the number of parameters - if (($i+1) >= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); - $i++; + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i + 1], false); + ++$i; break; case PCLZIP_OPT_TEMP_FILE_THRESHOLD: // ----- Check the number of parameters - if (($i+1) >= $p_size) { - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); + if (($i + 1) >= $p_size) { + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + return self::errorCode(); } // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + + return self::errorCode(); } // ----- Check the value - $v_value = $p_options_list[$i+1]; - if ((!is_integer($v_value)) || ($v_value<0)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); + $v_value = $p_options_list[$i + 1]; + if ((!is_integer($v_value)) || ($v_value < 0)) { + self::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + return self::errorCode(); } // ----- Get the value (and convert it in bytes) - $v_result_list[$p_options_list[$i]] = $v_value*1048576; - $i++; + $v_result_list[$p_options_list[$i]] = $v_value * 1048576; + ++$i; break; case PCLZIP_OPT_TEMP_FILE_ON: // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + + return self::errorCode(); } $v_result_list[$p_options_list[$i]] = true; @@ -1429,55 +1436,57 @@ class PclZip case PCLZIP_OPT_TEMP_FILE_OFF: // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + + return self::errorCode(); } // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + + return self::errorCode(); } $v_result_list[$p_options_list[$i]] = true; break; case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION: // ----- Check the number of parameters - if (($i+1) >= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - if (is_string($p_options_list[$i+1]) && ($p_options_list[$i+1] != '')) { - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); - $i++; + if (is_string($p_options_list[$i + 1]) && ($p_options_list[$i + 1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i + 1], false); + ++$i; } else { } break; // ----- Look for options that request an array of string for value case PCLZIP_OPT_BY_NAME: // ----- Check the number of parameters - if (($i+1) >= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; - } elseif (is_array($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + if (is_string($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i + 1]; + } elseif (is_array($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; } else { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } - $i++; + ++$i; break; // ----- Look for options that request an EREG or PREG expression case PCLZIP_OPT_BY_EREG: @@ -1488,23 +1497,23 @@ class PclZip case PCLZIP_OPT_BY_PREG: //case PCLZIP_OPT_CRYPT : // ----- Check the number of parameters - if (($i+1) >= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + if (is_string($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; } else { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } - $i++; + ++$i; break; // ----- Look for options that takes a string @@ -1512,67 +1521,67 @@ class PclZip case PCLZIP_OPT_ADD_COMMENT: case PCLZIP_OPT_PREPEND_COMMENT: // ----- Check the number of parameters - if (($i+1) >= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + if (is_string($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; } else { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" .PclZipUtilOptionText($p_options_list[$i]) ."'"); + self::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } - $i++; + ++$i; break; // ----- Look for options that request an array of index case PCLZIP_OPT_BY_INDEX: // ----- Check the number of parameters - if (($i+1) >= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - $v_work_list = array(); - if (is_string($p_options_list[$i+1])) { + $v_work_list = []; + if (is_string($p_options_list[$i + 1])) { // ----- Remove spaces - $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + $p_options_list[$i + 1] = strtr($p_options_list[$i + 1], ' ', ''); // ----- Parse items - $v_work_list = explode(",", $p_options_list[$i+1]); - } elseif (is_integer($p_options_list[$i+1])) { - $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; - } elseif (is_array($p_options_list[$i+1])) { - $v_work_list = $p_options_list[$i+1]; + $v_work_list = explode(',', $p_options_list[$i + 1]); + } elseif (is_integer($p_options_list[$i + 1])) { + $v_work_list[0] = $p_options_list[$i + 1] . '-' . $p_options_list[$i + 1]; + } elseif (is_array($p_options_list[$i + 1])) { + $v_work_list = $p_options_list[$i + 1]; } else { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Reduce the index list // each index item in the list must be a couple with a start and // an end value : [0,3], [5-5], [8-10], ... // ----- Check the format of each item - $v_sort_flag=false; - $v_sort_value=0; - for ($j=0; $j= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - $i++; + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; + ++$i; break; // ----- Look for options that request a call-back @@ -1652,52 +1660,52 @@ class PclZip case PCLZIP_CB_POST_LIST : */ // ----- Check the number of parameters - if (($i+1) >= $p_size) { + if (($i + 1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Get the value - $v_function_name = $p_options_list[$i+1]; + $v_function_name = $p_options_list[$i + 1]; // ----- Check that the value is a valid existing function if (!function_exists($v_function_name)) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + self::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '" . $v_function_name . "()' is not an existing function for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Set the attribute $v_result_list[$p_options_list[$i]] = $v_function_name; - $i++; + ++$i; break; default: // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" .$p_options_list[$i]."'"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" . $p_options_list[$i] . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Next options - $i++; + ++$i; } // ----- Look for mandatory options if ($v_requested_options !== false) { - for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) { // ----- Look for mandatory option if ($v_requested_options[$key] == 'mandatory') { // ----- Look if present if (!isset($v_result_list[$key])) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Missing mandatory parameter ' . PclZipUtilOptionText($key) . '(' . $key . ')'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } } } @@ -1720,7 +1728,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privOptionDefaultThreshold(&$p_options) { - $v_result=1; + $v_result = 1; if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { return $v_result; @@ -1733,17 +1741,17 @@ class PclZip if ($last == 'g') { //$v_memory_limit = $v_memory_limit*1024*1024*1024; - $v_memory_limit = $v_memory_limit*1073741824; + $v_memory_limit = $v_memory_limit * 1073741824; } if ($last == 'm') { //$v_memory_limit = $v_memory_limit*1024*1024; - $v_memory_limit = $v_memory_limit*1048576; + $v_memory_limit = $v_memory_limit * 1048576; } if ($last == 'k') { - $v_memory_limit = $v_memory_limit*1024; + $v_memory_limit = $v_memory_limit * 1024; } - $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); + $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit * PCLZIP_TEMPORARY_FILE_RATIO); // ----- Sanity check : No threshold if value lower than 1M if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { @@ -1765,72 +1773,80 @@ class PclZip // -------------------------------------------------------------------------------- public function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options = false) { - $v_result=1; + $v_result = 1; // ----- For each file in the list check the attributes foreach ($p_file_list as $v_key => $v_value) { // ----- Check if the option is supported if (!isset($v_requested_options[$v_key])) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '" . $v_key . "' for this file"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Look for attribute switch ($v_key) { case PCLZIP_ATT_FILE_NAME: if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type ' . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['filename'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } break; case PCLZIP_ATT_FILE_NEW_SHORT_NAME: if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type ' . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['new_short_name'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } break; case PCLZIP_ATT_FILE_NEW_FULL_NAME: if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type ' . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['new_full_name'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } break; // ----- Look for options that takes a string case PCLZIP_ATT_FILE_COMMENT: if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type ' . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } $p_filedescr['comment'] = $v_value; break; case PCLZIP_ATT_FILE_MTIME: if (!is_integer($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type ' . gettype($v_value) . ". Integer expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return self::errorCode(); } $p_filedescr['mtime'] = $v_value; break; @@ -1839,10 +1855,10 @@ class PclZip break; default: // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '".$v_key."'"); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" . $v_key . "'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Look for mandatory options @@ -1852,8 +1868,9 @@ class PclZip if ($v_requested_options[$key] == 'mandatory') { // ----- Look if present if (!isset($p_file_list[$key])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, 'Missing mandatory parameter ' . PclZipUtilOptionText($key) . '(' . $key . ')'); + + return self::errorCode(); } } } @@ -1881,13 +1898,13 @@ class PclZip // -------------------------------------------------------------------------------- public function privFileDescrExpand(&$p_filedescr_list, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Create a result list - $v_result_list = array(); + $v_result_list = []; // ----- Look each entry - for ($i=0; $iprivDisableMagicQuotes(); @@ -2026,8 +2043,8 @@ class PclZip // -------------------------------------------------------------------------------- public function privAdd($p_filedescr_list, &$p_result_list, &$p_options) { - $v_result=1; - $v_list_detail = array(); + $v_result = 1; + $v_list_detail = []; // ----- Look if the archive exists or is empty if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) { @@ -2041,7 +2058,7 @@ class PclZip $this->privDisableMagicQuotes(); // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) { + if (($v_result = $this->privOpenFd('rb')) != 1) { // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); @@ -2050,10 +2067,11 @@ class PclZip } // ----- Read the central directory informations - $v_central_dir = array(); + $v_central_dir = []; if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); + return $v_result; } @@ -2061,17 +2079,17 @@ class PclZip @rewind($this->zip_fd); // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp'; // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary write mode'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Copy the files from the archive to the temporary file @@ -2092,7 +2110,7 @@ class PclZip $v_zip_temp_fd = $v_swap; // ----- Add the files - $v_header_list = array(); + $v_header_list = []; if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { fclose($v_zip_temp_fd); $this->privCloseFd(); @@ -2116,7 +2134,7 @@ class PclZip } // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { @@ -2128,7 +2146,7 @@ class PclZip // ----- Return return $v_result; } - $v_count++; + ++$v_count; } // ----- Transform the header to a 'usable' info @@ -2141,17 +2159,17 @@ class PclZip $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { - $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; + $v_comment = $v_comment . $p_options[PCLZIP_OPT_ADD_COMMENT]; } if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT] . $v_comment; } // ----- Calculate the size of the central header - $v_size = @ftell($this->zip_fd)-$v_offset; + $v_size = @ftell($this->zip_fd) - $v_offset; // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) { + if (($v_result = $this->privWriteCentralHeader($v_count + $v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) { // ----- Reset the file list unset($v_header_list); $this->privSwapBackMagicQuotes(); @@ -2195,24 +2213,24 @@ class PclZip // -------------------------------------------------------------------------------- public function privOpenFd($p_mode) { - $v_result=1; + $v_result = 1; // ----- Look if already open if ($this->zip_fd != 0) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \'' . $this->zipname . '\' already open'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Open the zip file if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in ' . $p_mode . ' mode'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Return @@ -2227,7 +2245,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privCloseFd() { - $v_result=1; + $v_result = 1; if ($this->zip_fd != 0) { @fclose($this->zip_fd); @@ -2255,10 +2273,10 @@ class PclZip // public function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) public function privAddList($p_filedescr_list, &$p_result_list, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Add the files - $v_header_list = array(); + $v_header_list = []; if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { // ----- Return return $v_result; @@ -2268,14 +2286,14 @@ class PclZip $v_offset = @ftell($this->zip_fd); // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { // ----- Return return $v_result; } - $v_count++; + ++$v_count; } // ----- Transform the header to a 'usable' info @@ -2289,7 +2307,7 @@ class PclZip } // ----- Calculate the size of the central header - $v_size = @ftell($this->zip_fd)-$v_offset; + $v_size = @ftell($this->zip_fd) - $v_offset; // ----- Create the central dir footer if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) { @@ -2316,27 +2334,28 @@ class PclZip // -------------------------------------------------------------------------------- public function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) { - $v_result=1; - $v_header = array(); + $v_result = 1; + $v_header = []; // ----- Recuperate the current number of elt in list $v_nb = sizeof($p_result_list); // ----- Loop on the files - for ($j=0; ($jprivConvertHeader2FileInfo($p_header, $v_local_header); // ----- Call the callback @@ -2458,7 +2477,7 @@ class PclZip $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); if ($v_result == 0) { // ----- Change the file status - $p_header['status'] = "skipped"; + $p_header['status'] = 'skipped'; $v_result = 1; } @@ -2470,8 +2489,8 @@ class PclZip } // ----- Look for empty stored filename - if ($p_header['stored_filename'] == "") { - $p_header['status'] = "filtered"; + if ($p_header['stored_filename'] == '') { + $p_header['status'] = 'filtered'; } // ----- Check the path length @@ -2492,9 +2511,10 @@ class PclZip } else { // ----- Use "in memory" zip algo // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return PclZip::errorCode(); + if (($v_file = @fopen($p_filename, 'rb')) == 0) { + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + + return self::errorCode(); } // ----- Read the file content @@ -2524,6 +2544,7 @@ class PclZip // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { @fclose($v_file); + return $v_result; } @@ -2555,6 +2576,7 @@ class PclZip // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { @fclose($v_file); + return $v_result; } @@ -2582,7 +2604,7 @@ class PclZip // ----- Look for post-add callback if (isset($p_options[PCLZIP_CB_POST_ADD])) { // ----- Generate a local information - $v_local_header = array(); + $v_local_header = []; $this->privConvertHeader2FileInfo($p_header, $v_local_header); // ----- Call the callback @@ -2612,24 +2634,25 @@ class PclZip // -------------------------------------------------------------------------------- public function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) { - $v_result=PCLZIP_ERR_NO_ERROR; + $v_result = PCLZIP_ERR_NO_ERROR; // ----- Working variable $p_filename = $p_filedescr['filename']; - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return PclZip::errorCode(); + if (($v_file = @fopen($p_filename, 'rb')) == 0) { + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + + return self::errorCode(); } // ----- Creates a compressed temporary file - $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; - if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.gz'; + if (($v_file_compressed = @gzopen($v_gzip_temp_name, 'wb')) == 0) { fclose($v_file); - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary write mode'); + + return self::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks @@ -2648,14 +2671,16 @@ class PclZip // ----- Check the minimum file size if (filesize($v_gzip_temp_name) < 18) { - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \'' . $v_gzip_temp_name . '\' has invalid filesize - should be minimum 18 bytes'); + + return self::errorCode(); } // ----- Extract the compressed attributes - if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); + if (($v_file_compressed = @fopen($v_gzip_temp_name, 'rb')) == 0) { + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode'); + + return self::errorCode(); } // ----- Read the gzip file header @@ -2666,7 +2691,7 @@ class PclZip $v_data_header['os'] = bin2hex($v_data_header['os']); // ----- Read the gzip file footer - @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); + @fseek($v_file_compressed, filesize($v_gzip_temp_name) - 8); $v_binary_data = @fread($v_file_compressed, 8); $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); @@ -2674,7 +2699,7 @@ class PclZip $p_header['compression'] = ord($v_data_header['cm']); //$p_header['mtime'] = $v_data_header['mtime']; $p_header['crc'] = $v_data_footer['crc']; - $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; + $p_header['compressed_size'] = filesize($v_gzip_temp_name) - 18; // ----- Close the file @fclose($v_file_compressed); @@ -2685,9 +2710,10 @@ class PclZip } // ----- Add the compressed data - if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); + if (($v_file_compressed = @fopen($v_gzip_temp_name, 'rb')) == 0) { + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode'); + + return self::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks @@ -2722,7 +2748,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privCalculateStoredFilename(&$p_filedescr, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Working variables $p_filename = $p_filedescr['filename']; @@ -2754,9 +2780,9 @@ class PclZip $v_path_info = pathinfo($p_filename); $v_dir = ''; if ($v_path_info['dirname'] != '') { - $v_dir = $v_path_info['dirname'].'/'; + $v_dir = $v_path_info['dirname'] . '/'; } - $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; + $v_stored_filename = $v_dir . $p_filedescr['new_short_name']; } else { // ----- Calculate the stored filename $v_stored_filename = $p_filename; @@ -2765,17 +2791,17 @@ class PclZip // ----- Look for all path to remove if ($p_remove_all_dir) { $v_stored_filename = basename($p_filename); - } elseif ($p_remove_dir != "") { + } elseif ($p_remove_dir != '') { // ----- Look for partial path remove if (substr($p_remove_dir, -1) != '/') { - $p_remove_dir .= "/"; + $p_remove_dir .= '/'; } - if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) { - if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) { - $p_remove_dir = "./".$p_remove_dir; + if ((substr($p_filename, 0, 2) == './') || (substr($p_remove_dir, 0, 2) == './')) { + if ((substr($p_filename, 0, 2) == './') && (substr($p_remove_dir, 0, 2) != './')) { + $p_remove_dir = './' . $p_remove_dir; } - if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) { + if ((substr($p_filename, 0, 2) != './') && (substr($p_remove_dir, 0, 2) == './')) { $p_remove_dir = substr($p_remove_dir, 2); } } @@ -2783,7 +2809,7 @@ class PclZip $v_compare = PclZipUtilPathInclusion($p_remove_dir, $v_stored_filename); if ($v_compare > 0) { if ($v_compare == 2) { - $v_stored_filename = ""; + $v_stored_filename = ''; } else { $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir)); } @@ -2794,11 +2820,11 @@ class PclZip $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); // ----- Look for path to add - if ($p_add_dir != "") { - if (substr($p_add_dir, -1) == "/") { - $v_stored_filename = $p_add_dir.$v_stored_filename; + if ($p_add_dir != '') { + if (substr($p_add_dir, -1) == '/') { + $v_stored_filename = $p_add_dir . $v_stored_filename; } else { - $v_stored_filename = $p_add_dir."/".$v_stored_filename; + $v_stored_filename = $p_add_dir . '/' . $v_stored_filename; } } } @@ -2820,18 +2846,18 @@ class PclZip // -------------------------------------------------------------------------------- public function privWriteFileHeader(&$p_header) { - $v_result=1; + $v_result = 1; // ----- Store the offset position of the file $p_header['offset'] = ftell($this->zip_fd); // ----- Transform UNIX mtime to DOS format mdate/mtime $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + $v_mtime = ($v_date['hours'] << 11) + ($v_date['minutes'] << 5) + $v_date['seconds'] / 2; + $v_mdate = (($v_date['year'] - 1980) << 9) + ($v_date['mon'] << 5) + $v_date['mday']; // ----- Packed data - $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']); + $v_binary_data = pack('VvvvvvVVVvv', 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']); // ----- Write the first 148 bytes of the header in the archive fputs($this->zip_fd, $v_binary_data, 30); @@ -2857,7 +2883,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privWriteCentralFileHeader(&$p_header) { - $v_result=1; + $v_result = 1; // TBC //for(reset($p_header); $key = key($p_header); next($p_header)) { @@ -2865,12 +2891,11 @@ class PclZip // ----- Transform UNIX mtime to DOS format mdate/mtime $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - + $v_mtime = ($v_date['hours'] << 11) + ($v_date['minutes'] << 5) + $v_date['seconds'] / 2; + $v_mdate = (($v_date['year'] - 1980) << 9) + ($v_date['mon'] << 5) + $v_date['mday']; // ----- Packed data - $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); + $v_binary_data = pack('VvvvvvvVVVvvvvvVV', 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); // ----- Write the 42 bytes of the header in the zip file fputs($this->zip_fd, $v_binary_data, 46); @@ -2902,7 +2927,7 @@ class PclZip $v_result = 1; // ----- Packed data - $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); + $v_binary_data = pack('VvvvvVVv', 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); // ----- Write the 22 bytes of the header in the zip file fputs($this->zip_fd, $v_binary_data, 22); @@ -2936,16 +2961,17 @@ class PclZip $this->privSwapBackMagicQuotes(); // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in binary read mode'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read the central directory informations - $v_central_dir = array(); + $v_central_dir = []; if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privSwapBackMagicQuotes(); + return $v_result; } @@ -2955,17 +2981,18 @@ class PclZip $this->privSwapBackMagicQuotes(); // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + self::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read each entry - for ($i=0; $i<$v_central_dir['entries']; $i++) { + for ($i = 0; $i < $v_central_dir['entries']; ++$i) { // ----- Read the file header if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { $this->privSwapBackMagicQuotes(); + return $v_result; } $v_header['index'] = $i; @@ -3007,7 +3034,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privConvertHeader2FileInfo($p_header, &$p_info) { - $v_result=1; + $v_result = 1; // ----- Get the interesting attributes $v_temp_path = PclZipUtilPathReduction($p_header['filename']); @@ -3018,7 +3045,7 @@ class PclZip $p_info['compressed_size'] = $p_header['compressed_size']; $p_info['mtime'] = $p_header['mtime']; $p_info['comment'] = $p_header['comment']; - $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); + $p_info['folder'] = (($p_header['external'] & 0x00000010) == 0x00000010); $p_info['index'] = $p_header['index']; $p_info['status'] = $p_header['status']; $p_info['crc'] = $p_header['crc']; @@ -3046,26 +3073,26 @@ class PclZip // -------------------------------------------------------------------------------- public function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Check the path - if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 1, 2)!=":/"))) { - $p_path = "./".$p_path; + if (($p_path == '') || ((substr($p_path, 0, 1) != '/') && (substr($p_path, 0, 3) != '../') && (substr($p_path, 1, 2) != ':/'))) { + $p_path = './' . $p_path; } // ----- Reduce the path last (and duplicated) '/' - if (($p_path != "./") && ($p_path != "/")) { + if (($p_path != './') && ($p_path != '/')) { // ----- Look for the path end '/' - while (substr($p_path, -1) == "/") { - $p_path = substr($p_path, 0, strlen($p_path)-1); + while (substr($p_path, -1) == '/') { + $p_path = substr($p_path, 0, strlen($p_path) - 1); } } // ----- Look for path to remove format (should end by /) - if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { + if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/')) { $p_remove_path .= '/'; } $p_remove_path_size = strlen($p_remove_path); @@ -3073,11 +3100,12 @@ class PclZip // ----- Open the zip file if (($v_result = $this->privOpenFd('rb')) != 1) { $this->privSwapBackMagicQuotes(); + return $v_result; } // ----- Read the central directory informations - $v_central_dir = array(); + $v_central_dir = []; if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { // ----- Close the zip file $this->privCloseFd(); @@ -3091,7 +3119,7 @@ class PclZip // ----- Read each entry $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { + for ($i = 0, $v_nb_extracted = 0; $i < $v_central_dir['entries']; ++$i) { // ----- Read next Central dir entry @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_pos_entry)) { @@ -3100,14 +3128,14 @@ class PclZip $this->privSwapBackMagicQuotes(); // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + self::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read the file header - $v_header = array(); + $v_header = []; if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); @@ -3128,9 +3156,9 @@ class PclZip // ----- Look for extract by name rule if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_extract = true; @@ -3140,7 +3168,7 @@ class PclZip $v_extract = true; } } - } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != '')) { // ----- Look for extract by preg rule if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { $v_extract = true; @@ -3148,15 +3176,15 @@ class PclZip } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { // ----- Look for extract by index rule // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { - $v_extract = true; + for ($j = $j_start; ($j < sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); ++$j) { + if (($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i <= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_extract = true; } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; + if ($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j + 1; } - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start'] > $i) { break; } } @@ -3173,9 +3201,9 @@ class PclZip if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { $this->privSwapBackMagicQuotes(); - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '".$v_header['stored_filename']."' is compressed by an unsupported compression method (".$v_header['compression'].") "); + self::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '" . $v_header['stored_filename'] . "' is compressed by an unsupported compression method (" . $v_header['compression'] . ') '); - return PclZip::errorCode(); + return self::errorCode(); } } @@ -3186,9 +3214,9 @@ class PclZip if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { $this->privSwapBackMagicQuotes(); - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for filename '".$v_header['stored_filename']."'"); + self::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for filename '" . $v_header['stored_filename'] . "'"); - return PclZip::errorCode(); + return self::errorCode(); } } @@ -3198,6 +3226,7 @@ class PclZip if ($v_result != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); + return $v_result; } @@ -3215,10 +3244,10 @@ class PclZip $this->privSwapBackMagicQuotes(); // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + self::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Look for extraction as string @@ -3230,6 +3259,7 @@ class PclZip if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); + return $v_result1; } @@ -3246,7 +3276,7 @@ class PclZip $p_file_list[$v_nb_extracted]['content'] = $v_string; // ----- Next extracted file - $v_nb_extracted++; + ++$v_nb_extracted; // ----- Look for user callback abort if ($v_result1 == 2) { @@ -3259,6 +3289,7 @@ class PclZip if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); + return $v_result1; } @@ -3266,6 +3297,7 @@ class PclZip if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); + return $v_result; } @@ -3280,6 +3312,7 @@ class PclZip if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); + return $v_result1; } @@ -3320,7 +3353,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Read the file header if (($v_result = $this->privReadFileHeader($v_header)) != 1) { @@ -3328,7 +3361,6 @@ class PclZip return $v_result; } - // ----- Check that the file header is coherent with $p_entry info if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { // TBC @@ -3337,19 +3369,19 @@ class PclZip // ----- Look for all path to remove if ($p_remove_all_path == true) { // ----- Look for folder entry that not need to be extracted - if (($p_entry['external']&0x00000010)==0x00000010) { - $p_entry['status'] = "filtered"; + if (($p_entry['external'] & 0x00000010) == 0x00000010) { + $p_entry['status'] = 'filtered'; return $v_result; } // ----- Get the basename of the path $p_entry['filename'] = basename($p_entry['filename']); - } elseif ($p_remove_path != "") { + } elseif ($p_remove_path != '') { // ----- Look for path to remove if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) { // ----- Change the file status - $p_entry['status'] = "filtered"; + $p_entry['status'] = 'filtered'; // ----- Return return $v_result; @@ -3364,23 +3396,23 @@ class PclZip // ----- Add the path if ($p_path != '') { - $p_entry['filename'] = $p_path."/".$p_entry['filename']; + $p_entry['filename'] = $p_path . '/' . $p_entry['filename']; } // ----- Check a base_dir_restriction if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { $v_inclusion = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']); if ($v_inclusion == 0) { - PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '".$p_entry['filename']."' is outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + self::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '" . $p_entry['filename'] . "' is outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); - return PclZip::errorCode(); + return self::errorCode(); } } // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information - $v_local_header = array(); + $v_local_header = []; $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback @@ -3390,14 +3422,14 @@ class PclZip $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status - $p_entry['status'] = "skipped"; + $p_entry['status'] = 'skipped'; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; + $p_entry['status'] = 'aborted'; $v_result = PCLZIP_ERR_USER_ABORTED; } @@ -3413,57 +3445,60 @@ class PclZip // ----- Look if file is a directory if (is_dir($p_entry['filename'])) { // ----- Change the file status - $p_entry['status'] = "already_a_directory"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '".$p_entry['filename']."' is already used by an existing directory"); - return PclZip::errorCode(); - } - } elseif (!is_writeable($p_entry['filename'])) { - // ----- Look if file is write protected - // ----- Change the file status - $p_entry['status'] = "write_protected"; + $p_entry['status'] = 'already_a_directory'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '".$p_entry['filename']."' exists and is write protected"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '" . $p_entry['filename'] . "' is already used by an existing directory"); + + return self::errorCode(); + } + } elseif (!is_writeable($p_entry['filename'])) { + // ----- Look if file is write protected + // ----- Change the file status + $p_entry['status'] = 'write_protected'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { + self::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '" . $p_entry['filename'] . "' exists and is write protected"); + + return self::errorCode(); } } elseif (filemtime($p_entry['filename']) > $p_entry['mtime']) { // ----- Look if the extracted file is older // ----- Change the file status if ((isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) && ($p_options[PCLZIP_OPT_REPLACE_NEWER] === true)) { } else { - $p_entry['status'] = "newer_exist"; + $p_entry['status'] = 'newer_exist'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '".$p_entry['filename']."' exists and option PCLZIP_OPT_REPLACE_NEWER is not selected"); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '" . $p_entry['filename'] . "' exists and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + + return self::errorCode(); } } } else { } } else { // ----- Check the directory availability and create it if necessary - if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) { + if ((($p_entry['external'] & 0x00000010) == 0x00000010) || (substr($p_entry['filename'], -1) == '/')) { $v_dir_to_check = $p_entry['filename']; - } elseif (!strstr($p_entry['filename'], "/")) { - $v_dir_to_check = ""; + } elseif (!strstr($p_entry['filename'], '/')) { + $v_dir_to_check = ''; } else { $v_dir_to_check = dirname($p_entry['filename']); } - if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external'] & 0x00000010) == 0x00000010))) != 1) { // ----- Change the file status - $p_entry['status'] = "path_creation_fail"; + $p_entry['status'] = 'path_creation_fail'; // ----- Return //return $v_result; @@ -3475,13 +3510,13 @@ class PclZip // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010) == 0x00000010)) { + if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) { // ----- Look for not compressed file if ($p_entry['compression'] == 0) { // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { // ----- Change the file status - $p_entry['status'] = "write_error"; + $p_entry['status'] = 'write_error'; // ----- Return return $v_result; @@ -3509,8 +3544,9 @@ class PclZip // ----- TBC // Need to be finished if (($p_entry['flag'] & 1) == 1) { - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \'' . $p_entry['filename'] . '\' is encrypted. Encrypted files are not supported.'); + + return self::errorCode(); } // ----- Look for using temporary file to unzip @@ -3530,7 +3566,7 @@ class PclZip if ($v_file_content === false) { // ----- Change the file status // TBC - $p_entry['status'] = "error"; + $p_entry['status'] = 'error'; return $v_result; } @@ -3538,7 +3574,7 @@ class PclZip // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { // ----- Change the file status - $p_entry['status'] = "write_error"; + $p_entry['status'] = 'write_error'; return $v_result; } @@ -3564,12 +3600,12 @@ class PclZip } // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; + if ($p_entry['status'] == 'aborted') { + $p_entry['status'] = 'skipped'; } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Look for post-extract callback // ----- Generate a local information - $v_local_header = array(); + $v_local_header = []; $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback @@ -3580,7 +3616,7 @@ class PclZip // ----- Look for abort result if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; + $v_result = PCLZIP_ERR_USER_ABORTED; } } @@ -3597,14 +3633,15 @@ class PclZip // -------------------------------------------------------------------------------- public function privExtractFileUsingTempFile(&$p_entry, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Creates a temporary file - $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; - if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.gz'; + if (($v_dest_file = @fopen($v_gzip_temp_name, 'wb')) == 0) { fclose($v_file); - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); - return PclZip::errorCode(); + self::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary write mode'); + + return self::errorCode(); } // ----- Write gz file format header @@ -3630,16 +3667,18 @@ class PclZip // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - $p_entry['status'] = "write_error"; + $p_entry['status'] = 'write_error'; + return $v_result; } // ----- Open the temporary gz file if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { @fclose($v_dest_file); - $p_entry['status'] = "read_error"; - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); + $p_entry['status'] = 'read_error'; + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode'); + + return self::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks @@ -3670,7 +3709,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privExtractFileInOutput(&$p_entry, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Read the file header if (($v_result = $this->privReadFileHeader($v_header)) != 1) { @@ -3685,7 +3724,7 @@ class PclZip // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information - $v_local_header = array(); + $v_local_header = []; $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback @@ -3695,15 +3734,15 @@ class PclZip $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status - $p_entry['status'] = "skipped"; + $p_entry['status'] = 'skipped'; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; + $p_entry['status'] = 'aborted'; + $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations @@ -3716,7 +3755,7 @@ class PclZip // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { + if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) { // ----- Look for not compressed file if ($p_entry['compressed_size'] == $p_entry['size']) { // ----- Read the file in a buffer (one shot) @@ -3741,13 +3780,13 @@ class PclZip } // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; + if ($p_entry['status'] == 'aborted') { + $p_entry['status'] = 'skipped'; } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Look for post-extract callback // ----- Generate a local information - $v_local_header = array(); + $v_local_header = []; $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback @@ -3758,7 +3797,7 @@ class PclZip // ----- Look for abort result if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; + $v_result = PCLZIP_ERR_USER_ABORTED; } } @@ -3774,10 +3813,10 @@ class PclZip // -------------------------------------------------------------------------------- public function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) { - $v_result=1; + $v_result = 1; // ----- Read the file header - $v_header = array(); + $v_header = []; if (($v_result = $this->privReadFileHeader($v_header)) != 1) { // ----- Return return $v_result; @@ -3791,7 +3830,7 @@ class PclZip // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information - $v_local_header = array(); + $v_local_header = []; $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback @@ -3801,15 +3840,15 @@ class PclZip $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status - $p_entry['status'] = "skipped"; + $p_entry['status'] = 'skipped'; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; + $p_entry['status'] = 'aborted'; + $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations @@ -3820,7 +3859,7 @@ class PclZip // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { + if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) { // ----- Look for not compressed file // if ($p_entry['compressed_size'] == $p_entry['size']) if ($p_entry['compression'] == 0) { @@ -3837,17 +3876,17 @@ class PclZip } // ----- Trace } else { - // TBC : error : can not extract a folder in a string + // TBC : error : can not extract a folder in a string } } // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; + if ($p_entry['status'] == 'aborted') { + $p_entry['status'] = 'skipped'; } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Look for post-extract callback // ----- Generate a local information - $v_local_header = array(); + $v_local_header = []; $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Swap the content to header @@ -3866,7 +3905,7 @@ class PclZip // ----- Look for abort result if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; + $v_result = PCLZIP_ERR_USER_ABORTED; } } @@ -3883,7 +3922,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privReadFileHeader(&$p_header) { - $v_result=1; + $v_result = 1; // ----- Read the 4 bytes signature $v_binary_data = @fread($this->zip_fd, 4); @@ -3892,10 +3931,10 @@ class PclZip // ----- Check signature if ($v_data['id'] != 0x04034b50) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read the first 42 bytes of the header @@ -3903,14 +3942,14 @@ class PclZip // ----- Look for invalid block size if (strlen($v_binary_data) != 26) { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; + $p_header['filename'] = ''; + $p_header['status'] = 'invalid_header'; // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid block size : ' . strlen($v_binary_data)); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Extract the values @@ -3942,7 +3981,7 @@ class PclZip // ----- Extract time $v_hour = ($p_header['mtime'] & 0xF800) >> 11; $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; + $v_seconde = ($p_header['mtime'] & 0x001F) * 2; // ----- Extract date $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; @@ -3963,7 +4002,7 @@ class PclZip $p_header['stored_filename'] = $p_header['filename']; // ----- Set the status field - $p_header['status'] = "ok"; + $p_header['status'] = 'ok'; // ----- Return return $v_result; @@ -3987,10 +4026,10 @@ class PclZip // ----- Check signature if ($v_data['id'] != 0x02014b50) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read the first 42 bytes of the header @@ -3998,14 +4037,14 @@ class PclZip // ----- Look for invalid block size if (strlen($v_binary_data) != 42) { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; + $p_header['filename'] = ''; + $p_header['status'] = 'invalid_header'; // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid block size : ' . strlen($v_binary_data)); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Extract the values @@ -4041,7 +4080,7 @@ class PclZip // ----- Extract time $v_hour = ($p_header['mtime'] & 0xF800) >> 11; $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; + $v_seconde = ($p_header['mtime'] & 0x001F) * 2; // ----- Extract date $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; @@ -4066,7 +4105,6 @@ class PclZip $p_header['external'] = 0x00000010; } - // ----- Return return $v_result; } @@ -4082,7 +4120,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privCheckFileHeaders(&$p_local_header, &$p_central_header) { - $v_result=1; + $v_result = 1; // ----- Check the static values // TBC @@ -4119,30 +4157,30 @@ class PclZip // -------------------------------------------------------------------------------- public function privReadEndCentralDir(&$p_central_dir) { - $v_result=1; + $v_result = 1; // ----- Go to the end of the zip file $v_size = filesize($this->zipname); @fseek($this->zip_fd, $v_size); if (@ftell($this->zip_fd) != $v_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \'' . $this->zipname . '\''); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- First try : look if this is an archive with no commentaries (most of the time) // in this case the end of central dir is at 22 bytes of the file end $v_found = 0; if ($v_size > 26) { - @fseek($this->zip_fd, $v_size-22); - if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) { + @fseek($this->zip_fd, $v_size - 22); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size - 22)) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \'' . $this->zipname . '\''); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read for bytes @@ -4163,13 +4201,13 @@ class PclZip if ($v_maximum_size > $v_size) { $v_maximum_size = $v_size; } - @fseek($this->zip_fd, $v_size-$v_maximum_size); - if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) { + @fseek($this->zip_fd, $v_size - $v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size - $v_maximum_size)) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \'' . $this->zipname . '\''); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read byte per byte in order to find the signature @@ -4187,20 +4225,20 @@ class PclZip // ----- Compare the bytes if ($v_bytes == 0x504b0506) { - $v_pos++; + ++$v_pos; break; } - $v_pos++; + ++$v_pos; } // ----- Look if not found end of central dir if ($v_pos == $v_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to find End of Central Dir Record signature'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } } @@ -4210,10 +4248,10 @@ class PclZip // ----- Look for invalid block size if (strlen($v_binary_data) != 18) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid End of Central Dir Record size : ' . strlen($v_binary_data)); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Extract the values @@ -4227,10 +4265,10 @@ class PclZip // While decrypted, zip has training 0 bytes if (0) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive. Some trailing bytes exists after the archive.'); + self::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive. Some trailing bytes exists after the archive.'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } } @@ -4265,19 +4303,20 @@ class PclZip // -------------------------------------------------------------------------------- public function privDeleteByRule(&$p_result_list, &$p_options) { - $v_result=1; - $v_list_detail = array(); + $v_result = 1; + $v_list_detail = []; // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) { + if (($v_result = $this->privOpenFd('rb')) != 1) { // ----- Return return $v_result; } // ----- Read the central directory informations - $v_central_dir = array(); + $v_central_dir = []; if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); + return $v_result; } @@ -4293,18 +4332,18 @@ class PclZip $this->privCloseFd(); // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + self::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read each entry - $v_header_list = array(); + $v_header_list = []; $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { + for ($i = 0, $v_nb_extracted = 0; $i < $v_central_dir['entries']; ++$i) { // ----- Read the file header - $v_header_list[$v_nb_extracted] = array(); + $v_header_list[$v_nb_extracted] = []; if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) { // ----- Close the zip file $this->privCloseFd(); @@ -4312,7 +4351,6 @@ class PclZip return $v_result; } - // ----- Store the index $v_header_list[$v_nb_extracted]['index'] = $i; @@ -4322,13 +4360,13 @@ class PclZip // ----- Look for extract by name rule if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_found = true; - } elseif ((($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + } elseif ((($v_header_list[$v_nb_extracted]['external'] & 0x00000010) == 0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'] . '/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_found = true; } } elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { @@ -4336,22 +4374,22 @@ class PclZip $v_found = true; } } - } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != '')) { // ----- Look for extract by preg rule if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; + $v_found = true; } } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { // ----- Look for extract by index rule // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + for ($j = $j_start; ($j < sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); ++$j) { + if (($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i <= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { $v_found = true; } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; + if ($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j + 1; } - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start'] > $i) { break; } } @@ -4363,17 +4401,17 @@ class PclZip if ($v_found) { unset($v_header_list[$v_nb_extracted]); } else { - $v_nb_extracted++; + ++$v_nb_extracted; } } // ----- Look if something need to be deleted if ($v_nb_extracted > 0) { // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp'; // ----- Creates a temporary zip archive - $v_temp_zip = new PclZip($v_zip_temp_name); + $v_temp_zip = new self($v_zip_temp_name); // ----- Open the temporary zip file in write mode if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { @@ -4384,7 +4422,7 @@ class PclZip } // ----- Look which file need to be kept - for ($i=0; $izip_fd); if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { @@ -4394,14 +4432,14 @@ class PclZip @unlink($v_zip_temp_name); // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + self::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Read the file header - $v_local_header = array(); + $v_local_header = []; if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); @@ -4445,7 +4483,7 @@ class PclZip $v_offset = @ftell($v_temp_zip->zip_fd); // ----- Re-Create the Central Dir files header - for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { $v_temp_zip->privCloseFd(); @@ -4460,7 +4498,6 @@ class PclZip $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } - // ----- Zip file comment $v_comment = ''; if (isset($p_options[PCLZIP_OPT_COMMENT])) { @@ -4468,15 +4505,15 @@ class PclZip } // ----- Calculate the size of the central header - $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; + $v_size = @ftell($v_temp_zip->zip_fd) - $v_offset; // ----- Create the central dir footer if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { - // ----- Reset the file list + // ----- Reset the file list unset($v_header_list); - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - @unlink($v_zip_temp_name); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); // ----- Return return $v_result; @@ -4533,12 +4570,12 @@ class PclZip $v_result = 1; // ----- Remove the final '/' - if (($p_is_dir) && (substr($p_dir, -1)=='/')) { - $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + if (($p_is_dir) && (substr($p_dir, -1) == '/')) { + $p_dir = substr($p_dir, 0, strlen($p_dir) - 1); } // ----- Check the directory availability - if ((is_dir($p_dir)) || ($p_dir == "")) { + if ((is_dir($p_dir)) || ($p_dir == '')) { return 1; } @@ -4548,7 +4585,7 @@ class PclZip // ----- Just a check if ($p_parent_dir != $p_dir) { // ----- Look for parent directory - if ($p_parent_dir != "") { + if ($p_parent_dir != '') { if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) { return $v_result; } @@ -4558,10 +4595,10 @@ class PclZip // ----- Create the directory if (!@mkdir($p_dir, 0777)) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + self::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Return @@ -4578,7 +4615,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privMerge(&$p_archive_to_add) { - $v_result=1; + $v_result = 1; // ----- Look if the archive_to_add exists if (!is_file($p_archive_to_add->zipname)) { @@ -4599,15 +4636,16 @@ class PclZip } // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) { + if (($v_result = $this->privOpenFd('rb')) != 1) { // ----- Return return $v_result; } // ----- Read the central directory informations - $v_central_dir = array(); + $v_central_dir = []; if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); + return $v_result; } @@ -4615,7 +4653,7 @@ class PclZip @rewind($this->zip_fd); // ----- Open the archive_to_add file - if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) { + if (($v_result = $p_archive_to_add->privOpenFd('rb')) != 1) { $this->privCloseFd(); // ----- Return @@ -4623,7 +4661,7 @@ class PclZip } // ----- Read the central directory informations - $v_central_dir_to_add = array(); + $v_central_dir_to_add = []; if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); @@ -4635,17 +4673,17 @@ class PclZip @rewind($p_archive_to_add->zip_fd); // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp'; // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary write mode'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Copy the files from the archive to the temporary file @@ -4689,10 +4727,10 @@ class PclZip } // ----- Merge the file comments - $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + $v_comment = $v_central_dir['comment'] . ' ' . $v_central_dir_to_add['comment']; // ----- Calculate the size of the (new) central header - $v_size = @ftell($v_zip_temp_fd)-$v_offset; + $v_size = @ftell($v_zip_temp_fd) - $v_offset; // ----- Swap the file descriptor // Here is a trick : I swap the temporary fd with the zip fd, in order to use @@ -4702,7 +4740,7 @@ class PclZip $v_zip_temp_fd = $v_swap; // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) { + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries'] + $v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); @fclose($v_zip_temp_fd); @@ -4749,7 +4787,7 @@ class PclZip // -------------------------------------------------------------------------------- public function privDuplicate($p_archive_filename) { - $v_result=1; + $v_result = 1; // ----- Look if the $p_archive_filename exists if (!is_file($p_archive_filename)) { @@ -4761,7 +4799,7 @@ class PclZip } // ----- Open the zip file - if (($v_result=$this->privOpenFd('wb')) != 1) { + if (($v_result = $this->privOpenFd('wb')) != 1) { // ----- Return return $v_result; } @@ -4770,10 +4808,10 @@ class PclZip if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { $this->privCloseFd(); - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + self::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \'' . $p_archive_filename . '\' in binary write mode'); // ----- Return - return PclZip::errorCode(); + return self::errorCode(); } // ----- Copy the files from the archive to the temporary file @@ -4837,10 +4875,10 @@ class PclZip // -------------------------------------------------------------------------------- public function privDisableMagicQuotes() { - $v_result=1; + $v_result = 1; // ----- Look if function exists - if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { + if ((!function_exists('get_magic_quotes_runtime')) || (!function_exists('set_magic_quotes_runtime'))) { return $v_result; } @@ -4870,10 +4908,10 @@ class PclZip // -------------------------------------------------------------------------------- public function privSwapBackMagicQuotes() { - $v_result=1; + $v_result = 1; // ----- Look if function exists - if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { + if ((!function_exists('get_magic_quotes_runtime')) || (!function_exists('set_magic_quotes_runtime'))) { return $v_result; } @@ -4903,33 +4941,33 @@ class PclZip // -------------------------------------------------------------------------------- function PclZipUtilPathReduction($p_dir) { - $v_result = ""; + $v_result = ''; // ----- Look for not empty path - if ($p_dir != "") { + if ($p_dir != '') { // ----- Explode path by directory names - $v_list = explode("/", $p_dir); + $v_list = explode('/', $p_dir); // ----- Study directories from last to first $v_skip = 0; - for ($i=sizeof($v_list)-1; $i>=0; $i--) { + for ($i = sizeof($v_list) - 1; $i >= 0; --$i) { // ----- Look for current path - if ($v_list[$i] == ".") { + if ($v_list[$i] == '.') { // ----- Ignore this directory // Should be the first $i=0, but no check is done - } elseif ($v_list[$i] == "..") { - $v_skip++; - } elseif ($v_list[$i] == "") { + } elseif ($v_list[$i] == '..') { + ++$v_skip; + } elseif ($v_list[$i] == '') { // ----- First '/' i.e. root slash if ($i == 0) { - $v_result = "/".$v_result; + $v_result = '/' . $v_result; if ($v_skip > 0) { // ----- It is an invalid path, so the path is not modified // TBC $v_result = $p_dir; $v_skip = 0; } - } elseif ($i == (sizeof($v_list)-1)) { + } elseif ($i == (sizeof($v_list) - 1)) { // ----- Last '/' i.e. indicates a directory $v_result = $v_list[$i]; } else { @@ -4940,9 +4978,9 @@ function PclZipUtilPathReduction($p_dir) } else { // ----- Look for item to skip if ($v_skip > 0) { - $v_skip--; + --$v_skip; } else { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + $v_result = $v_list[$i] . ($i != (sizeof($v_list) - 1)?'/' . $v_result:''); } } } @@ -4950,8 +4988,8 @@ function PclZipUtilPathReduction($p_dir) // ----- Look for skip if ($v_skip > 0) { while ($v_skip > 0) { - $v_result = '../'.$v_result; - $v_skip--; + $v_result = '../' . $v_result; + --$v_skip; } } } @@ -4981,17 +5019,17 @@ function PclZipUtilPathInclusion($p_dir, $p_path) $v_result = 1; // ----- Look for path beginning by ./ - if (($p_dir == '.') || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { - $p_dir = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_dir, 1); + if (($p_dir == '.') || ((strlen($p_dir) >= 2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), false) . '/' . substr($p_dir, 1); } - if (($p_path == '.') || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { - $p_path = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_path, 1); + if (($p_path == '.') || ((strlen($p_path) >= 2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), false) . '/' . substr($p_path, 1); } // ----- Explode dir and path by directory separator - $v_list_dir = explode("/", $p_dir); + $v_list_dir = explode('/', $p_dir); $v_list_dir_size = sizeof($v_list_dir); - $v_list_path = explode("/", $p_path); + $v_list_path = explode('/', $p_path); $v_list_path_size = sizeof($v_list_path); // ----- Study directories paths @@ -5000,11 +5038,11 @@ function PclZipUtilPathInclusion($p_dir, $p_path) while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { // ----- Look for empty dir (path reduction) if ($v_list_dir[$i] == '') { - $i++; + ++$i; continue; } if ($v_list_path[$j] == '') { - $j++; + ++$j; continue; } @@ -5014,18 +5052,18 @@ function PclZipUtilPathInclusion($p_dir, $p_path) } // ----- Next items - $i++; - $j++; + ++$i; + ++$j; } // ----- Look if everything seems to be the same if ($v_result) { // ----- Skip all the empty items while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) { - $j++; + ++$j; } while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) { - $i++; + ++$i; } if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { @@ -5057,28 +5095,28 @@ function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode = 0) { $v_result = 1; - if ($p_mode==0) { + if ($p_mode == 0) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_src, $v_read_size); @fwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } - } elseif ($p_mode==1) { + } elseif ($p_mode == 1) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($p_src, $v_read_size); @fwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } - } elseif ($p_mode==2) { + } elseif ($p_mode == 2) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_src, $v_read_size); @gzwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } - } elseif ($p_mode==3) { + } elseif ($p_mode == 3) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($p_src, $v_read_size); @@ -5164,12 +5202,13 @@ function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter = true) if (stristr(php_uname(), 'windows')) { // ----- Look for potential disk letter if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); + $p_path = substr($p_path, $v_position + 1); } // ----- Change potential windows directory separator if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0, 1) == '\\')) { $p_path = strtr($p_path, '\\', '/'); } } + return $p_path; } diff --git a/src/PhpSpreadsheet/Shared/PasswordHasher.php b/src/PhpSpreadsheet/Shared/PasswordHasher.php index 8ca36333..fc75548b 100644 --- a/src/PhpSpreadsheet/Shared/PasswordHasher.php +++ b/src/PhpSpreadsheet/Shared/PasswordHasher.php @@ -40,21 +40,21 @@ class PasswordHasher */ public static function hashPassword($pPassword = '') { - $password = 0x0000; - $charPos = 1; // char position + $password = 0x0000; + $charPos = 1; // char position // split the plain text password in its component characters $chars = preg_split('//', $pPassword, -1, PREG_SPLIT_NO_EMPTY); foreach ($chars as $char) { - $value = ord($char) << $charPos++; // shifted ASCII value - $rotated_bits = $value >> 15; // rotated bits beyond bit 15 - $value &= 0x7fff; // first 15 bits - $password ^= ($value | $rotated_bits); + $value = ord($char) << $charPos++; // shifted ASCII value + $rotated_bits = $value >> 15; // rotated bits beyond bit 15 + $value &= 0x7fff; // first 15 bits + $password ^= ($value | $rotated_bits); } $password ^= strlen($pPassword); $password ^= 0xCE4B; - return(strtoupper(dechex($password))); + return strtoupper(dechex($password)); } } diff --git a/src/PhpSpreadsheet/Shared/StringHelper.php b/src/PhpSpreadsheet/Shared/StringHelper.php index 18f91488..403fdffe 100644 --- a/src/PhpSpreadsheet/Shared/StringHelper.php +++ b/src/PhpSpreadsheet/Shared/StringHelper.php @@ -29,24 +29,23 @@ namespace PhpSpreadsheet\Shared; class StringHelper { /** Constants */ - /** Regular Expressions */ +/** Regular Expressions */ // Fraction - const STRING_REGEXP_FRACTION = '(-?)(\d+)\s+(\d+\/\d+)'; - + const STRING_REGEXP_FRACTION = '(-?)(\d+)\s+(\d+\/\d+)'; /** * Control characters array * * @var string[] */ - private static $controlCharacters = array(); + private static $controlCharacters = []; /** * SYLK Characters array * * $var array */ - private static $SYLKCharacters = array(); + private static $SYLKCharacters = []; /** * Decimal separator @@ -72,14 +71,14 @@ class StringHelper /** * Is mbstring extension avalable? * - * @var boolean + * @var bool */ private static $isMbstringEnabled; /** * Is iconv extension avalable? * - * @var boolean + * @var bool */ private static $isIconvEnabled; @@ -102,106 +101,106 @@ class StringHelper */ private static function buildSYLKCharacters() { - self::$SYLKCharacters = array( - "\x1B 0" => chr(0), - "\x1B 1" => chr(1), - "\x1B 2" => chr(2), - "\x1B 3" => chr(3), - "\x1B 4" => chr(4), - "\x1B 5" => chr(5), - "\x1B 6" => chr(6), - "\x1B 7" => chr(7), - "\x1B 8" => chr(8), - "\x1B 9" => chr(9), - "\x1B :" => chr(10), - "\x1B ;" => chr(11), - "\x1B <" => chr(12), - "\x1B :" => chr(13), - "\x1B >" => chr(14), - "\x1B ?" => chr(15), - "\x1B!0" => chr(16), - "\x1B!1" => chr(17), - "\x1B!2" => chr(18), - "\x1B!3" => chr(19), - "\x1B!4" => chr(20), - "\x1B!5" => chr(21), - "\x1B!6" => chr(22), - "\x1B!7" => chr(23), - "\x1B!8" => chr(24), - "\x1B!9" => chr(25), - "\x1B!:" => chr(26), - "\x1B!;" => chr(27), - "\x1B!<" => chr(28), - "\x1B!=" => chr(29), - "\x1B!>" => chr(30), - "\x1B!?" => chr(31), - "\x1B'?" => chr(127), - "\x1B(0" => '€', // 128 in CP1252 - "\x1B(2" => '‚', // 130 in CP1252 - "\x1B(3" => 'ƒ', // 131 in CP1252 - "\x1B(4" => '„', // 132 in CP1252 - "\x1B(5" => '…', // 133 in CP1252 - "\x1B(6" => '†', // 134 in CP1252 - "\x1B(7" => '‡', // 135 in CP1252 - "\x1B(8" => 'ˆ', // 136 in CP1252 - "\x1B(9" => '‰', // 137 in CP1252 - "\x1B(:" => 'Š', // 138 in CP1252 - "\x1B(;" => '‹', // 139 in CP1252 - "\x1BNj" => 'Œ', // 140 in CP1252 - "\x1B(>" => 'Ž', // 142 in CP1252 - "\x1B)1" => '‘', // 145 in CP1252 - "\x1B)2" => '’', // 146 in CP1252 - "\x1B)3" => '“', // 147 in CP1252 - "\x1B)4" => '”', // 148 in CP1252 - "\x1B)5" => '•', // 149 in CP1252 - "\x1B)6" => '–', // 150 in CP1252 - "\x1B)7" => '—', // 151 in CP1252 - "\x1B)8" => '˜', // 152 in CP1252 - "\x1B)9" => '™', // 153 in CP1252 - "\x1B):" => 'š', // 154 in CP1252 - "\x1B);" => '›', // 155 in CP1252 - "\x1BNz" => 'œ', // 156 in CP1252 - "\x1B)>" => 'ž', // 158 in CP1252 - "\x1B)?" => 'Ÿ', // 159 in CP1252 - "\x1B*0" => ' ', // 160 in CP1252 - "\x1BN!" => '¡', // 161 in CP1252 + self::$SYLKCharacters = [ + "\x1B 0" => chr(0), + "\x1B 1" => chr(1), + "\x1B 2" => chr(2), + "\x1B 3" => chr(3), + "\x1B 4" => chr(4), + "\x1B 5" => chr(5), + "\x1B 6" => chr(6), + "\x1B 7" => chr(7), + "\x1B 8" => chr(8), + "\x1B 9" => chr(9), + "\x1B :" => chr(10), + "\x1B ;" => chr(11), + "\x1B <" => chr(12), + "\x1B :" => chr(13), + "\x1B >" => chr(14), + "\x1B ?" => chr(15), + "\x1B!0" => chr(16), + "\x1B!1" => chr(17), + "\x1B!2" => chr(18), + "\x1B!3" => chr(19), + "\x1B!4" => chr(20), + "\x1B!5" => chr(21), + "\x1B!6" => chr(22), + "\x1B!7" => chr(23), + "\x1B!8" => chr(24), + "\x1B!9" => chr(25), + "\x1B!:" => chr(26), + "\x1B!;" => chr(27), + "\x1B!<" => chr(28), + "\x1B!=" => chr(29), + "\x1B!>" => chr(30), + "\x1B!?" => chr(31), + "\x1B'?" => chr(127), + "\x1B(0" => '€', // 128 in CP1252 + "\x1B(2" => '‚', // 130 in CP1252 + "\x1B(3" => 'ƒ', // 131 in CP1252 + "\x1B(4" => '„', // 132 in CP1252 + "\x1B(5" => '…', // 133 in CP1252 + "\x1B(6" => '†', // 134 in CP1252 + "\x1B(7" => '‡', // 135 in CP1252 + "\x1B(8" => 'ˆ', // 136 in CP1252 + "\x1B(9" => '‰', // 137 in CP1252 + "\x1B(:" => 'Š', // 138 in CP1252 + "\x1B(;" => '‹', // 139 in CP1252 + "\x1BNj" => 'Œ', // 140 in CP1252 + "\x1B(>" => 'Ž', // 142 in CP1252 + "\x1B)1" => '‘', // 145 in CP1252 + "\x1B)2" => '’', // 146 in CP1252 + "\x1B)3" => '“', // 147 in CP1252 + "\x1B)4" => '”', // 148 in CP1252 + "\x1B)5" => '•', // 149 in CP1252 + "\x1B)6" => '–', // 150 in CP1252 + "\x1B)7" => '—', // 151 in CP1252 + "\x1B)8" => '˜', // 152 in CP1252 + "\x1B)9" => '™', // 153 in CP1252 + "\x1B):" => 'š', // 154 in CP1252 + "\x1B);" => '›', // 155 in CP1252 + "\x1BNz" => 'œ', // 156 in CP1252 + "\x1B)>" => 'ž', // 158 in CP1252 + "\x1B)?" => 'Ÿ', // 159 in CP1252 + "\x1B*0" => ' ', // 160 in CP1252 + "\x1BN!" => '¡', // 161 in CP1252 "\x1BN\"" => '¢', // 162 in CP1252 - "\x1BN#" => '£', // 163 in CP1252 - "\x1BN(" => '¤', // 164 in CP1252 - "\x1BN%" => '¥', // 165 in CP1252 - "\x1B*6" => '¦', // 166 in CP1252 - "\x1BN'" => '§', // 167 in CP1252 + "\x1BN#" => '£', // 163 in CP1252 + "\x1BN(" => '¤', // 164 in CP1252 + "\x1BN%" => '¥', // 165 in CP1252 + "\x1B*6" => '¦', // 166 in CP1252 + "\x1BN'" => '§', // 167 in CP1252 "\x1BNH " => '¨', // 168 in CP1252 - "\x1BNS" => '©', // 169 in CP1252 - "\x1BNc" => 'ª', // 170 in CP1252 - "\x1BN+" => '«', // 171 in CP1252 - "\x1B*<" => '¬', // 172 in CP1252 - "\x1B*=" => '­', // 173 in CP1252 - "\x1BNR" => '®', // 174 in CP1252 - "\x1B*?" => '¯', // 175 in CP1252 - "\x1BN0" => '°', // 176 in CP1252 - "\x1BN1" => '±', // 177 in CP1252 - "\x1BN2" => '²', // 178 in CP1252 - "\x1BN3" => '³', // 179 in CP1252 + "\x1BNS" => '©', // 169 in CP1252 + "\x1BNc" => 'ª', // 170 in CP1252 + "\x1BN+" => '«', // 171 in CP1252 + "\x1B*<" => '¬', // 172 in CP1252 + "\x1B*=" => '­', // 173 in CP1252 + "\x1BNR" => '®', // 174 in CP1252 + "\x1B*?" => '¯', // 175 in CP1252 + "\x1BN0" => '°', // 176 in CP1252 + "\x1BN1" => '±', // 177 in CP1252 + "\x1BN2" => '²', // 178 in CP1252 + "\x1BN3" => '³', // 179 in CP1252 "\x1BNB " => '´', // 180 in CP1252 - "\x1BN5" => 'µ', // 181 in CP1252 - "\x1BN6" => '¶', // 182 in CP1252 - "\x1BN7" => '·', // 183 in CP1252 - "\x1B+8" => '¸', // 184 in CP1252 - "\x1BNQ" => '¹', // 185 in CP1252 - "\x1BNk" => 'º', // 186 in CP1252 - "\x1BN;" => '»', // 187 in CP1252 - "\x1BN<" => '¼', // 188 in CP1252 - "\x1BN=" => '½', // 189 in CP1252 - "\x1BN>" => '¾', // 190 in CP1252 - "\x1BN?" => '¿', // 191 in CP1252 + "\x1BN5" => 'µ', // 181 in CP1252 + "\x1BN6" => '¶', // 182 in CP1252 + "\x1BN7" => '·', // 183 in CP1252 + "\x1B+8" => '¸', // 184 in CP1252 + "\x1BNQ" => '¹', // 185 in CP1252 + "\x1BNk" => 'º', // 186 in CP1252 + "\x1BN;" => '»', // 187 in CP1252 + "\x1BN<" => '¼', // 188 in CP1252 + "\x1BN=" => '½', // 189 in CP1252 + "\x1BN>" => '¾', // 190 in CP1252 + "\x1BN?" => '¿', // 191 in CP1252 "\x1BNAA" => 'À', // 192 in CP1252 "\x1BNBA" => 'Á', // 193 in CP1252 "\x1BNCA" => 'Â', // 194 in CP1252 "\x1BNDA" => 'Ã', // 195 in CP1252 "\x1BNHA" => 'Ä', // 196 in CP1252 "\x1BNJA" => 'Å', // 197 in CP1252 - "\x1BNa" => 'Æ', // 198 in CP1252 + "\x1BNa" => 'Æ', // 198 in CP1252 "\x1BNKC" => 'Ç', // 199 in CP1252 "\x1BNAE" => 'È', // 200 in CP1252 "\x1BNBE" => 'É', // 201 in CP1252 @@ -211,29 +210,29 @@ class StringHelper "\x1BNBI" => 'Í', // 205 in CP1252 "\x1BNCI" => 'Î', // 206 in CP1252 "\x1BNHI" => 'Ï', // 207 in CP1252 - "\x1BNb" => 'Ð', // 208 in CP1252 + "\x1BNb" => 'Ð', // 208 in CP1252 "\x1BNDN" => 'Ñ', // 209 in CP1252 "\x1BNAO" => 'Ò', // 210 in CP1252 "\x1BNBO" => 'Ó', // 211 in CP1252 "\x1BNCO" => 'Ô', // 212 in CP1252 "\x1BNDO" => 'Õ', // 213 in CP1252 "\x1BNHO" => 'Ö', // 214 in CP1252 - "\x1B-7" => '×', // 215 in CP1252 - "\x1BNi" => 'Ø', // 216 in CP1252 + "\x1B-7" => '×', // 215 in CP1252 + "\x1BNi" => 'Ø', // 216 in CP1252 "\x1BNAU" => 'Ù', // 217 in CP1252 "\x1BNBU" => 'Ú', // 218 in CP1252 "\x1BNCU" => 'Û', // 219 in CP1252 "\x1BNHU" => 'Ü', // 220 in CP1252 - "\x1B-=" => 'Ý', // 221 in CP1252 - "\x1BNl" => 'Þ', // 222 in CP1252 - "\x1BN{" => 'ß', // 223 in CP1252 + "\x1B-=" => 'Ý', // 221 in CP1252 + "\x1BNl" => 'Þ', // 222 in CP1252 + "\x1BN{" => 'ß', // 223 in CP1252 "\x1BNAa" => 'à', // 224 in CP1252 "\x1BNBa" => 'á', // 225 in CP1252 "\x1BNCa" => 'â', // 226 in CP1252 "\x1BNDa" => 'ã', // 227 in CP1252 "\x1BNHa" => 'ä', // 228 in CP1252 "\x1BNJa" => 'å', // 229 in CP1252 - "\x1BNq" => 'æ', // 230 in CP1252 + "\x1BNq" => 'æ', // 230 in CP1252 "\x1BNKc" => 'ç', // 231 in CP1252 "\x1BNAe" => 'è', // 232 in CP1252 "\x1BNBe" => 'é', // 233 in CP1252 @@ -243,29 +242,29 @@ class StringHelper "\x1BNBi" => 'í', // 237 in CP1252 "\x1BNCi" => 'î', // 238 in CP1252 "\x1BNHi" => 'ï', // 239 in CP1252 - "\x1BNs" => 'ð', // 240 in CP1252 + "\x1BNs" => 'ð', // 240 in CP1252 "\x1BNDn" => 'ñ', // 241 in CP1252 "\x1BNAo" => 'ò', // 242 in CP1252 "\x1BNBo" => 'ó', // 243 in CP1252 "\x1BNCo" => 'ô', // 244 in CP1252 "\x1BNDo" => 'õ', // 245 in CP1252 "\x1BNHo" => 'ö', // 246 in CP1252 - "\x1B/7" => '÷', // 247 in CP1252 - "\x1BNy" => 'ø', // 248 in CP1252 + "\x1B/7" => '÷', // 247 in CP1252 + "\x1BNy" => 'ø', // 248 in CP1252 "\x1BNAu" => 'ù', // 249 in CP1252 "\x1BNBu" => 'ú', // 250 in CP1252 "\x1BNCu" => 'û', // 251 in CP1252 "\x1BNHu" => 'ü', // 252 in CP1252 - "\x1B/=" => 'ý', // 253 in CP1252 - "\x1BN|" => 'þ', // 254 in CP1252 + "\x1B/=" => 'ý', // 253 in CP1252 + "\x1BN|" => 'þ', // 254 in CP1252 "\x1BNHy" => 'ÿ', // 255 in CP1252 - ); + ]; } /** * Get whether mbstring extension is available * - * @return boolean + * @return bool */ public static function getIsMbstringEnabled() { @@ -282,7 +281,7 @@ class StringHelper /** * Get whether iconv extension is available * - * @return boolean + * @return bool */ public static function getIsIconvEnabled() { @@ -293,12 +292,14 @@ class StringHelper // Fail if iconv doesn't exist if (!function_exists('iconv')) { self::$isIconvEnabled = false; + return false; } // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false, if (!@iconv('UTF-8', 'UTF-16LE', 'x')) { self::$isIconvEnabled = false; + return false; } @@ -306,17 +307,20 @@ class StringHelper // we cannot use iconv in that case either (http://bugs.php.net/bug.php?id=37773) if (!@iconv_substr('A', 0, 1, 'UTF-8')) { self::$isIconvEnabled = false; + return false; } // CUSTOM: IBM AIX iconv() does not work if (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) { self::$isIconvEnabled = false; + return false; } // If we reach here no problems were detected with iconv self::$isIconvEnabled = true; + return true; } @@ -378,11 +382,13 @@ class StringHelper { if (self::getIsIconvEnabled()) { $value = @iconv('UTF-8', 'UTF-8', $value); + return $value; } if (self::getIsMbstringEnabled()) { $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); + return $value; } @@ -394,7 +400,7 @@ class StringHelper * Check if a string contains UTF8 data * * @param string $value - * @return boolean + * @return bool */ public static function isUTF8($value = '') { @@ -413,6 +419,7 @@ class StringHelper if (is_float($value)) { return str_replace(',', '.', $value); } + return (string) $value; } @@ -427,7 +434,7 @@ class StringHelper * @param mixed[] $arrcRuns Details of rich text runs in $value * @return string */ - public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = array()) + public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = []) { // character count $ln = self::countCharacters($value, 'UTF-8'); @@ -448,6 +455,7 @@ class StringHelper $data .= pack('v', $cRun['fontidx']); } } + return $data; } @@ -474,6 +482,7 @@ class StringHelper $chars = self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); $data = pack('vC', $ln, $opt) . $chars; + return $data; } @@ -514,7 +523,6 @@ class StringHelper * * @param string $str UTF-16 encoded data to decode. * @return string UTF-8 / ISO encoded data. - * @access public * @version 0.2 / 2010-05-13 * @author Rasmus Andersson {@link http://rasmusandersson.se/} * @author vadik56 @@ -534,16 +542,17 @@ class StringHelper } $len = strlen($str); $newstr = ''; - for ($i=0; $i<$len; $i+=2) { + for ($i = 0; $i < $len; $i += 2) { if ($bom_be) { - $val = ord($str{$i}) << 4; - $val += ord($str{$i+1}); + $val = ord($str{$i}) << 4; + $val += ord($str{$i + 1}); } else { - $val = ord($str{$i+1}) << 4; + $val = ord($str{$i + 1}) << 4; $val += ord($str{$i}); } $newstr .= ($val == 0x228) ? "\n" : chr($val); } + return $newstr; } @@ -599,8 +608,9 @@ class StringHelper public static function strToUpper($pValue = '') { if (function_exists('mb_convert_case')) { - return mb_convert_case($pValue, MB_CASE_UPPER, "UTF-8"); + return mb_convert_case($pValue, MB_CASE_UPPER, 'UTF-8'); } + return strtoupper($pValue); } @@ -613,8 +623,9 @@ class StringHelper public static function strToLower($pValue = '') { if (function_exists('mb_convert_case')) { - return mb_convert_case($pValue, MB_CASE_LOWER, "UTF-8"); + return mb_convert_case($pValue, MB_CASE_LOWER, 'UTF-8'); } + return strtolower($pValue); } @@ -628,14 +639,15 @@ class StringHelper public static function strToTitle($pValue = '') { if (function_exists('mb_convert_case')) { - return mb_convert_case($pValue, MB_CASE_TITLE, "UTF-8"); + return mb_convert_case($pValue, MB_CASE_TITLE, 'UTF-8'); } + return ucwords($pValue); } public static function mbIsUpper($char) { - return mb_strtolower($char, "UTF-8") != $char; + return mb_strtolower($char, 'UTF-8') != $char; } public static function mbStrSplit($string) @@ -663,8 +675,10 @@ class StringHelper $character = mb_strtoupper($character, 'UTF-8'); } } + return implode('', $characters); } + return strtolower($pValue) ^ strtoupper($pValue) ^ $pValue; } @@ -673,16 +687,18 @@ class StringHelper * and convert it to a numeric if it is * * @param string &$operand string value to test - * @return boolean + * @return bool */ public static function convertToNumberIfFraction(&$operand) { - if (preg_match('/^'.self::STRING_REGEXP_FRACTION.'$/i', $operand, $match)) { + if (preg_match('/^' . self::STRING_REGEXP_FRACTION . '$/i', $operand, $match)) { $sign = ($match[1] == '-') ? '-' : '+'; - $fractionFormula = '='.$sign.$match[2].$sign.$match[3]; + $fractionFormula = '=' . $sign . $match[2] . $sign . $match[3]; $operand = \PhpSpreadsheet\Calculation::getInstance()->_calculateFormulaValue($fractionFormula); + return true; } + return false; } // function convertToNumberIfFraction() @@ -704,6 +720,7 @@ class StringHelper self::$decimalSeparator = '.'; } } + return self::$decimalSeparator; } @@ -736,6 +753,7 @@ class StringHelper self::$thousandsSeparator = ','; } } + return self::$thousandsSeparator; } @@ -765,12 +783,15 @@ class StringHelper $localeconv = localeconv(); if (!empty($localeconv['currency_symbol'])) { self::$currencyCode = $localeconv['currency_symbol']; + return self::$currencyCode; } if (!empty($localeconv['int_curr_symbol'])) { self::$currencyCode = $localeconv['int_curr_symbol']; + return self::$currencyCode; } + return self::$currencyCode; } @@ -818,6 +839,7 @@ class StringHelper return $value; } $v = floatval($value); + return (is_numeric(substr($value, 0, strlen($v)))) ? $v : $value; } } diff --git a/src/PhpSpreadsheet/Shared/TimeZone.php b/src/PhpSpreadsheet/Shared/TimeZone.php index 9b0ac31f..fa4f54b4 100644 --- a/src/PhpSpreadsheet/Shared/TimeZone.php +++ b/src/PhpSpreadsheet/Shared/TimeZone.php @@ -34,19 +34,20 @@ class TimeZone * @private * @var string */ - protected static $timezone = 'UTC'; + protected static $timezone = 'UTC'; /** * Validate a Timezone name * * @param string $timezone Time zone (e.g. 'Europe/London') - * @return boolean Success or failure + * @return bool Success or failure */ private static function validateTimeZone($timezone) { if (in_array($timezone, \DateTimeZone::listIdentifiers())) { return true; } + return false; } @@ -54,18 +55,19 @@ class TimeZone * Set the Default Timezone used for date/time conversions * * @param string $timezone Time zone (e.g. 'Europe/London') - * @return boolean Success or failure + * @return bool Success or failure */ public static function setTimeZone($timezone) { if (self::validateTimezone($timezone)) { self::$timezone = $timezone; + return true; } + return false; } - /** * Return the Default Timezone used for date/time conversions * @@ -76,18 +78,17 @@ class TimeZone return self::$timezone; } - /** * Return the Timezone transition for the specified timezone and timestamp * * @param DateTimeZone $objTimezone The timezone for finding the transitions - * @param integer $timestamp PHP date/time value for finding the current transition + * @param int $timestamp PHP date/time value for finding the current transition * @return array The current transition details */ private static function getTimezoneTransitions($objTimezone, $timestamp) { $allTransitions = $objTimezone->getTransitions(); - $transitions = array(); + $transitions = []; foreach ($allTransitions as $key => $transition) { if ($transition['ts'] > $timestamp) { $transitions[] = ($key > 0) ? $allTransitions[$key - 1] : $transition; @@ -106,15 +107,15 @@ class TimeZone * This requires both the timezone and the calculated date/time to allow for local DST * * @param string $timezone The timezone for finding the adjustment to UST - * @param integer $timestamp PHP date/time value - * @return integer Number of seconds for timezone adjustment + * @param int $timestamp PHP date/time value * @throws \PhpSpreadsheet\Exception + * @return int Number of seconds for timezone adjustment */ public static function getTimeZoneAdjustment($timezone, $timestamp) { if ($timezone !== null) { if (!self::validateTimezone($timezone)) { - throw new \PhpSpreadsheet\Exception("Invalid timezone " . $timezone); + throw new \PhpSpreadsheet\Exception('Invalid timezone ' . $timezone); } } else { $timezone = self::$timezone; diff --git a/src/PhpSpreadsheet/Shared/Trend/BestFit.php b/src/PhpSpreadsheet/Shared/Trend/BestFit.php index 15014ec8..07fc444f 100644 --- a/src/PhpSpreadsheet/Shared/Trend/BestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/BestFit.php @@ -31,7 +31,7 @@ class BestFit /** * Indicator flag for a calculation error * - * @var boolean + * @var bool **/ protected $error = false; @@ -54,19 +54,19 @@ class BestFit * * @var float[] **/ - protected $xValues = array(); + protected $xValues = []; /** * Y-value dataseries of values * * @var float[] **/ - protected $yValues = array(); + protected $yValues = []; /** * Flag indicating whether values should be adjusted to Y=0 * - * @var boolean + * @var bool **/ protected $adjustToZero = false; @@ -75,7 +75,7 @@ class BestFit * * @var float[] **/ - protected $yBestFitValues = array(); + protected $yBestFitValues = []; protected $goodnessOfFit = 1; @@ -105,13 +105,11 @@ class BestFit protected $yOffset = 0; - public function getError() { return $this->error; } - public function getBestFitType() { return $this->bestFitType; @@ -171,6 +169,7 @@ class BestFit if ($dp != 0) { return round($this->slope, $dp); } + return $this->slope; } @@ -185,6 +184,7 @@ class BestFit if ($dp != 0) { return round($this->slopeSE, $dp); } + return $this->slopeSE; } @@ -199,6 +199,7 @@ class BestFit if ($dp != 0) { return round($this->intersect, $dp); } + return $this->intersect; } @@ -213,6 +214,7 @@ class BestFit if ($dp != 0) { return round($this->intersectSE, $dp); } + return $this->intersectSE; } @@ -227,6 +229,7 @@ class BestFit if ($dp != 0) { return round($this->goodnessOfFit, $dp); } + return $this->goodnessOfFit; } @@ -235,6 +238,7 @@ class BestFit if ($dp != 0) { return round($this->goodnessOfFit * 100, $dp); } + return $this->goodnessOfFit * 100; } @@ -249,6 +253,7 @@ class BestFit if ($dp != 0) { return round($this->stdevOfResiduals, $dp); } + return $this->stdevOfResiduals; } @@ -257,6 +262,7 @@ class BestFit if ($dp != 0) { return round($this->SSRegression, $dp); } + return $this->SSRegression; } @@ -265,6 +271,7 @@ class BestFit if ($dp != 0) { return round($this->SSResiduals, $dp); } + return $this->SSResiduals; } @@ -273,6 +280,7 @@ class BestFit if ($dp != 0) { return round($this->DFResiduals, $dp); } + return $this->DFResiduals; } @@ -281,6 +289,7 @@ class BestFit if ($dp != 0) { return round($this->f, $dp); } + return $this->f; } @@ -289,6 +298,7 @@ class BestFit if ($dp != 0) { return round($this->covariance, $dp); } + return $this->covariance; } @@ -297,6 +307,7 @@ class BestFit if ($dp != 0) { return round($this->correlation, $dp); } + return $this->correlation; } @@ -401,9 +412,9 @@ class BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ - public function __construct($yValues, $xValues = array(), $const = true) + public function __construct($yValues, $xValues = [], $const = true) { // Calculate number of points $nY = count($yValues); @@ -416,6 +427,7 @@ class BestFit } elseif ($nY != $nX) { // Ensure both arrays of points are the same size $this->error = true; + return false; } diff --git a/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php b/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php index 641fefea..281e0b93 100644 --- a/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php @@ -32,7 +32,7 @@ class ExponentialBestFit extends BestFit * * @var string **/ - protected $bestFitType = 'exponential'; + protected $bestFitType = 'exponential'; /** * Return the Y-Value for a specified value of X @@ -81,6 +81,7 @@ class ExponentialBestFit extends BestFit if ($dp != 0) { return round(exp($this->_slope), $dp); } + return exp($this->_slope); } @@ -95,6 +96,7 @@ class ExponentialBestFit extends BestFit if ($dp != 0) { return round(exp($this->intersect), $dp); } + return exp($this->intersect); } @@ -103,7 +105,7 @@ class ExponentialBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ private function exponentialRegression($yValues, $xValues, $const) { @@ -124,9 +126,9 @@ class ExponentialBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ - public function __construct($yValues, $xValues = array(), $const = true) + public function __construct($yValues, $xValues = [], $const = true) { if (parent::__construct($yValues, $xValues) !== false) { $this->exponentialRegression($yValues, $xValues, $const); diff --git a/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php b/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php index fc3b664c..a314cb03 100644 --- a/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php @@ -32,7 +32,7 @@ class LinearBestFit extends BestFit * * @var string **/ - protected $bestFitType = 'linear'; + protected $bestFitType = 'linear'; /** * Return the Y-Value for a specified value of X @@ -56,7 +56,6 @@ class LinearBestFit extends BestFit return ($yValue - $this->getIntersect()) / $this->getSlope(); } - /** * Return the Equation of the best-fit line * @@ -76,7 +75,7 @@ class LinearBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ private function linearRegression($yValues, $xValues, $const) { @@ -88,9 +87,9 @@ class LinearBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ - public function __construct($yValues, $xValues = array(), $const = true) + public function __construct($yValues, $xValues = [], $const = true) { if (parent::__construct($yValues, $xValues) !== false) { $this->linearRegression($yValues, $xValues, $const); diff --git a/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php b/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php index adc34b62..5f03d941 100644 --- a/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php @@ -32,7 +32,7 @@ class LogarithmicBestFit extends BestFit * * @var string **/ - protected $bestFitType = 'logarithmic'; + protected $bestFitType = 'logarithmic'; /** * Return the Y-Value for a specified value of X @@ -67,7 +67,7 @@ class LogarithmicBestFit extends BestFit $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); - return 'Y = '.$intersect.' + '.$slope.' * log(X)'; + return 'Y = ' . $intersect . ' + ' . $slope . ' * log(X)'; } /** @@ -75,7 +75,7 @@ class LogarithmicBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ private function logarithmicRegression($yValues, $xValues, $const) { @@ -96,9 +96,9 @@ class LogarithmicBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ - public function __construct($yValues, $xValues = array(), $const = true) + public function __construct($yValues, $xValues = [], $const = true) { if (parent::__construct($yValues, $xValues) !== false) { $this->logarithmicRegression($yValues, $xValues, $const); diff --git a/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php b/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php index 6ef4d33d..5732f871 100644 --- a/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php @@ -42,7 +42,6 @@ class PolynomialBestFit extends BestFit **/ protected $order = 0; - /** * Return the order of this polynomial * @@ -53,7 +52,6 @@ class PolynomialBestFit extends BestFit return $this->order; } - /** * Return the Y-Value for a specified value of X * @@ -69,10 +67,10 @@ class PolynomialBestFit extends BestFit $retVal += $value * pow($xValue, $key + 1); } } + return $retVal; } - /** * Return the X-Value for a specified value of Y * @@ -84,7 +82,6 @@ class PolynomialBestFit extends BestFit return ($yValue - $this->getIntersect()) / $this->getSlope(); } - /** * Return the Equation of the best-fit line * @@ -105,10 +102,10 @@ class PolynomialBestFit extends BestFit } } } + return $equation; } - /** * Return the Slope of the line * @@ -118,29 +115,29 @@ class PolynomialBestFit extends BestFit public function getSlope($dp = 0) { if ($dp != 0) { - $coefficients = array(); + $coefficients = []; foreach ($this->_slope as $coefficient) { $coefficients[] = round($coefficient, $dp); } + return $coefficients; } + return $this->_slope; } - public function getCoefficients($dp = 0) { - return array_merge(array($this->getIntersect($dp)), $this->getSlope($dp)); + return array_merge([$this->getIntersect($dp)], $this->getSlope($dp)); } - /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values * * @param int $order Order of Polynomial for this regression * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ private function polynomialRegression($order, $yValues, $xValues, $const) { @@ -166,14 +163,14 @@ class PolynomialBestFit extends BestFit $A[$i][$j] = pow($xValues[$i], $j); } } - for ($i=0; $i < $this->valueCount; ++$i) { - $B[$i] = array($yValues[$i]); + for ($i = 0; $i < $this->valueCount; ++$i) { + $B[$i] = [$yValues[$i]]; } $matrixA = new Matrix($A); $matrixB = new Matrix($B); $C = $matrixA->solve($matrixB); - $coefficients = array(); + $coefficients = []; for ($i = 0; $i < $C->m; ++$i) { $r = $C->get($i, 0); if (abs($r) <= pow(10, -9)) { @@ -191,20 +188,19 @@ class PolynomialBestFit extends BestFit } } - /** * Define the regression and calculate the goodness of fit for a set of X and Y data values * * @param int $order Order of Polynomial for this regression * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ - public function __construct($order, $yValues, $xValues = array(), $const = true) + public function __construct($order, $yValues, $xValues = [], $const = true) { if (parent::__construct($yValues, $xValues) !== false) { if ($order < $this->valueCount) { - $this->bestFitType .= '_'.$order; + $this->bestFitType .= '_' . $order; $this->order = $order; $this->polynomialRegression($order, $yValues, $xValues, $const); if (($this->getGoodnessOfFit() < 0.0) || ($this->getGoodnessOfFit() > 1.0)) { diff --git a/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php b/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php index ce7d87f9..b6be976e 100644 --- a/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php @@ -34,8 +34,7 @@ class PowerBestFit extends BestFit * * @var string **/ - protected $bestFitType = 'power'; - + protected $bestFitType = 'power'; /** * Return the Y-Value for a specified value of X @@ -48,7 +47,6 @@ class PowerBestFit extends BestFit return $this->getIntersect() * pow(($xValue - $this->xOffset), $this->getSlope()); } - /** * Return the X-Value for a specified value of Y * @@ -60,7 +58,6 @@ class PowerBestFit extends BestFit return pow((($yValue + $this->yOffset) / $this->getIntersect()), (1 / $this->getSlope())); } - /** * Return the Equation of the best-fit line * @@ -75,7 +72,6 @@ class PowerBestFit extends BestFit return 'Y = ' . $intersect . ' * X^' . $slope; } - /** * Return the Value of X where it intersects Y = 0 * @@ -87,16 +83,16 @@ class PowerBestFit extends BestFit if ($dp != 0) { return round(exp($this->intersect), $dp); } + return exp($this->intersect); } - /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ private function powerRegression($yValues, $xValues, $const) { @@ -120,15 +116,14 @@ class PowerBestFit extends BestFit $this->leastSquareFit($yValues, $xValues, $const); } - /** * Define the regression and calculate the goodness of fit for a set of X and Y data values * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param boolean $const + * @param bool $const */ - public function __construct($yValues, $xValues = array(), $const = true) + public function __construct($yValues, $xValues = [], $const = true) { if (parent::__construct($yValues, $xValues) !== false) { $this->powerRegression($yValues, $xValues, $const); diff --git a/src/PhpSpreadsheet/Shared/Trend/Trend.php b/src/PhpSpreadsheet/Shared/Trend/Trend.php index c4e3260c..bf5ad69f 100644 --- a/src/PhpSpreadsheet/Shared/Trend/Trend.php +++ b/src/PhpSpreadsheet/Shared/Trend/Trend.php @@ -26,52 +26,51 @@ namespace PhpSpreadsheet\Shared\Trend; */ class Trend { - const TREND_LINEAR = 'Linear'; - const TREND_LOGARITHMIC = 'Logarithmic'; - const TREND_EXPONENTIAL = 'Exponential'; - const TREND_POWER = 'Power'; - const TREND_POLYNOMIAL_2 = 'Polynomial_2'; - const TREND_POLYNOMIAL_3 = 'Polynomial_3'; - const TREND_POLYNOMIAL_4 = 'Polynomial_4'; - const TREND_POLYNOMIAL_5 = 'Polynomial_5'; - const TREND_POLYNOMIAL_6 = 'Polynomial_6'; - const TREND_BEST_FIT = 'Bestfit'; - const TREND_BEST_FIT_NO_POLY = 'Bestfit_no_Polynomials'; + const TREND_LINEAR = 'Linear'; + const TREND_LOGARITHMIC = 'Logarithmic'; + const TREND_EXPONENTIAL = 'Exponential'; + const TREND_POWER = 'Power'; + const TREND_POLYNOMIAL_2 = 'Polynomial_2'; + const TREND_POLYNOMIAL_3 = 'Polynomial_3'; + const TREND_POLYNOMIAL_4 = 'Polynomial_4'; + const TREND_POLYNOMIAL_5 = 'Polynomial_5'; + const TREND_POLYNOMIAL_6 = 'Polynomial_6'; + const TREND_BEST_FIT = 'Bestfit'; + const TREND_BEST_FIT_NO_POLY = 'Bestfit_no_Polynomials'; /** * Names of the best-fit Trend analysis methods * * @var string[] **/ - private static $trendTypes = array( + private static $trendTypes = [ self::TREND_LINEAR, self::TREND_LOGARITHMIC, self::TREND_EXPONENTIAL, - self::TREND_POWER - ); + self::TREND_POWER, + ]; /** * Names of the best-fit Trend polynomial orders * * @var string[] **/ - private static $trendTypePolynomialOrders = array( + private static $trendTypePolynomialOrders = [ self::TREND_POLYNOMIAL_2, self::TREND_POLYNOMIAL_3, self::TREND_POLYNOMIAL_4, self::TREND_POLYNOMIAL_5, - self::TREND_POLYNOMIAL_6 - ); + self::TREND_POLYNOMIAL_6, + ]; /** * Cached results for each method when trying to identify which provides the best fit * * @var bestFit[] **/ - private static $trendCache = array(); + private static $trendCache = []; - - public static function calculate($trendType = self::TREND_BEST_FIT, $yValues = array(), $xValues = array(), $const = true) + public static function calculate($trendType = self::TREND_BEST_FIT, $yValues = [], $xValues = [], $const = true) { // Calculate number of points in each dataset $nY = count($yValues); @@ -83,10 +82,10 @@ class Trend $nX = $nY; } elseif ($nY != $nX) { // Ensure both arrays of points are the same size - trigger_error("Trend(): Number of elements in coordinate arrays do not match.", E_USER_ERROR); + trigger_error('Trend(): Number of elements in coordinate arrays do not match.', E_USER_ERROR); } - $key = md5($trendType.$const.serialize($yValues).serialize($xValues)); + $key = md5($trendType . $const . serialize($yValues) . serialize($xValues)); // Determine which Trend method has been requested switch ($trendType) { // Instantiate and return the class for the requested Trend method @@ -95,9 +94,10 @@ class Trend case self::TREND_EXPONENTIAL: case self::TREND_POWER: if (!isset(self::$trendCache[$key])) { - $className = '\PhpSpreadsheet\Shared\Trend\\'.$trendType.'BestFit'; + $className = '\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit'; self::$trendCache[$key] = new $className($yValues, $xValues, $const); } + return self::$trendCache[$key]; case self::TREND_POLYNOMIAL_2: case self::TREND_POLYNOMIAL_3: @@ -108,13 +108,14 @@ class Trend $order = substr($trendType, -1); self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues, $const); } + return self::$trendCache[$key]; case self::TREND_BEST_FIT: case self::TREND_BEST_FIT_NO_POLY: // If the request is to determine the best fit regression, then we test each Trend line in turn // Start by generating an instance of each available Trend method foreach (self::$trendTypes as $trendMethod) { - $className = '\PhpSpreadsheet\Shared\Trend\\'.$trendType.'BestFit'; + $className = '\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit'; $bestFit[$trendMethod] = new $className($yValues, $xValues, $const); $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); } @@ -132,6 +133,7 @@ class Trend // Determine which of our Trend lines is the best fit, and then we return the instance of that Trend class arsort($bestFitValue); $bestFitType = key($bestFitValue); + return $bestFit[$bestFitType]; default: return false; diff --git a/src/PhpSpreadsheet/Shared/XMLWriter.php b/src/PhpSpreadsheet/Shared/XMLWriter.php index 7a67c667..f0568809 100644 --- a/src/PhpSpreadsheet/Shared/XMLWriter.php +++ b/src/PhpSpreadsheet/Shared/XMLWriter.php @@ -35,15 +35,15 @@ if (!defined('DEBUGMODE_ENABLED')) { class XMLWriter extends \XMLWriter { /** Temporary storage method */ - const STORAGE_MEMORY = 1; - const STORAGE_DISK = 2; + const STORAGE_MEMORY = 1; + const STORAGE_DISK = 2; /** * Temporary filename * * @var string */ - private $tempFileName = ''; + private $tempFileName = ''; /** * Create a new XMLWriter instance @@ -98,6 +98,7 @@ class XMLWriter extends \XMLWriter return $this->outputMemory(true); } else { $this->flush(); + return file_get_contents($this->tempFileName); } } diff --git a/src/PhpSpreadsheet/Shared/ZipArchive.php b/src/PhpSpreadsheet/Shared/ZipArchive.php index d12fb674..4ea74071 100644 --- a/src/PhpSpreadsheet/Shared/ZipArchive.php +++ b/src/PhpSpreadsheet/Shared/ZipArchive.php @@ -32,11 +32,9 @@ use PhpSpreadsheet\Shared\PCLZip\PclZip; */ class ZipArchive { - /** constants */ const OVERWRITE = 'OVERWRITE'; - const CREATE = 'CREATE'; - + const CREATE = 'CREATE'; /** * Temporary storage directory @@ -52,12 +50,11 @@ class ZipArchive */ private $zip; - /** * Open a new zip archive * * @param string $fileName Filename for the zip archive - * @return boolean + * @return bool */ public function open($fileName) { @@ -67,16 +64,13 @@ class ZipArchive return true; } - /** * Close this zip archive - * */ public function close() { } - /** * Add a new file to the zip archive from a string of raw data. * @@ -88,23 +82,23 @@ class ZipArchive { $filenameParts = pathinfo($localname); - $handle = fopen($this->tempDir.'/'.$filenameParts["basename"], "wb"); + $handle = fopen($this->tempDir . '/' . $filenameParts['basename'], 'wb'); fwrite($handle, $contents); fclose($handle); - $res = $this->zip->add($this->tempDir.'/'.$filenameParts["basename"], PCLZIP_OPT_REMOVE_PATH, $this->tempDir, PCLZIP_OPT_ADD_PATH, $filenameParts["dirname"]); + $res = $this->zip->add($this->tempDir . '/' . $filenameParts['basename'], PCLZIP_OPT_REMOVE_PATH, $this->tempDir, PCLZIP_OPT_ADD_PATH, $filenameParts['dirname']); if ($res == 0) { - throw new \PhpSpreadsheet\Writer\Exception("Error zipping files : " . $this->zip->errorInfo(true)); + throw new \PhpSpreadsheet\Writer\Exception('Error zipping files : ' . $this->zip->errorInfo(true)); } - unlink($this->tempDir.'/'.$filenameParts["basename"]); + unlink($this->tempDir . '/' . $filenameParts['basename']); } /** * Find if given fileName exist in archive (Emulate ZipArchive locateName()) * * @param string $fileName Filename for the file in zip archive - * @return boolean + * @return bool */ public function locateName($fileName) { @@ -114,12 +108,13 @@ class ZipArchive $listCount = count($list); $index = -1; for ($i = 0; $i < $listCount; ++$i) { - if (strtolower($list[$i]["filename"]) == strtolower($fileName) || - strtolower($list[$i]["stored_filename"]) == strtolower($fileName)) { + if (strtolower($list[$i]['filename']) == strtolower($fileName) || + strtolower($list[$i]['stored_filename']) == strtolower($fileName)) { $index = $i; break; } } + return ($index > -1) ? $index : false; } @@ -146,7 +141,7 @@ class ZipArchive $contents = $extracted; if ((is_array($extracted)) && ($extracted != 0)) { - $contents = $extracted[0]["content"]; + $contents = $extracted[0]['content']; } return $contents; @@ -157,7 +152,7 @@ class ZipArchive $extracted = $this->zip->extractByIndex($index, PCLZIP_OPT_EXTRACT_AS_STRING); $contents = ''; if ((is_array($extracted)) && ($extracted != 0)) { - $contents = $extracted[0]["content"]; + $contents = $extracted[0]['content']; } } } diff --git a/src/PhpSpreadsheet/Shared/ZipStreamWrapper.php b/src/PhpSpreadsheet/Shared/ZipStreamWrapper.php index 763bf19f..7d4fb7aa 100644 --- a/src/PhpSpreadsheet/Shared/ZipStreamWrapper.php +++ b/src/PhpSpreadsheet/Shared/ZipStreamWrapper.php @@ -70,8 +70,8 @@ class ZipStreamWrapper * @param string $mode only "r" is supported * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH * @param string &$openedPath absolute path of the opened stream (out parameter) - * @return bool true on success * @throws \PhpSpreadsheet\Reader\Exception + * @return bool true on success */ public function stream_open($path, $mode, $options, &$opened_path) // @codingStandardsIgnoreLine { @@ -99,7 +99,7 @@ class ZipStreamWrapper /** * Implements support for fstat(). * - * @return boolean + * @return bool */ public function statName() { @@ -109,7 +109,7 @@ class ZipStreamWrapper /** * Implements support for fstat(). * - * @return boolean + * @return bool */ public function url_stat() // @codingStandardsIgnoreLine { @@ -119,7 +119,7 @@ class ZipStreamWrapper /** * Implements support for fstat(). * - * @return boolean + * @return bool */ public function stream_stat() // @codingStandardsIgnoreLine { @@ -136,6 +136,7 @@ class ZipStreamWrapper { $ret = substr($this->data, $this->position, $count); $this->position += strlen($ret); + return $ret; } @@ -172,26 +173,29 @@ class ZipStreamWrapper switch ($whence) { case SEEK_SET: if ($offset < strlen($this->data) && $offset >= 0) { - $this->position = $offset; - return true; + $this->position = $offset; + + return true; } else { - return false; + return false; } break; case SEEK_CUR: if ($offset >= 0) { - $this->position += $offset; - return true; + $this->position += $offset; + + return true; } else { - return false; + return false; } break; case SEEK_END: if (strlen($this->data) + $offset >= 0) { - $this->position = strlen($this->data) + $offset; - return true; + $this->position = strlen($this->data) + $offset; + + return true; } else { - return false; + return false; } break; default: diff --git a/src/PhpSpreadsheet/Spreadsheet.php b/src/PhpSpreadsheet/Spreadsheet.php index 54f4d825..afe7597d 100644 --- a/src/PhpSpreadsheet/Spreadsheet.php +++ b/src/PhpSpreadsheet/Spreadsheet.php @@ -54,7 +54,7 @@ class Spreadsheet * * @var Worksheet[] */ - private $workSheetCollection = array(); + private $workSheetCollection = []; /** * Calculation Engine @@ -66,7 +66,7 @@ class Spreadsheet /** * Active sheet index * - * @var integer + * @var int */ private $activeSheetIndex = 0; @@ -75,7 +75,7 @@ class Spreadsheet * * @var NamedRange[] */ - private $namedRanges = array(); + private $namedRanges = []; /** * CellXf supervisor @@ -89,75 +89,75 @@ class Spreadsheet * * @var Style[] */ - private $cellXfCollection = array(); + private $cellXfCollection = []; /** * CellStyleXf collection * * @var Style[] */ - private $cellStyleXfCollection = array(); + private $cellStyleXfCollection = []; /** - * hasMacros : this workbook have macros ? - * - * @var bool - */ + * hasMacros : this workbook have macros ? + * + * @var bool + */ private $hasMacros = false; /** - * macrosCode : all macros code (the vbaProject.bin file, this include form, code, etc.), null if no macro - * - * @var binary - */ + * macrosCode : all macros code (the vbaProject.bin file, this include form, code, etc.), null if no macro + * + * @var binary + */ private $macrosCode; /** - * macrosCertificate : if macros are signed, contains vbaProjectSignature.bin file, null if not signed - * - * @var binary - */ + * macrosCertificate : if macros are signed, contains vbaProjectSignature.bin file, null if not signed + * + * @var binary + */ private $macrosCertificate; /** - * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI - * - * @var null|string - */ + * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI + * + * @var null|string + */ private $ribbonXMLData; /** - * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements - * ignored if $ribbonXMLData is null - * - * @var null|array - */ + * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements + * ignored if $ribbonXMLData is null + * + * @var null|array + */ private $ribbonBinObjects; /** - * The workbook has macros ? - * - * @return true if workbook has macros, false if not - */ + * The workbook has macros ? + * + * @return true if workbook has macros, false if not + */ public function hasMacros() { return $this->hasMacros; } /** - * Define if a workbook has macros - * - * @param boolean $hasMacros true|false - */ + * Define if a workbook has macros + * + * @param bool $hasMacros true|false + */ public function setHasMacros($hasMacros = false) { $this->hasMacros = (bool) $hasMacros; } /** - * Set the macros code - * - * @param string $macroCode string|null - */ + * Set the macros code + * + * @param string $macroCode string|null + */ public function setMacrosCode($macroCode = null) { $this->macrosCode = $macroCode; @@ -165,49 +165,48 @@ class Spreadsheet } /** - * Return the macros code - * - * @return string|null - */ + * Return the macros code + * + * @return string|null + */ public function getMacrosCode() { return $this->macrosCode; } /** - * Set the macros certificate - * - * @param string|null $Certificate - */ + * Set the macros certificate + * + * @param string|null $Certificate + */ public function setMacrosCertificate($certificate = null) { $this->macrosCertificate = $certificate; } /** - * Is the project signed ? - * - * @return boolean true|false - */ + * Is the project signed ? + * + * @return bool true|false + */ public function hasMacrosCertificate() { return !is_null($this->macrosCertificate); } /** - * Return the macros certificate - * - * @return string|null - */ + * Return the macros certificate + * + * @return string|null + */ public function getMacrosCertificate() { return $this->macrosCertificate; } /** - * Remove all macros, certificate from spreadsheet - * - */ + * Remove all macros, certificate from spreadsheet + */ public function discardMacros() { $this->hasMacros = false; @@ -216,23 +215,22 @@ class Spreadsheet } /** - * set ribbon XML data - * - */ + * set ribbon XML data + */ public function setRibbonXMLData($target = null, $xmlData = null) { if (!is_null($target) && !is_null($xmlData)) { - $this->ribbonXMLData = array('target' => $target, 'data' => $xmlData); + $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData]; } else { $this->ribbonXMLData = null; } } /** - * retrieve ribbon XML Data - * - * return string|null|array - */ + * retrieve ribbon XML Data + * + * return string|null|array + */ public function getRibbonXMLData($what = 'all') //we need some constants here... { $returnData = null; @@ -253,30 +251,27 @@ class Spreadsheet } /** - * store binaries ribbon objects (pictures) - * - */ + * store binaries ribbon objects (pictures) + */ public function setRibbonBinObjects($BinObjectsNames = null, $BinObjectsData = null) { if (!is_null($BinObjectsNames) && !is_null($BinObjectsData)) { - $this->ribbonBinObjects = array('names' => $BinObjectsNames, 'data' => $BinObjectsData); + $this->ribbonBinObjects = ['names' => $BinObjectsNames, 'data' => $BinObjectsData]; } else { $this->ribbonBinObjects = null; } } /** - * return the extension of a filename. Internal use for a array_map callback (php<5.3 don't like lambda function) - * - */ + * return the extension of a filename. Internal use for a array_map callback (php<5.3 don't like lambda function) + */ private function getExtensionOnly($ThePath) { return pathinfo($ThePath, PATHINFO_EXTENSION); } /** - * retrieve Binaries Ribbon Objects - * - */ + * retrieve Binaries Ribbon Objects + */ public function getRibbonBinObjects($What = 'all') { $ReturnData = null; @@ -288,37 +283,38 @@ class Spreadsheet case 'names': case 'data': if (is_array($this->ribbonBinObjects) && array_key_exists($What, $this->ribbonBinObjects)) { - $ReturnData=$this->ribbonBinObjects[$What]; + $ReturnData = $this->ribbonBinObjects[$What]; } break; case 'types': if (is_array($this->ribbonBinObjects) && array_key_exists('data', $this->ribbonBinObjects) && is_array($this->ribbonBinObjects['data'])) { - $tmpTypes=array_keys($this->ribbonBinObjects['data']); - $ReturnData = array_unique(array_map(array($this, 'getExtensionOnly'), $tmpTypes)); + $tmpTypes = array_keys($this->ribbonBinObjects['data']); + $ReturnData = array_unique(array_map([$this, 'getExtensionOnly'], $tmpTypes)); } else { - $ReturnData=array(); // the caller want an array... not null if empty + $ReturnData = []; // the caller want an array... not null if empty } break; } + return $ReturnData; } /** - * This workbook have a custom UI ? - * - * @return true|false - */ + * This workbook have a custom UI ? + * + * @return true|false + */ public function hasRibbon() { return !is_null($this->ribbonXMLData); } /** - * This workbook have additionnal object for the ribbon ? - * - * @return true|false - */ + * This workbook have additionnal object for the ribbon ? + * + * @return true|false + */ public function hasRibbonBinObjects() { return !is_null($this->ribbonBinObjects); @@ -328,11 +324,11 @@ class Spreadsheet * Check if a sheet with a specified code name already exists * * @param string $pSheetCodeName Name of the worksheet to check - * @return boolean + * @return bool */ public function sheetCodeNameExists($pSheetCodeName) { - return ($this->getSheetByCodeName($pSheetCodeName) !== null); + return $this->getSheetByCodeName($pSheetCodeName) !== null; } /** @@ -353,7 +349,7 @@ class Spreadsheet return null; } - /** + /** * Create a new PhpSpreadsheet with one Worksheet */ public function __construct() @@ -362,7 +358,7 @@ class Spreadsheet $this->calculationEngine = new Calculation($this); // Initialise worksheet collection and add one worksheet - $this->workSheetCollection = array(); + $this->workSheetCollection = []; $this->workSheetCollection[] = new Worksheet($this); $this->activeSheetIndex = 0; @@ -373,20 +369,19 @@ class Spreadsheet $this->security = new Document\Security(); // Set named ranges - $this->namedRanges = array(); + $this->namedRanges = []; // Create the cellXf supervisor $this->cellXfSupervisor = new Style(true); $this->cellXfSupervisor->bindParent($this); // Create the default style - $this->addCellXf(new Style); - $this->addCellStyleXf(new Style); + $this->addCellXf(new Style()); + $this->addCellStyleXf(new Style()); } /** * Code to execute when this worksheet is unset() - * */ public function __destruct() { @@ -397,7 +392,6 @@ class Spreadsheet /** * Disconnect all worksheets from this PhpSpreadsheet workbook object, * typically so that the PhpSpreadsheet object can be unset - * */ public function disconnectWorksheets() { @@ -407,7 +401,7 @@ class Spreadsheet $this->workSheetCollection[$k] = null; } unset($worksheet); - $this->workSheetCollection = array(); + $this->workSheetCollection = []; } /** @@ -463,9 +457,8 @@ class Spreadsheet /** * Get active sheet * - * @return Worksheet - * * @throws Exception + * @return Worksheet */ public function getActiveSheet() { @@ -476,13 +469,14 @@ class Spreadsheet * Create sheet and add it to this workbook * * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) - * @return Worksheet * @throws Exception + * @return Worksheet */ public function createSheet($iSheetIndex = null) { $newSheet = new Worksheet($this); $this->addSheet($newSheet, $iSheetIndex); + return $newSheet; } @@ -490,11 +484,11 @@ class Spreadsheet * Check if a sheet with a specified name already exists * * @param string $pSheetName Name of the worksheet to check - * @return boolean + * @return bool */ public function sheetNameExists($pSheetName) { - return ($this->getSheetByName($pSheetName) !== null); + return $this->getSheetByName($pSheetName) !== null; } /** @@ -502,8 +496,8 @@ class Spreadsheet * * @param Worksheet $pSheet * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) - * @return Worksheet * @throws Exception + * @return Worksheet */ public function addSheet(Worksheet $pSheet, $iSheetIndex = null) { @@ -524,7 +518,7 @@ class Spreadsheet $this->workSheetCollection, $iSheetIndex, 0, - array($pSheet) + [$pSheet] ); // Adjust active sheet index if necessary @@ -548,7 +542,6 @@ class Spreadsheet */ public function removeSheetByIndex($pIndex = 0) { - $numSheets = count($this->workSheetCollection); if ($pIndex > $numSheets - 1) { throw new Exception( @@ -568,8 +561,8 @@ class Spreadsheet * Get sheet by index * * @param int $pIndex Sheet index - * @return Worksheet * @throws Exception + * @return Worksheet */ public function getSheet($pIndex = 0) { @@ -615,8 +608,8 @@ class Spreadsheet * Get index for sheet * * @param Worksheet $pSheet - * @return Sheet index * @throws Exception + * @return Sheet index */ public function getIndex(Worksheet $pSheet) { @@ -626,7 +619,7 @@ class Spreadsheet } } - throw new Exception("Sheet does not exist."); + throw new Exception('Sheet does not exist.'); } /** @@ -634,8 +627,8 @@ class Spreadsheet * * @param string $sheetName Sheet name to modify index for * @param int $newIndex New index for the sheet - * @return New sheet index * @throws Exception + * @return New sheet index */ public function setIndexByName($sheetName, $newIndex) { @@ -651,6 +644,7 @@ class Spreadsheet 0, $pSheet ); + return $newIndex; } @@ -692,6 +686,7 @@ class Spreadsheet } else { $this->activeSheetIndex = $pIndex; } + return $this->getActiveSheet(); } @@ -699,13 +694,14 @@ class Spreadsheet * Set active sheet index by name * * @param string $pValue Sheet title - * @return Worksheet * @throws Exception + * @return Worksheet */ public function setActiveSheetIndexByName($pValue = '') { if (($worksheet = $this->getSheetByName($pValue)) instanceof Worksheet) { $this->setActiveSheetIndex($this->getIndex($worksheet)); + return $worksheet; } @@ -719,7 +715,7 @@ class Spreadsheet */ public function getSheetNames() { - $returnValue = array(); + $returnValue = []; $worksheetCount = $this->getSheetCount(); for ($i = 0; $i < $worksheetCount; ++$i) { $returnValue[] = $this->getSheet($i)->getTitle(); @@ -785,8 +781,9 @@ class Spreadsheet $this->namedRanges[$namedRange->getName()] = $namedRange; } else { // local scope - $this->namedRanges[$namedRange->getScope()->getTitle().'!'.$namedRange->getName()] = $namedRange; + $this->namedRanges[$namedRange->getScope()->getTitle() . '!' . $namedRange->getName()] = $namedRange; } + return true; } @@ -834,6 +831,7 @@ class Spreadsheet unset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange]); } } + return $this; } @@ -911,6 +909,7 @@ class Spreadsheet return $cellXf; } } + return false; } @@ -918,7 +917,7 @@ class Spreadsheet * Check if style exists in style collection * * @param Style $pCellStyle - * @return boolean + * @return bool */ public function cellXfExists($pCellStyle = null) { @@ -928,8 +927,8 @@ class Spreadsheet /** * Get default style * - * @return Style * @throws Exception + * @return Style */ public function getDefaultStyle() { @@ -953,13 +952,13 @@ class Spreadsheet /** * Remove cellXf by index. It is ensured that all cells get their xf index updated. * - * @param integer $pIndex Index to cellXf + * @param int $pIndex Index to cellXf * @throws Exception */ public function removeCellXfByIndex($pIndex = 0) { if ($pIndex > count($this->cellXfCollection) - 1) { - throw new Exception("CellXf index is out of bounds."); + throw new Exception('CellXf index is out of bounds.'); } else { // first remove the cellXf array_splice($this->cellXfCollection, $pIndex, 1); @@ -1004,7 +1003,7 @@ class Spreadsheet /** * Get cellStyleXf by index * - * @param integer $pIndex Index to cellXf + * @param int $pIndex Index to cellXf * @return Style */ public function getCellStyleXfByIndex($pIndex = 0) @@ -1025,6 +1024,7 @@ class Spreadsheet return $cellStyleXf; } } + return false; } @@ -1042,13 +1042,13 @@ class Spreadsheet /** * Remove cellStyleXf by index * - * @param integer $pIndex Index to cellXf + * @param int $pIndex Index to cellXf * @throws Exception */ public function removeCellStyleXfByIndex($pIndex = 0) { if ($pIndex > count($this->cellStyleXfCollection) - 1) { - throw new Exception("CellStyleXf index is out of bounds."); + throw new Exception('CellStyleXf index is out of bounds.'); } else { array_splice($this->cellStyleXfCollection, $pIndex, 1); } @@ -1061,7 +1061,7 @@ class Spreadsheet public function garbageCollect() { // how many references are there to each cellXf ? - $countReferencesCellXf = array(); + $countReferencesCellXf = []; foreach ($this->cellXfCollection as $index => $cellXf) { $countReferencesCellXf[$index] = 0; } diff --git a/src/PhpSpreadsheet/Style.php b/src/PhpSpreadsheet/Style.php index fbc80a16..c651d011 100644 --- a/src/PhpSpreadsheet/Style.php +++ b/src/PhpSpreadsheet/Style.php @@ -85,17 +85,17 @@ class Style extends Style\Supervisor implements IComparable /** * Use Quote Prefix when displaying in cell editor. Only used for real style. * - * @var boolean + * @var bool */ protected $quotePrefix = false; /** * Create a new Style * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -105,13 +105,13 @@ class Style extends Style\Supervisor implements IComparable $this->isSupervisor = $isSupervisor; // Initialise values - $this->conditionalStyles = array(); - $this->font = new Style\Font($isSupervisor, $isConditional); - $this->fill = new Style\Fill($isSupervisor, $isConditional); - $this->borders = new Style\Borders($isSupervisor, $isConditional); - $this->alignment = new Style\Alignment($isSupervisor, $isConditional); + $this->conditionalStyles = []; + $this->font = new Style\Font($isSupervisor, $isConditional); + $this->fill = new Style\Fill($isSupervisor, $isConditional); + $this->borders = new Style\Borders($isSupervisor, $isConditional); + $this->alignment = new Style\Alignment($isSupervisor, $isConditional); $this->numberFormat = new Style\NumberFormat($isSupervisor, $isConditional); - $this->protection = new Style\Protection($isSupervisor, $isConditional); + $this->protection = new Style\Protection($isSupervisor, $isConditional); // bind parent if we are a supervisor if ($isSupervisor) { @@ -162,7 +162,7 @@ class Style extends Style\Supervisor implements IComparable */ public function getStyleArray($array) { - return array('quotePrefix' => $array); + return ['quotePrefix' => $array]; } /** @@ -201,7 +201,7 @@ class Style extends Style\Supervisor implements IComparable * * * @param array $pStyles Array containing style information - * @param boolean $pAdvanced Advanced mode for setting borders. + * @param bool $pAdvanced Advanced mode for setting borders. * @throws Exception * @return Style */ @@ -224,11 +224,11 @@ class Style extends Style\Supervisor implements IComparable // Calculate range outer borders $rangeStart = Cell::coordinateFromString($rangeA); - $rangeEnd = Cell::coordinateFromString($rangeB); + $rangeEnd = Cell::coordinateFromString($rangeB); // Translate column into index $rangeStart[0] = Cell::columnIndexFromString($rangeStart[0]) - 1; - $rangeEnd[0] = Cell::columnIndexFromString($rangeEnd[0]) - 1; + $rangeEnd[0] = Cell::columnIndexFromString($rangeEnd[0]) - 1; // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { @@ -242,7 +242,7 @@ class Style extends Style\Supervisor implements IComparable // 'allborders' is a shorthand property for 'outline' and 'inside' and // it applies to components that have not been set explicitly if (isset($pStyles['borders']['allborders'])) { - foreach (array('outline', 'inside') as $component) { + foreach (['outline', 'inside'] as $component) { if (!isset($pStyles['borders'][$component])) { $pStyles['borders'][$component] = $pStyles['borders']['allborders']; } @@ -252,7 +252,7 @@ class Style extends Style\Supervisor implements IComparable // 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left' // it applies to components that have not been set explicitly if (isset($pStyles['borders']['outline'])) { - foreach (array('top', 'right', 'bottom', 'left') as $component) { + foreach (['top', 'right', 'bottom', 'left'] as $component) { if (!isset($pStyles['borders'][$component])) { $pStyles['borders'][$component] = $pStyles['borders']['outline']; } @@ -262,7 +262,7 @@ class Style extends Style\Supervisor implements IComparable // 'inside' is a shorthand property for 'vertical' and 'horizontal' // it applies to components that have not been set explicitly if (isset($pStyles['borders']['inside'])) { - foreach (array('vertical', 'horizontal') as $component) { + foreach (['vertical', 'horizontal'] as $component) { if (!isset($pStyles['borders'][$component])) { $pStyles['borders'][$component] = $pStyles['borders']['inside']; } @@ -286,7 +286,7 @@ class Style extends Style\Supervisor implements IComparable for ($y = 1; $y <= $yMax; ++$y) { // which edges are touching the region - $edges = array(); + $edges = []; if ($x == 1) { // are we at left edge $edges[] = 'left'; @@ -320,7 +320,7 @@ class Style extends Style\Supervisor implements IComparable unset($regionStyles['borders']['inside']); // what are the inner edges of the region when looking at the selection - $innerEdges = array_diff(array('top', 'right', 'bottom', 'left'), $edges); + $innerEdges = array_diff(['top', 'right', 'bottom', 'left'], $edges); // inner edges that are not touching the region should take the 'inside' border properties if they have been set foreach ($innerEdges as $innerEdge) { @@ -350,6 +350,7 @@ class Style extends Style\Supervisor implements IComparable $this->getActiveSheet()->getStyle($range)->applyFromArray($regionStyles, false); } } + return $this; } @@ -366,13 +367,13 @@ class Style extends Style\Supervisor implements IComparable // First loop through columns, rows, or cells to find out which styles are affected by this operation switch ($selectionType) { case 'COLUMN': - $oldXfIndexes = array(); + $oldXfIndexes = []; for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true; } break; case 'ROW': - $oldXfIndexes = array(); + $oldXfIndexes = []; for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() == null) { $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style @@ -382,7 +383,7 @@ class Style extends Style\Supervisor implements IComparable } break; case 'CELL': - $oldXfIndexes = array(); + $oldXfIndexes = []; for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true; @@ -462,8 +463,9 @@ class Style extends Style\Supervisor implements IComparable } } } else { - throw new Exception("Invalid style array passed."); + throw new Exception('Invalid style array passed.'); } + return $this; } @@ -496,6 +498,7 @@ class Style extends Style\Supervisor implements IComparable public function setFont(Style\Font $font) { $this->font = $font; + return $this; } @@ -550,6 +553,7 @@ class Style extends Style\Supervisor implements IComparable if (is_array($pValue)) { $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $pValue); } + return $this; } @@ -566,20 +570,21 @@ class Style extends Style\Supervisor implements IComparable /** * Get quote prefix * - * @return boolean + * @return bool */ public function getQuotePrefix() { if ($this->isSupervisor) { return $this->getSharedComponent()->getQuotePrefix(); } + return $this->quotePrefix; } /** * Set quote prefix * - * @param boolean $pValue + * @param bool $pValue */ public function setQuotePrefix($pValue) { @@ -587,11 +592,12 @@ class Style extends Style\Supervisor implements IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = array('quotePrefix' => $pValue); + $styleArray = ['quotePrefix' => $pValue]; $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->quotePrefix = (boolean) $pValue; } + return $this; } diff --git a/src/PhpSpreadsheet/Style/Alignment.php b/src/PhpSpreadsheet/Style/Alignment.php index 1bb34dd8..f632d0e8 100644 --- a/src/PhpSpreadsheet/Style/Alignment.php +++ b/src/PhpSpreadsheet/Style/Alignment.php @@ -27,26 +27,26 @@ namespace PhpSpreadsheet\Style; class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable { /* Horizontal alignment styles */ - const HORIZONTAL_GENERAL = 'general'; - const HORIZONTAL_LEFT = 'left'; - const HORIZONTAL_RIGHT = 'right'; - const HORIZONTAL_CENTER = 'center'; + const HORIZONTAL_GENERAL = 'general'; + const HORIZONTAL_LEFT = 'left'; + const HORIZONTAL_RIGHT = 'right'; + const HORIZONTAL_CENTER = 'center'; const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous'; - const HORIZONTAL_JUSTIFY = 'justify'; - const HORIZONTAL_FILL = 'fill'; - const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only + const HORIZONTAL_JUSTIFY = 'justify'; + const HORIZONTAL_FILL = 'fill'; + const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only /* Vertical alignment styles */ - const VERTICAL_BOTTOM = 'bottom'; - const VERTICAL_TOP = 'top'; - const VERTICAL_CENTER = 'center'; - const VERTICAL_JUSTIFY = 'justify'; + const VERTICAL_BOTTOM = 'bottom'; + const VERTICAL_TOP = 'top'; + const VERTICAL_CENTER = 'center'; + const VERTICAL_JUSTIFY = 'justify'; const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only /* Read order */ const READORDER_CONTEXT = 0; - const READORDER_LTR = 1; - const READORDER_RTL = 2; + const READORDER_LTR = 1; + const READORDER_RTL = 2; /** * Horizontal alignment @@ -65,45 +65,45 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable /** * Text rotation * - * @var integer + * @var int */ protected $textRotation = 0; /** * Wrap text * - * @var boolean + * @var bool */ protected $wrapText = false; /** * Shrink to fit * - * @var boolean + * @var bool */ protected $shrinkToFit = false; /** * Indent - only possible with horizontal alignment left and right * - * @var integer + * @var int */ protected $indent = 0; /** * Read order * - * @var integer + * @var int */ protected $readorder = 0; /** * Create a new Alignment * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -113,8 +113,8 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable parent::__construct($isSupervisor); if ($isConditional) { - $this->horizontal = null; - $this->vertical = null; + $this->horizontal = null; + $this->vertical = null; $this->textRotation = null; } } @@ -138,7 +138,7 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable */ public function getStyleArray($array) { - return array('alignment' => $array); + return ['alignment' => $array]; } /** @@ -189,8 +189,9 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -204,6 +205,7 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHorizontal(); } + return $this->horizontal; } @@ -220,11 +222,12 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('horizontal' => $pValue)); + $styleArray = $this->getStyleArray(['horizontal' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->horizontal = $pValue; } + return $this; } @@ -238,6 +241,7 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getVertical(); } + return $this->vertical; } @@ -254,11 +258,12 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('vertical' => $pValue)); + $styleArray = $this->getStyleArray(['vertical' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->vertical = $pValue; } + return $this; } @@ -272,6 +277,7 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getTextRotation(); } + return $this->textRotation; } @@ -292,13 +298,13 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable // Set rotation if (($pValue >= -90 && $pValue <= 90) || $pValue == -165) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('rotation' => $pValue)); + $styleArray = $this->getStyleArray(['rotation' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->textRotation = $pValue; } } else { - throw new \PhpSpreadsheet\Exception("Text rotation should be a value between -90 and 90."); + throw new \PhpSpreadsheet\Exception('Text rotation should be a value between -90 and 90.'); } return $this; @@ -307,20 +313,21 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable /** * Get Wrap Text * - * @return boolean + * @return bool */ public function getWrapText() { if ($this->isSupervisor) { return $this->getSharedComponent()->getWrapText(); } + return $this->wrapText; } /** * Set Wrap Text * - * @param boolean $pValue + * @param bool $pValue * @return Alignment */ public function setWrapText($pValue = false) @@ -329,31 +336,33 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('wrap' => $pValue)); + $styleArray = $this->getStyleArray(['wrap' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->wrapText = $pValue; } + return $this; } /** * Get Shrink to fit * - * @return boolean + * @return bool */ public function getShrinkToFit() { if ($this->isSupervisor) { return $this->getSharedComponent()->getShrinkToFit(); } + return $this->shrinkToFit; } /** * Set Shrink to fit * - * @param boolean $pValue + * @param bool $pValue * @return Alignment */ public function setShrinkToFit($pValue = false) @@ -362,11 +371,12 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('shrinkToFit' => $pValue)); + $styleArray = $this->getStyleArray(['shrinkToFit' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->shrinkToFit = $pValue; } + return $this; } @@ -380,6 +390,7 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getIndent(); } + return $this->indent; } @@ -399,24 +410,26 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable } } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('indent' => $pValue)); + $styleArray = $this->getStyleArray(['indent' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->indent = $pValue; } + return $this; } /** * Get read order * - * @return integer + * @return int */ public function getReadorder() { if ($this->isSupervisor) { return $this->getSharedComponent()->getReadorder(); } + return $this->readorder; } @@ -432,11 +445,12 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = 0; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('readorder' => $pValue)); + $styleArray = $this->getStyleArray(['readorder' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->readorder = $pValue; } + return $this; } @@ -450,6 +464,7 @@ class Alignment extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } + return md5( $this->horizontal . $this->vertical . diff --git a/src/PhpSpreadsheet/Style/Border.php b/src/PhpSpreadsheet/Style/Border.php index fef0adc0..9108b65a 100644 --- a/src/PhpSpreadsheet/Style/Border.php +++ b/src/PhpSpreadsheet/Style/Border.php @@ -27,20 +27,20 @@ namespace PhpSpreadsheet\Style; class Border extends Supervisor implements \PhpSpreadsheet\IComparable { /* Border style */ - const BORDER_NONE = 'none'; - const BORDER_DASHDOT = 'dashDot'; - const BORDER_DASHDOTDOT = 'dashDotDot'; - const BORDER_DASHED = 'dashed'; - const BORDER_DOTTED = 'dotted'; - const BORDER_DOUBLE = 'double'; - const BORDER_HAIR = 'hair'; - const BORDER_MEDIUM = 'medium'; - const BORDER_MEDIUMDASHDOT = 'mediumDashDot'; + const BORDER_NONE = 'none'; + const BORDER_DASHDOT = 'dashDot'; + const BORDER_DASHDOTDOT = 'dashDotDot'; + const BORDER_DASHED = 'dashed'; + const BORDER_DOTTED = 'dotted'; + const BORDER_DOUBLE = 'double'; + const BORDER_HAIR = 'hair'; + const BORDER_MEDIUM = 'medium'; + const BORDER_MEDIUMDASHDOT = 'mediumDashDot'; const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot'; - const BORDER_MEDIUMDASHED = 'mediumDashed'; - const BORDER_SLANTDASHDOT = 'slantDashDot'; - const BORDER_THICK = 'thick'; - const BORDER_THIN = 'thin'; + const BORDER_MEDIUMDASHED = 'mediumDashed'; + const BORDER_SLANTDASHDOT = 'slantDashDot'; + const BORDER_THICK = 'thick'; + const BORDER_THIN = 'thin'; /** * Border style @@ -66,10 +66,10 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable /** * Create a new Border * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -98,6 +98,7 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable { $this->parent = $parent; $this->parentPropertyName = $parentPropertyName; + return $this; } @@ -105,8 +106,8 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor * - * @return Border * @throws \PhpSpreadsheet\Exception + * @return Border */ public function getSharedComponent() { @@ -153,7 +154,8 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable $key = strtolower('vertical'); break; } - return $this->parent->getStyleArray(array($key => $array)); + + return $this->parent->getStyleArray([$key => $array]); } /** @@ -188,8 +190,9 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -203,31 +206,32 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getBorderStyle(); } + return $this->borderStyle; } /** * Set Border style * - * @param string|boolean $pValue + * @param string|bool $pValue * When passing a boolean, FALSE equates Border::BORDER_NONE * and TRUE to Border::BORDER_MEDIUM * @return Border */ - public function setBorderStyle($pValue = Border::BORDER_NONE) + public function setBorderStyle($pValue = self::BORDER_NONE) { - if (empty($pValue)) { - $pValue = Border::BORDER_NONE; + $pValue = self::BORDER_NONE; } elseif (is_bool($pValue) && $pValue) { - $pValue = Border::BORDER_MEDIUM; + $pValue = self::BORDER_MEDIUM; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('style' => $pValue)); + $styleArray = $this->getStyleArray(['style' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->borderStyle = $pValue; } + return $this; } @@ -254,11 +258,12 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; if ($this->isSupervisor) { - $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB())); + $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } + return $this; } @@ -272,6 +277,7 @@ class Border extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } + return md5( $this->borderStyle . $this->color->getHashCode() . diff --git a/src/PhpSpreadsheet/Style/Borders.php b/src/PhpSpreadsheet/Style/Borders.php index 6e3bf37c..6594cbb5 100644 --- a/src/PhpSpreadsheet/Style/Borders.php +++ b/src/PhpSpreadsheet/Style/Borders.php @@ -28,7 +28,7 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable { /* Diagonal directions */ const DIAGONAL_NONE = 0; - const DIAGONAL_UP = 1; + const DIAGONAL_UP = 1; const DIAGONAL_DOWN = 2; const DIAGONAL_BOTH = 3; @@ -112,10 +112,10 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable /** * Create a new Borders * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -174,7 +174,7 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable */ public function getStyleArray($array) { - return array('borders' => $array); + return ['borders' => $array]; } /** @@ -247,8 +247,9 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -305,70 +306,75 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable /** * Get AllBorders (pseudo-border). Only applies to supervisor. * - * @return Border * @throws \PhpSpreadsheet\Exception + * @return Border */ public function getAllBorders() { if (!$this->isSupervisor) { throw new \PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } + return $this->allBorders; } /** * Get Outline (pseudo-border). Only applies to supervisor. * - * @return boolean * @throws \PhpSpreadsheet\Exception + * @return bool */ public function getOutline() { if (!$this->isSupervisor) { throw new \PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } + return $this->outline; } /** * Get Inside (pseudo-border). Only applies to supervisor. * - * @return boolean * @throws \PhpSpreadsheet\Exception + * @return bool */ public function getInside() { if (!$this->isSupervisor) { throw new \PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } + return $this->inside; } /** * Get Vertical (pseudo-border). Only applies to supervisor. * - * @return Border * @throws \PhpSpreadsheet\Exception + * @return Border */ public function getVertical() { if (!$this->isSupervisor) { throw new \PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } + return $this->vertical; } /** * Get Horizontal (pseudo-border). Only applies to supervisor. * - * @return Border * @throws \PhpSpreadsheet\Exception + * @return Border */ public function getHorizontal() { if (!$this->isSupervisor) { throw new \PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } + return $this->horizontal; } @@ -382,6 +388,7 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getDiagonalDirection(); } + return $this->diagonalDirection; } @@ -397,11 +404,12 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = self::DIAGONAL_NONE; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('diagonaldirection' => $pValue)); + $styleArray = $this->getStyleArray(['diagonaldirection' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->diagonalDirection = $pValue; } + return $this; } @@ -415,6 +423,7 @@ class Borders extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashcode(); } + return md5( $this->getLeft()->getHashCode() . $this->getRight()->getHashCode() . diff --git a/src/PhpSpreadsheet/Style/Color.php b/src/PhpSpreadsheet/Style/Color.php index 8329bf22..7937536b 100644 --- a/src/PhpSpreadsheet/Style/Color.php +++ b/src/PhpSpreadsheet/Style/Color.php @@ -27,15 +27,15 @@ namespace PhpSpreadsheet\Style; class Color extends Supervisor implements \PhpSpreadsheet\IComparable { /* Colors */ - const COLOR_BLACK = 'FF000000'; - const COLOR_WHITE = 'FFFFFFFF'; - const COLOR_RED = 'FFFF0000'; - const COLOR_DARKRED = 'FF800000'; - const COLOR_BLUE = 'FF0000FF'; - const COLOR_DARKBLUE = 'FF000080'; - const COLOR_GREEN = 'FF00FF00'; - const COLOR_DARKGREEN = 'FF008000'; - const COLOR_YELLOW = 'FFFFFF00'; + const COLOR_BLACK = 'FF000000'; + const COLOR_WHITE = 'FFFFFFFF'; + const COLOR_RED = 'FFFF0000'; + const COLOR_DARKRED = 'FF800000'; + const COLOR_BLUE = 'FF0000FF'; + const COLOR_DARKBLUE = 'FF000080'; + const COLOR_GREEN = 'FF00FF00'; + const COLOR_DARKGREEN = 'FF008000'; + const COLOR_YELLOW = 'FFFFFF00'; const COLOR_DARKYELLOW = 'FF808000'; /** @@ -59,15 +59,14 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable */ protected $parentPropertyName; - /** * Create a new Color * * @param string $pARGB ARGB value for the colour - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -93,6 +92,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable { $this->parent = $parent; $this->parentPropertyName = $parentPropertyName; + return $this; } @@ -133,7 +133,8 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable $key = 'startcolor'; break; } - return $this->parent->getStyleArray(array($key => $array)); + + return $this->parent->getStyleArray([$key => $array]); } /** @@ -161,8 +162,9 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -176,6 +178,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getARGB(); } + return $this->argb; } @@ -191,11 +194,12 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = self::COLOR_BLACK; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('argb' => $pValue)); + $styleArray = $this->getStyleArray(['argb' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->argb = $pValue; } + return $this; } @@ -209,6 +213,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getRGB(); } + return substr($this->argb, 2); } @@ -224,11 +229,12 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = '000000'; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('argb' => 'FF' . $pValue)); + $styleArray = $this->getStyleArray(['argb' => 'FF' . $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->argb = 'FF' . $pValue; } + return $this; } @@ -238,7 +244,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable * @private * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param int $offset Position within the RGB value to extract - * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * @return string The extracted colour component */ @@ -248,6 +254,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable if (!$hex) { $colour = hexdec($colour); } + return $colour; } @@ -255,7 +262,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable * Get the red colour component of an RGB value * * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE - * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * @return string The red colour component */ @@ -268,7 +275,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable * Get the green colour component of an RGB value * * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE - * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * @return string The green colour component */ @@ -281,7 +288,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable * Get the blue colour component of an RGB value * * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE - * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * @return string The blue colour component */ @@ -335,6 +342,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable str_pad(dechex($green), 2, '0', 0) . str_pad(dechex($blue), 2, '0', 0) ); + return (($rgba) ? 'FF' : '') . $rgb; } @@ -342,7 +350,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable * Get indexed color * * @param int $pIndex Index entry point into the colour array - * @param boolean $background Flag to indicate whether default background or foreground colour + * @param bool $background Flag to indicate whether default background or foreground colour * should be returned if the indexed colour doesn't exist * @return Color */ @@ -354,15 +362,15 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable // Indexed colors if (is_null(self::$indexedColors)) { self::$indexedColors = [ - 1 => 'FF000000', // System Colour #1 - Black - 2 => 'FFFFFFFF', // System Colour #2 - White - 3 => 'FFFF0000', // System Colour #3 - Red - 4 => 'FF00FF00', // System Colour #4 - Green - 5 => 'FF0000FF', // System Colour #5 - Blue - 6 => 'FFFFFF00', // System Colour #6 - Yellow - 7 => 'FFFF00FF', // System Colour #7- Magenta - 8 => 'FF00FFFF', // System Colour #8- Cyan - 9 => 'FF800000', // Standard Colour #9 + 1 => 'FF000000', // System Colour #1 - Black + 2 => 'FFFFFFFF', // System Colour #2 - White + 3 => 'FFFF0000', // System Colour #3 - Red + 4 => 'FF00FF00', // System Colour #4 - Green + 5 => 'FF0000FF', // System Colour #5 - Blue + 6 => 'FFFFFF00', // System Colour #6 - Yellow + 7 => 'FFFF00FF', // System Colour #7- Magenta + 8 => 'FF00FFFF', // System Colour #8- Cyan + 9 => 'FF800000', // Standard Colour #9 10 => 'FF008000', // Standard Colour #10 11 => 'FF000080', // Standard Colour #11 12 => 'FF808000', // Standard Colour #12 @@ -409,18 +417,19 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable 53 => 'FF993300', // Standard Colour #53 54 => 'FF993366', // Standard Colour #54 55 => 'FF333399', // Standard Colour #55 - 56 => 'FF333333' // Standard Colour #56 + 56 => 'FF333333', // Standard Colour #56 ]; } if (array_key_exists($pIndex, self::$indexedColors)) { - return new Color(self::$indexedColors[$pIndex]); + return new self(self::$indexedColors[$pIndex]); } if ($background) { - return new Color(self::COLOR_WHITE); + return new self(self::COLOR_WHITE); } - return new Color(self::COLOR_BLACK); + + return new self(self::COLOR_BLACK); } /** @@ -433,6 +442,7 @@ class Color extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } + return md5( $this->argb . __CLASS__ diff --git a/src/PhpSpreadsheet/Style/Conditional.php b/src/PhpSpreadsheet/Style/Conditional.php index a6c738e0..d1523720 100644 --- a/src/PhpSpreadsheet/Style/Conditional.php +++ b/src/PhpSpreadsheet/Style/Conditional.php @@ -27,24 +27,24 @@ namespace PhpSpreadsheet\Style; class Conditional implements \PhpSpreadsheet\IComparable { /* Condition types */ - const CONDITION_NONE = 'none'; - const CONDITION_CELLIS = 'cellIs'; + const CONDITION_NONE = 'none'; + const CONDITION_CELLIS = 'cellIs'; const CONDITION_CONTAINSTEXT = 'containsText'; - const CONDITION_EXPRESSION = 'expression'; + const CONDITION_EXPRESSION = 'expression'; /* Operator types */ - const OPERATOR_NONE = ''; - const OPERATOR_BEGINSWITH = 'beginsWith'; - const OPERATOR_ENDSWITH = 'endsWith'; - const OPERATOR_EQUAL = 'equal'; - const OPERATOR_GREATERTHAN = 'greaterThan'; + const OPERATOR_NONE = ''; + const OPERATOR_BEGINSWITH = 'beginsWith'; + const OPERATOR_ENDSWITH = 'endsWith'; + const OPERATOR_EQUAL = 'equal'; + const OPERATOR_GREATERTHAN = 'greaterThan'; const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; - const OPERATOR_LESSTHAN = 'lessThan'; - const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; - const OPERATOR_NOTEQUAL = 'notEqual'; - const OPERATOR_CONTAINSTEXT = 'containsText'; - const OPERATOR_NOTCONTAINS = 'notContains'; - const OPERATOR_BETWEEN = 'between'; + const OPERATOR_LESSTHAN = 'lessThan'; + const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; + const OPERATOR_NOTEQUAL = 'notEqual'; + const OPERATOR_CONTAINSTEXT = 'containsText'; + const OPERATOR_NOTCONTAINS = 'notContains'; + const OPERATOR_BETWEEN = 'between'; /** * Condition type @@ -72,7 +72,7 @@ class Conditional implements \PhpSpreadsheet\IComparable * * @var string[] */ - private $condition = array(); + private $condition = []; /** * Style @@ -88,10 +88,10 @@ class Conditional implements \PhpSpreadsheet\IComparable { // Initialise values $this->conditionType = self::CONDITION_NONE; - $this->operatorType = self::OPERATOR_NONE; - $this->text = null; - $this->condition = array(); - $this->style = new \PhpSpreadsheet\Style(false, true); + $this->operatorType = self::OPERATOR_NONE; + $this->text = null; + $this->condition = []; + $this->style = new \PhpSpreadsheet\Style(false, true); } /** @@ -113,6 +113,7 @@ class Conditional implements \PhpSpreadsheet\IComparable public function setConditionType($pValue = self::CONDITION_NONE) { $this->conditionType = $pValue; + return $this; } @@ -135,6 +136,7 @@ class Conditional implements \PhpSpreadsheet\IComparable public function setOperatorType($pValue = self::OPERATOR_NONE) { $this->operatorType = $pValue; + return $this; } @@ -157,6 +159,7 @@ class Conditional implements \PhpSpreadsheet\IComparable public function setText($value = null) { $this->text = $value; + return $this; } @@ -185,7 +188,7 @@ class Conditional implements \PhpSpreadsheet\IComparable public function setCondition($pValue = '') { if (!is_array($pValue)) { - $pValue = array($pValue); + $pValue = [$pValue]; } return $this->setConditions($pValue); @@ -210,9 +213,10 @@ class Conditional implements \PhpSpreadsheet\IComparable public function setConditions($pValue) { if (!is_array($pValue)) { - $pValue = array($pValue); + $pValue = [$pValue]; } $this->condition = $pValue; + return $this; } @@ -225,6 +229,7 @@ class Conditional implements \PhpSpreadsheet\IComparable public function addCondition($pValue = '') { $this->condition[] = $pValue; + return $this; } @@ -247,8 +252,9 @@ class Conditional implements \PhpSpreadsheet\IComparable */ public function setStyle(\PhpSpreadsheet\Style $pValue = null) { - $this->style = $pValue; - return $this; + $this->style = $pValue; + + return $this; } /** diff --git a/src/PhpSpreadsheet/Style/Fill.php b/src/PhpSpreadsheet/Style/Fill.php index afa6b448..507f5554 100644 --- a/src/PhpSpreadsheet/Style/Fill.php +++ b/src/PhpSpreadsheet/Style/Fill.php @@ -27,27 +27,27 @@ namespace PhpSpreadsheet\Style; class Fill extends Supervisor implements \PhpSpreadsheet\IComparable { /* Fill types */ - const FILL_NONE = 'none'; - const FILL_SOLID = 'solid'; - const FILL_GRADIENT_LINEAR = 'linear'; - const FILL_GRADIENT_PATH = 'path'; - const FILL_PATTERN_DARKDOWN = 'darkDown'; - const FILL_PATTERN_DARKGRAY = 'darkGray'; - const FILL_PATTERN_DARKGRID = 'darkGrid'; - const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal'; - const FILL_PATTERN_DARKTRELLIS = 'darkTrellis'; - const FILL_PATTERN_DARKUP = 'darkUp'; - const FILL_PATTERN_DARKVERTICAL = 'darkVertical'; - const FILL_PATTERN_GRAY0625 = 'gray0625'; - const FILL_PATTERN_GRAY125 = 'gray125'; - const FILL_PATTERN_LIGHTDOWN = 'lightDown'; - const FILL_PATTERN_LIGHTGRAY = 'lightGray'; - const FILL_PATTERN_LIGHTGRID = 'lightGrid'; + const FILL_NONE = 'none'; + const FILL_SOLID = 'solid'; + const FILL_GRADIENT_LINEAR = 'linear'; + const FILL_GRADIENT_PATH = 'path'; + const FILL_PATTERN_DARKDOWN = 'darkDown'; + const FILL_PATTERN_DARKGRAY = 'darkGray'; + const FILL_PATTERN_DARKGRID = 'darkGrid'; + const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal'; + const FILL_PATTERN_DARKTRELLIS = 'darkTrellis'; + const FILL_PATTERN_DARKUP = 'darkUp'; + const FILL_PATTERN_DARKVERTICAL = 'darkVertical'; + const FILL_PATTERN_GRAY0625 = 'gray0625'; + const FILL_PATTERN_GRAY125 = 'gray125'; + const FILL_PATTERN_LIGHTDOWN = 'lightDown'; + const FILL_PATTERN_LIGHTGRAY = 'lightGray'; + const FILL_PATTERN_LIGHTGRID = 'lightGrid'; const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal'; - const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis'; - const FILL_PATTERN_LIGHTUP = 'lightUp'; - const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical'; - const FILL_PATTERN_MEDIUMGRAY = 'mediumGray'; + const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis'; + const FILL_PATTERN_LIGHTUP = 'lightUp'; + const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical'; + const FILL_PATTERN_MEDIUMGRAY = 'mediumGray'; /** * Fill type @@ -59,7 +59,7 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable /** * Rotation * - * @var double + * @var float */ protected $rotation = 0; @@ -80,10 +80,10 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable /** * Create a new Fill * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -125,7 +125,7 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable */ public function getStyleArray($array) { - return array('fill' => $array); + return ['fill' => $array]; } /** @@ -173,8 +173,9 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -188,6 +189,7 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getFillType(); } + return $this->fillType; } @@ -197,44 +199,47 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable * @param string $pValue Fill type * @return Fill */ - public function setFillType($pValue = Fill::FILL_NONE) + public function setFillType($pValue = self::FILL_NONE) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('type' => $pValue)); + $styleArray = $this->getStyleArray(['type' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->fillType = $pValue; } + return $this; } /** * Get Rotation * - * @return double + * @return float */ public function getRotation() { if ($this->isSupervisor) { return $this->getSharedComponent()->getRotation(); } + return $this->rotation; } /** * Set Rotation * - * @param double $pValue + * @param float $pValue * @return Fill */ public function setRotation($pValue = 0) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('rotation' => $pValue)); + $styleArray = $this->getStyleArray(['rotation' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->rotation = $pValue; } + return $this; } @@ -261,11 +266,12 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; if ($this->isSupervisor) { - $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB())); + $styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->startColor = $color; } + return $this; } @@ -292,11 +298,12 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; if ($this->isSupervisor) { - $styleArray = $this->getEndColor()->getStyleArray(array('argb' => $color->getARGB())); + $styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->endColor = $color; } + return $this; } @@ -310,6 +317,7 @@ class Fill extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } + return md5( $this->getFillType() . $this->getRotation() . diff --git a/src/PhpSpreadsheet/Style/Font.php b/src/PhpSpreadsheet/Style/Font.php index 97075fe4..4f9e706e 100644 --- a/src/PhpSpreadsheet/Style/Font.php +++ b/src/PhpSpreadsheet/Style/Font.php @@ -27,10 +27,10 @@ namespace PhpSpreadsheet\Style; class Font extends Supervisor implements \PhpSpreadsheet\IComparable { /* Underline types */ - const UNDERLINE_NONE = 'none'; - const UNDERLINE_DOUBLE = 'double'; + const UNDERLINE_NONE = 'none'; + const UNDERLINE_DOUBLE = 'double'; const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting'; - const UNDERLINE_SINGLE = 'single'; + const UNDERLINE_SINGLE = 'single'; const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting'; /** @@ -50,28 +50,28 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable /** * Bold * - * @var boolean + * @var bool */ protected $bold = false; /** * Italic * - * @var boolean + * @var bool */ protected $italic = false; /** * Superscript * - * @var boolean + * @var bool */ protected $superScript = false; /** * Subscript * - * @var boolean + * @var bool */ protected $subScript = false; @@ -85,7 +85,7 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable /** * Strikethrough * - * @var boolean + * @var bool */ protected $strikethrough = false; @@ -99,10 +99,10 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable /** * Create a new Font * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -150,7 +150,7 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable */ public function getStyleArray($array) { - return array('font' => $array); + return ['font' => $array]; } /** @@ -210,8 +210,9 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -225,6 +226,7 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getName(); } + return $this->name; } @@ -240,31 +242,33 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = 'Calibri'; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('name' => $pValue)); + $styleArray = $this->getStyleArray(['name' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->name = $pValue; } + return $this; } /** * Get Size * - * @return double + * @return float */ public function getSize() { if ($this->isSupervisor) { return $this->getSharedComponent()->getSize(); } + return $this->size; } /** * Set Size * - * @param double $pValue + * @param float $pValue * @return Font */ public function setSize($pValue = 10) @@ -273,31 +277,33 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = 10; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('size' => $pValue)); + $styleArray = $this->getStyleArray(['size' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->size = $pValue; } + return $this; } /** * Get Bold * - * @return boolean + * @return bool */ public function getBold() { if ($this->isSupervisor) { return $this->getSharedComponent()->getBold(); } + return $this->bold; } /** * Set Bold * - * @param boolean $pValue + * @param bool $pValue * @return Font */ public function setBold($pValue = false) @@ -306,31 +312,33 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('bold' => $pValue)); + $styleArray = $this->getStyleArray(['bold' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->bold = $pValue; } + return $this; } /** * Get Italic * - * @return boolean + * @return bool */ public function getItalic() { if ($this->isSupervisor) { return $this->getSharedComponent()->getItalic(); } + return $this->italic; } /** * Set Italic * - * @param boolean $pValue + * @param bool $pValue * @return Font */ public function setItalic($pValue = false) @@ -339,31 +347,33 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('italic' => $pValue)); + $styleArray = $this->getStyleArray(['italic' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->italic = $pValue; } + return $this; } /** * Get SuperScript * - * @return boolean + * @return bool */ public function getSuperScript() { if ($this->isSupervisor) { return $this->getSharedComponent()->getSuperScript(); } + return $this->superScript; } /** * Set SuperScript * - * @param boolean $pValue + * @param bool $pValue * @return Font */ public function setSuperScript($pValue = false) @@ -372,32 +382,34 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('superScript' => $pValue)); + $styleArray = $this->getStyleArray(['superScript' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->superScript = $pValue; $this->subScript = !$pValue; } + return $this; } - /** + /** * Get SubScript * - * @return boolean + * @return bool */ public function getSubScript() { if ($this->isSupervisor) { return $this->getSharedComponent()->getSubScript(); } + return $this->subScript; } /** * Set SubScript * - * @param boolean $pValue + * @param bool $pValue * @return Font */ public function setSubScript($pValue = false) @@ -406,12 +418,13 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('subScript' => $pValue)); + $styleArray = $this->getStyleArray(['subScript' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->subScript = $pValue; $this->superScript = !$pValue; } + return $this; } @@ -425,13 +438,14 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getUnderline(); } + return $this->underline; } /** * Set Underline * - * @param string|boolean $pValue \PhpSpreadsheet\Style\Font underline type + * @param string|bool $pValue \PhpSpreadsheet\Style\Font underline type * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE, * false equates to UNDERLINE_NONE * @return Font @@ -444,31 +458,33 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = self::UNDERLINE_NONE; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('underline' => $pValue)); + $styleArray = $this->getStyleArray(['underline' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->underline = $pValue; } + return $this; } /** * Get Strikethrough * - * @return boolean + * @return bool */ public function getStrikethrough() { if ($this->isSupervisor) { return $this->getSharedComponent()->getStrikethrough(); } + return $this->strikethrough; } /** * Set Strikethrough * - * @param boolean $pValue + * @param bool $pValue * @return Font */ public function setStrikethrough($pValue = false) @@ -477,11 +493,12 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $pValue = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('strike' => $pValue)); + $styleArray = $this->getStyleArray(['strike' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->strikethrough = $pValue; } + return $this; } @@ -508,11 +525,12 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; if ($this->isSupervisor) { - $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB())); + $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } + return $this; } @@ -526,6 +544,7 @@ class Font extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } + return md5( $this->name . $this->size . diff --git a/src/PhpSpreadsheet/Style/NumberFormat.php b/src/PhpSpreadsheet/Style/NumberFormat.php index 098be074..3588cfc5 100644 --- a/src/PhpSpreadsheet/Style/NumberFormat.php +++ b/src/PhpSpreadsheet/Style/NumberFormat.php @@ -29,44 +29,44 @@ namespace PhpSpreadsheet\Style; class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable { /* Pre-defined formats */ - const FORMAT_GENERAL = 'General'; + const FORMAT_GENERAL = 'General'; - const FORMAT_TEXT = '@'; + const FORMAT_TEXT = '@'; - const FORMAT_NUMBER = '0'; - const FORMAT_NUMBER_00 = '0.00'; + const FORMAT_NUMBER = '0'; + const FORMAT_NUMBER_00 = '0.00'; const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00'; const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-'; - const FORMAT_PERCENTAGE = '0%'; - const FORMAT_PERCENTAGE_00 = '0.00%'; + const FORMAT_PERCENTAGE = '0%'; + const FORMAT_PERCENTAGE_00 = '0.00%'; - const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd'; - const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd'; - const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy'; - const FORMAT_DATE_DMYSLASH = 'd/m/y'; - const FORMAT_DATE_DMYMINUS = 'd-m-y'; - const FORMAT_DATE_DMMINUS = 'd-m'; - const FORMAT_DATE_MYMINUS = 'm-y'; - const FORMAT_DATE_XLSX14 = 'mm-dd-yy'; - const FORMAT_DATE_XLSX15 = 'd-mmm-yy'; - const FORMAT_DATE_XLSX16 = 'd-mmm'; - const FORMAT_DATE_XLSX17 = 'mmm-yy'; - const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm'; - const FORMAT_DATE_DATETIME = 'd/m/y h:mm'; - const FORMAT_DATE_TIME1 = 'h:mm AM/PM'; - const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM'; - const FORMAT_DATE_TIME3 = 'h:mm'; - const FORMAT_DATE_TIME4 = 'h:mm:ss'; - const FORMAT_DATE_TIME5 = 'mm:ss'; - const FORMAT_DATE_TIME6 = 'h:mm:ss'; - const FORMAT_DATE_TIME7 = 'i:s.S'; - const FORMAT_DATE_TIME8 = 'h:mm:ss;@'; - const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@'; + const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd'; + const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd'; + const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy'; + const FORMAT_DATE_DMYSLASH = 'd/m/y'; + const FORMAT_DATE_DMYMINUS = 'd-m-y'; + const FORMAT_DATE_DMMINUS = 'd-m'; + const FORMAT_DATE_MYMINUS = 'm-y'; + const FORMAT_DATE_XLSX14 = 'mm-dd-yy'; + const FORMAT_DATE_XLSX15 = 'd-mmm-yy'; + const FORMAT_DATE_XLSX16 = 'd-mmm'; + const FORMAT_DATE_XLSX17 = 'mmm-yy'; + const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm'; + const FORMAT_DATE_DATETIME = 'd/m/y h:mm'; + const FORMAT_DATE_TIME1 = 'h:mm AM/PM'; + const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM'; + const FORMAT_DATE_TIME3 = 'h:mm'; + const FORMAT_DATE_TIME4 = 'h:mm:ss'; + const FORMAT_DATE_TIME5 = 'mm:ss'; + const FORMAT_DATE_TIME6 = 'h:mm:ss'; + const FORMAT_DATE_TIME7 = 'i:s.S'; + const FORMAT_DATE_TIME8 = 'h:mm:ss;@'; + const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@'; - const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-'; - const FORMAT_CURRENCY_USD = '$#,##0_-'; - const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-'; + const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-'; + const FORMAT_CURRENCY_USD = '$#,##0_-'; + const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-'; /** * Excel built-in number formats @@ -94,15 +94,15 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable * * @var string */ - protected $builtInFormatCode = 0; + protected $builtInFormatCode = 0; /** * Create a new NumberFormat * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -136,7 +136,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable */ public function getStyleArray($array) { - return array('numberformat' => $array); + return ['numberformat' => $array]; } /** @@ -165,8 +165,9 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -183,6 +184,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->builtInFormatCode !== false) { return self::builtInFormatCode($this->builtInFormatCode); } + return $this->formatCode; } @@ -192,18 +194,19 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable * @param string $pValue * @return NumberFormat */ - public function setFormatCode($pValue = NumberFormat::FORMAT_GENERAL) + public function setFormatCode($pValue = self::FORMAT_GENERAL) { if ($pValue == '') { - $pValue = NumberFormat::FORMAT_GENERAL; + $pValue = self::FORMAT_GENERAL; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('code' => $pValue)); + $styleArray = $this->getStyleArray(['code' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->formatCode = $pValue; $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue); } + return $this; } @@ -217,6 +220,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getBuiltInFormatCode(); } + return $this->builtInFormatCode; } @@ -228,14 +232,14 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable */ public function setBuiltInFormatCode($pValue = 0) { - if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue))); + $styleArray = $this->getStyleArray(['code' => self::builtInFormatCode($pValue)]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->builtInFormatCode = $pValue; $this->formatCode = self::builtInFormatCode($pValue); } + return $this; } @@ -268,10 +272,10 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable // Built-in format codes if (is_null(self::$builtInFormats)) { - self::$builtInFormats = array(); + self::$builtInFormats = []; // General - self::$builtInFormats[0] = NumberFormat::FORMAT_GENERAL; + self::$builtInFormats[0] = self::FORMAT_GENERAL; self::$builtInFormats[1] = '0'; self::$builtInFormats[2] = '0.00'; self::$builtInFormats[3] = '#,##0'; @@ -352,7 +356,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable * Get built-in format code index * * @param string $formatCode - * @return int|boolean + * @return int|bool */ public static function builtInFormatCodeIndex($formatCode) { @@ -377,6 +381,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } + return md5( $this->formatCode . $this->builtInFormatCode . @@ -389,62 +394,62 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable * * @var array */ - private static $dateFormatReplacements = array( + private static $dateFormatReplacements = [ // first remove escapes related to non-format characters - '\\' => '', + '\\' => '', // 12-hour suffix 'am/pm' => 'A', // 4-digit year - 'e' => 'Y', - 'yyyy' => 'Y', + 'e' => 'Y', + 'yyyy' => 'Y', // 2-digit year - 'yy' => 'y', + 'yy' => 'y', // first letter of month - no php equivalent 'mmmmm' => 'M', // full month name - 'mmmm' => 'F', + 'mmmm' => 'F', // short month name - 'mmm' => 'M', + 'mmm' => 'M', // mm is minutes if time, but can also be month w/leading zero // so we try to identify times be the inclusion of a : separator in the mask // It isn't perfect, but the best way I know how - ':mm' => ':i', - 'mm:' => 'i:', + ':mm' => ':i', + 'mm:' => 'i:', // month leading zero - 'mm' => 'm', + 'mm' => 'm', // month no leading zero - 'm' => 'n', + 'm' => 'n', // full day of week name - 'dddd' => 'l', + 'dddd' => 'l', // short day of week name - 'ddd' => 'D', + 'ddd' => 'D', // days leading zero - 'dd' => 'd', + 'dd' => 'd', // days no leading zero - 'd' => 'j', + 'd' => 'j', // seconds - 'ss' => 's', + 'ss' => 's', // fractional seconds - no php equivalent - '.s' => '' - ); + '.s' => '', + ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock) * * @var array */ - private static $dateFormatReplacements24 = array( + private static $dateFormatReplacements24 = [ 'hh' => 'H', - 'h' => 'G' - ); + 'h' => 'G', + ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock) * * @var array */ - private static $dateFormatReplacements12 = array( + private static $dateFormatReplacements12 = [ 'hh' => 'h', - 'h' => 'g' - ); + 'h' => 'g', + ]; private static function setLowercaseCallback($matches) { @@ -519,8 +524,8 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable $GCD = \PhpSpreadsheet\Calculation\MathTrig::GCD($decimalPart, $decimalDivisor); - $adjustedDecimalPart = $decimalPart/$GCD; - $adjustedDecimalDivisor = $decimalDivisor/$GCD; + $adjustedDecimalPart = $decimalPart / $GCD; + $adjustedDecimalDivisor = $decimalDivisor / $GCD; if ((strpos($format, '0') !== false) || (strpos($format, '#') !== false) || (substr($format, 0, 3) == '? ?')) { if ($integerPart == 0) { @@ -542,6 +547,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable $masks = explode('.', $mask . '.0'); $result1 = self::complexNumberFormatMask($numbers[0], $masks[0], 1); $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), 1)); + return (($sign) ? '-' : '') . $result1 . '.' . $result2; } @@ -580,7 +586,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable * @param array $callBack Callback function for additional formatting of string * @return string Formatted string */ - public static function toFormattedString($value = '0', $format = NumberFormat::FORMAT_GENERAL, $callBack = null) + public static function toFormattedString($value = '0', $format = self::FORMAT_GENERAL, $callBack = null) { // For now we do not treat strings although section 4 of a format code affects strings if (!is_numeric($value)) { @@ -589,7 +595,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, // it seems to round numbers to a total of 10 digits. - if (($format === NumberFormat::FORMAT_GENERAL) || ($format === NumberFormat::FORMAT_TEXT)) { + if (($format === self::FORMAT_GENERAL) || ($format === self::FORMAT_TEXT)) { return $value; } @@ -616,13 +622,13 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable break; case 3: $format = ($value > 0) ? - $sections[0] : ( ($value < 0) ? + $sections[0] : (($value < 0) ? $sections[1] : $sections[2]); $value = abs($value); // Use the absolute value break; case 4: $format = ($value > 0) ? - $sections[0] : ( ($value < 0) ? + $sections[0] : (($value < 0) ? $sections[1] : $sections[2]); $value = abs($value); // Use the absolute value break; @@ -657,7 +663,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable $value = 'EUR ' . sprintf('%1.2f', $value); } else { // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols - $format = str_replace(array('"', '*'), '', $format); + $format = str_replace(['"', '*'], '', $format); // Find out if we need thousands separator // This is indicated by a comma enclosed by a digit placeholder: @@ -672,7 +678,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable // This is indicated by a number of commas after a digit placeholder: // #, or 0.0,, $scale = 1; // same as no scale - $matches = array(); + $matches = []; if (preg_match('/(#|0)(,+)/', $format, $matches)) { $scale = pow(1000, strlen($matches[2])); @@ -683,7 +689,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable if (preg_match('/#?.*\?\/\?/', $format, $m)) { //echo 'Format mask is fractional '.$format.'
'; - if ($value != (int)$value) { + if ($value != (int) $value) { self::formatAsFraction($value, $format); } } else { @@ -720,7 +726,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable } elseif (preg_match('/0([^\d\.]+)0/', $format)) { $value = self::complexNumberFormatMask($value, $format); } else { - $sprintf_pattern = "%0$minWidth." . strlen($right) . "f"; + $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f'; $value = sprintf($sprintf_pattern, $value); $value = preg_replace($number_regex, $value, $format); } @@ -741,7 +747,7 @@ class NumberFormat extends Supervisor implements \PhpSpreadsheet\IComparable } // Escape any escaped slashes to a single slash - $format = preg_replace("/\\\\/u", '\\', $format); + $format = preg_replace('/\\\\/u', '\\', $format); // Additional formatting provided by callback function if ($callBack !== null) { diff --git a/src/PhpSpreadsheet/Style/Protection.php b/src/PhpSpreadsheet/Style/Protection.php index f30ad6d7..44a9f51c 100644 --- a/src/PhpSpreadsheet/Style/Protection.php +++ b/src/PhpSpreadsheet/Style/Protection.php @@ -27,9 +27,9 @@ namespace PhpSpreadsheet\Style; class Protection extends Supervisor implements \PhpSpreadsheet\IComparable { /** Protection styles */ - const PROTECTION_INHERIT = 'inherit'; - const PROTECTION_PROTECTED = 'protected'; - const PROTECTION_UNPROTECTED = 'unprotected'; + const PROTECTION_INHERIT = 'inherit'; + const PROTECTION_PROTECTED = 'protected'; + const PROTECTION_UNPROTECTED = 'unprotected'; /** * Locked @@ -48,10 +48,10 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable /** * Create a new Protection * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param boolean $isConditional Flag indicating if this is a conditional style or not + * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -86,7 +86,7 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable */ public function getStyleArray($array) { - return array('protection' => $array); + return ['protection' => $array]; } /** @@ -119,8 +119,9 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable } } } else { - throw new \PhpSpreadsheet\Exception("Invalid style array passed."); + throw new \PhpSpreadsheet\Exception('Invalid style array passed.'); } + return $this; } @@ -134,6 +135,7 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getLocked(); } + return $this->locked; } @@ -146,11 +148,12 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable public function setLocked($pValue = self::PROTECTION_INHERIT) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('locked' => $pValue)); + $styleArray = $this->getStyleArray(['locked' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->locked = $pValue; } + return $this; } @@ -164,6 +167,7 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHidden(); } + return $this->hidden; } @@ -176,11 +180,12 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable public function setHidden($pValue = self::PROTECTION_INHERIT) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(array('hidden' => $pValue)); + $styleArray = $this->getStyleArray(['hidden' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->hidden = $pValue; } + return $this; } @@ -194,6 +199,7 @@ class Protection extends Supervisor implements \PhpSpreadsheet\IComparable if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } + return md5( $this->locked . $this->hidden . diff --git a/src/PhpSpreadsheet/Style/Supervisor.php b/src/PhpSpreadsheet/Style/Supervisor.php index 15a4e5b4..c924b5b9 100644 --- a/src/PhpSpreadsheet/Style/Supervisor.php +++ b/src/PhpSpreadsheet/Style/Supervisor.php @@ -29,7 +29,7 @@ abstract class Supervisor /** * Supervisor? * - * @var boolean + * @var bool */ protected $isSupervisor; @@ -43,7 +43,7 @@ abstract class Supervisor /** * Create a new Supervisor * - * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are */ @@ -62,13 +62,14 @@ abstract class Supervisor public function bindParent($parent, $parentPropertyName = null) { $this->parent = $parent; + return $this; } /** * Is this a supervisor or a cell style component? * - * @return boolean + * @return bool */ public function getIsSupervisor() { diff --git a/src/PhpSpreadsheet/Worksheet.php b/src/PhpSpreadsheet/Worksheet.php index 7dc45d31..c2aff429 100644 --- a/src/PhpSpreadsheet/Worksheet.php +++ b/src/PhpSpreadsheet/Worksheet.php @@ -29,13 +29,13 @@ namespace PhpSpreadsheet; class Worksheet implements IComparable { /* Break types */ - const BREAK_NONE = 0; - const BREAK_ROW = 1; + const BREAK_NONE = 0; + const BREAK_ROW = 1; const BREAK_COLUMN = 2; /* Sheet state */ - const SHEETSTATE_VISIBLE = 'visible'; - const SHEETSTATE_HIDDEN = 'hidden'; + const SHEETSTATE_VISIBLE = 'visible'; + const SHEETSTATE_HIDDEN = 'hidden'; const SHEETSTATE_VERYHIDDEN = 'veryHidden'; /** @@ -43,7 +43,7 @@ class Worksheet implements IComparable * * @var array */ - private static $invalidCharacters = array('*', ':', '/', '\\', '?', '[', ']'); + private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']']; /** * Parent spreadsheet @@ -64,7 +64,7 @@ class Worksheet implements IComparable * * @var Worksheet\RowDimension[] */ - private $rowDimensions = array(); + private $rowDimensions = []; /** * Default row dimension @@ -78,7 +78,7 @@ class Worksheet implements IComparable * * @var Worksheet\ColumnDimension[] */ - private $columnDimensions = array(); + private $columnDimensions = []; /** * Default column dimension @@ -99,7 +99,7 @@ class Worksheet implements IComparable * * @var Chart[] */ - private $chartCollection = array(); + private $chartCollection = []; /** * Worksheet title @@ -155,19 +155,19 @@ class Worksheet implements IComparable * * @var Style[] */ - private $styles = array(); + private $styles = []; /** * Conditional styles. Indexed by cell coordinate, e.g. 'A1' * * @var array */ - private $conditionalStylesCollection = array(); + private $conditionalStylesCollection = []; /** * Is the current cell collection sorted already? * - * @var boolean + * @var bool */ private $cellCollectionIsSorted = false; @@ -176,21 +176,21 @@ class Worksheet implements IComparable * * @var array */ - private $breaks = array(); + private $breaks = []; /** * Collection of merged cell ranges * * @var array */ - private $mergeCells = array(); + private $mergeCells = []; /** * Collection of protected cell ranges * * @var array */ - private $protectedCells = array(); + private $protectedCells = []; /** * Autofilter Range and selection @@ -209,35 +209,35 @@ class Worksheet implements IComparable /** * Show gridlines? * - * @var boolean + * @var bool */ private $showGridlines = true; /** - * Print gridlines? - * - * @var boolean - */ + * Print gridlines? + * + * @var bool + */ private $printGridlines = false; /** - * Show row and column headers? - * - * @var boolean - */ + * Show row and column headers? + * + * @var bool + */ private $showRowColHeaders = true; /** * Show summary below? (Row/Column outline) * - * @var boolean + * @var bool */ private $showSummaryBelow = true; /** * Show summary right? (Row/Column outline) * - * @var boolean + * @var bool */ private $showSummaryRight = true; @@ -246,7 +246,7 @@ class Worksheet implements IComparable * * @var Comment[] */ - private $comments = array(); + private $comments = []; /** * Active cell. (Only one!) @@ -279,7 +279,7 @@ class Worksheet implements IComparable /** * Right-to-left? * - * @var boolean + * @var bool */ private $rightToLeft = false; @@ -288,14 +288,14 @@ class Worksheet implements IComparable * * @var array */ - private $hyperlinkCollection = array(); + private $hyperlinkCollection = []; /** * Data validation objects. Indexed by cell coordinate, e.g. 'A1' * * @var array */ - private $dataValidationCollection = array(); + private $dataValidationCollection = []; /** * Tab color @@ -307,7 +307,7 @@ class Worksheet implements IComparable /** * Dirty flag * - * @var boolean + * @var bool */ private $dirty = true; @@ -319,10 +319,10 @@ class Worksheet implements IComparable private $hash; /** - * CodeName - * - * @var string - */ + * CodeName + * + * @var string + */ private $codeName = null; /** @@ -338,35 +338,33 @@ class Worksheet implements IComparable $this->setTitle($pTitle, false); // setTitle can change $pTitle $this->setCodeName($this->getTitle()); - $this->setSheetState(Worksheet::SHEETSTATE_VISIBLE); + $this->setSheetState(self::SHEETSTATE_VISIBLE); - $this->cellCollection = CachedObjectStorageFactory::getInstance($this); + $this->cellCollection = CachedObjectStorageFactory::getInstance($this); // Set page setup - $this->pageSetup = new Worksheet\PageSetup(); + $this->pageSetup = new Worksheet\PageSetup(); // Set page margins - $this->pageMargins = new Worksheet\PageMargins(); + $this->pageMargins = new Worksheet\PageMargins(); // Set page header/footer - $this->headerFooter = new Worksheet\HeaderFooter(); + $this->headerFooter = new Worksheet\HeaderFooter(); // Set sheet view - $this->sheetView = new Worksheet\SheetView(); + $this->sheetView = new Worksheet\SheetView(); // Drawing collection - $this->drawingCollection = new \ArrayObject(); + $this->drawingCollection = new \ArrayObject(); // Chart collection - $this->chartCollection = new \ArrayObject(); + $this->chartCollection = new \ArrayObject(); // Protection - $this->protection = new Worksheet\Protection(); + $this->protection = new Worksheet\Protection(); // Default row dimension - $this->defaultRowDimension = new Worksheet\RowDimension(null); + $this->defaultRowDimension = new Worksheet\RowDimension(null); // Default column dimension $this->defaultColumnDimension = new Worksheet\ColumnDimension(null); - $this->autoFilter = new Worksheet\AutoFilter(null, $this); + $this->autoFilter = new Worksheet\AutoFilter(null, $this); } - /** * Disconnect all cells from this Worksheet object, * typically so that the worksheet object can be unset - * */ public function disconnectCells() { @@ -380,7 +378,6 @@ class Worksheet implements IComparable /** * Code to execute when this worksheet is unset() - * */ public function __destruct() { @@ -389,7 +386,7 @@ class Worksheet implements IComparable $this->disconnectCells(); } - /** + /** * Return the cache controller for the cell collection * * @return CachedObjectStorage_xxx @@ -399,7 +396,6 @@ class Worksheet implements IComparable return $this->cellCollection; } - /** * Get array of invalid characters for sheet title * @@ -414,8 +410,8 @@ class Worksheet implements IComparable * Check sheet code name for valid Excel syntax * * @param string $pValue The string to check - * @return string The valid string * @throws Exception + * @return string The valid string */ private static function checkSheetCodeName($pValue) { @@ -425,8 +421,8 @@ class Worksheet implements IComparable } // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) || - (Shared\StringHelper::substring($pValue, -1, 1)=='\'') || - (Shared\StringHelper::substring($pValue, 0, 1)=='\'')) { + (Shared\StringHelper::substring($pValue, -1, 1) == '\'') || + (Shared\StringHelper::substring($pValue, 0, 1) == '\'')) { throw new Exception('Invalid character found in sheet code name'); } @@ -438,12 +434,12 @@ class Worksheet implements IComparable return $pValue; } - /** + /** * Check sheet title for valid Excel syntax * * @param string $pValue The string to check - * @return string The valid string * @throws Exception + * @return string The valid string */ private static function checkSheetTitle($pValue) { @@ -463,7 +459,7 @@ class Worksheet implements IComparable /** * Get collection of cells * - * @param boolean $pSorted Also sort the cell collection? + * @param bool $pSorted Also sort the cell collection? * @return Cell[] */ public function getCellCollection($pSorted = true) @@ -475,7 +471,8 @@ class Worksheet implements IComparable if ($this->cellCollection !== null) { return $this->cellCollection->getCellList(); } - return array(); + + return []; } /** @@ -488,7 +485,8 @@ class Worksheet implements IComparable if ($this->cellCollection !== null) { return $this->cellCollection->getSortedCellList(); } - return array(); + + return []; } /** @@ -565,7 +563,7 @@ class Worksheet implements IComparable $this->chartCollection[] = $pChart; } else { // Insert the chart at the requested index - array_splice($this->chartCollection, $iChartIndex, 0, array($pChart)); + array_splice($this->chartCollection, $iChartIndex, 0, [$pChart]); } return $pChart; @@ -585,8 +583,8 @@ class Worksheet implements IComparable * Get a chart by its index position * * @param string $index Chart index position - * @return false|Chart * @throws Exception + * @return false|Chart */ public function getChartByIndex($index = null) { @@ -607,15 +605,16 @@ class Worksheet implements IComparable /** * Return an array of the names of charts on this worksheet * - * @return string[] The names of charts * @throws Exception + * @return string[] The names of charts */ public function getChartNames() { - $chartNames = array(); + $chartNames = []; foreach ($this->chartCollection as $chart) { $chartNames[] = $chart->getName(); } + return $chartNames; } @@ -623,8 +622,8 @@ class Worksheet implements IComparable * Get a chart by name * * @param string $chartName Chart name - * @return false|Chart * @throws Exception + * @return false|Chart */ public function getChartByName($chartName = '') { @@ -637,6 +636,7 @@ class Worksheet implements IComparable return $this->chartCollection[$index]; } } + return false; } @@ -648,7 +648,7 @@ class Worksheet implements IComparable public function refreshColumnDimensions() { $currentColumnDimensions = $this->getColumnDimensions(); - $newColumnDimensions = array(); + $newColumnDimensions = []; foreach ($currentColumnDimensions as $objColumnDimension) { $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; @@ -667,7 +667,7 @@ class Worksheet implements IComparable public function refreshRowDimensions() { $currentRowDimensions = $this->getRowDimensions(); - $newRowDimensions = array(); + $newRowDimensions = []; foreach ($currentRowDimensions as $objRowDimension) { $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; @@ -686,7 +686,7 @@ class Worksheet implements IComparable public function calculateWorksheetDimension() { // Return - return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow(); + return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow(); } /** @@ -697,19 +697,19 @@ class Worksheet implements IComparable public function calculateWorksheetDataDimension() { // Return - return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow(); + return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow(); } /** * Calculate widths for auto-size columns * - * @param boolean $calculateMergeCells Calculate merge cell width + * @param bool $calculateMergeCells Calculate merge cell width * @return Worksheet; */ public function calculateColumnWidths($calculateMergeCells = false) { // initialize $autoSizes array - $autoSizes = array(); + $autoSizes = []; foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; @@ -719,7 +719,7 @@ class Worksheet implements IComparable // There is only something to do if there are some auto-size columns if (!empty($autoSizes)) { // build list of cells references that participate in a merge - $isMergeCell = array(); + $isMergeCell = []; foreach ($this->getMergeCells() as $cells) { foreach (Cell::extractAllCellReferencesInRange($cells) as $cellReference) { $isMergeCell[$cellReference] = true; @@ -854,6 +854,7 @@ class Worksheet implements IComparable } $altTitle = $pValue . ' ' . $i; + return $this->setTitle($altTitle, $updateFormulaCellReferences); } } @@ -891,9 +892,10 @@ class Worksheet implements IComparable * @param string $value Sheet state (visible, hidden, veryHidden) * @return Worksheet */ - public function setSheetState($value = Worksheet::SHEETSTATE_VISIBLE) + public function setSheetState($value = self::SHEETSTATE_VISIBLE) { $this->sheetState = $value; + return $this; } @@ -916,6 +918,7 @@ class Worksheet implements IComparable public function setPageSetup(Worksheet\PageSetup $pValue) { $this->pageSetup = $pValue; + return $this; } @@ -938,6 +941,7 @@ class Worksheet implements IComparable public function setPageMargins(Worksheet\PageMargins $pValue) { $this->pageMargins = $pValue; + return $this; } @@ -960,6 +964,7 @@ class Worksheet implements IComparable public function setHeaderFooter(Worksheet\HeaderFooter $pValue) { $this->headerFooter = $pValue; + return $this; } @@ -982,6 +987,7 @@ class Worksheet implements IComparable public function setSheetView(Worksheet\SheetView $pValue) { $this->sheetView = $pValue; + return $this; } @@ -1021,6 +1027,7 @@ class Worksheet implements IComparable if ($row == null) { return $this->cachedHighestColumn; } + return $this->getHighestDataColumn($row); } @@ -1048,6 +1055,7 @@ class Worksheet implements IComparable if ($column == null) { return $this->cachedHighestRow; } + return $this->getHighestDataRow($column); } @@ -1084,6 +1092,7 @@ class Worksheet implements IComparable public function setCellValue($pCoordinate = 'A1', $pValue = null, $returnCell = false) { $cell = $this->getCell(strtoupper($pCoordinate))->setValue($pValue); + return ($returnCell) ? $cell : $this; } @@ -1099,6 +1108,7 @@ class Worksheet implements IComparable public function setCellValueByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $returnCell = false) { $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValue($pValue); + return ($returnCell) ? $cell : $this; } @@ -1115,6 +1125,7 @@ class Worksheet implements IComparable { // Set value $cell = $this->getCell(strtoupper($pCoordinate))->setValueExplicit($pValue, $pDataType); + return ($returnCell) ? $cell : $this; } @@ -1131,6 +1142,7 @@ class Worksheet implements IComparable public function setCellValueExplicitByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $pDataType = Cell\DataType::TYPE_STRING, $returnCell = false) { $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValueExplicit($pValue, $pDataType); + return ($returnCell) ? $cell : $this; } @@ -1138,7 +1150,7 @@ class Worksheet implements IComparable * Get cell at a specific coordinate * * @param string $pCoordinate Coordinate of the cell - * @param boolean $createIfNotExists Flag indicating whether a new cell should be created if it doesn't + * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't * already exist, or a null should be returned instead * @throws Exception * @return null|Cell Cell that was found/created or null @@ -1152,16 +1164,18 @@ class Worksheet implements IComparable // Worksheet reference? if (strpos($pCoordinate, '!') !== false) { - $worksheetReference = Worksheet::extractSheetTitle($pCoordinate, true); + $worksheetReference = self::extractSheetTitle($pCoordinate, true); + return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists); } // Named range? - if ((!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) && - (preg_match('/^'.Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) { + if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && + (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) { $namedRange = NamedRange::resolveRange($pCoordinate, $this); if ($namedRange !== null) { $pCoordinate = $namedRange->getRange(); + return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists); } } @@ -1184,7 +1198,7 @@ class Worksheet implements IComparable * * @param string $pColumn Numeric column coordinate of the cell * @param string $pRow Numeric row coordinate of the cell - * @param boolean $createIfNotExists Flag indicating whether a new cell should be created if it doesn't + * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't * already exist, or a null should be returned instead * @return null|Cell Cell that was found/created or null */ @@ -1224,7 +1238,7 @@ class Worksheet implements IComparable // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist - $rowDimension = $this->getRowDimension($aCoordinates[1], false); + $rowDimension = $this->getRowDimension($aCoordinates[1], false); $columnDimension = $this->getColumnDimension($aCoordinates[0], false); if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) { @@ -1243,19 +1257,20 @@ class Worksheet implements IComparable * * @param string $pCoordinate Coordinate of the cell * @throws Exception - * @return boolean + * @return bool */ public function cellExists($pCoordinate = 'A1') { - // Worksheet reference? + // Worksheet reference? if (strpos($pCoordinate, '!') !== false) { - $worksheetReference = Worksheet::extractSheetTitle($pCoordinate, true); + $worksheetReference = self::extractSheetTitle($pCoordinate, true); + return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1])); } // Named range? - if ((!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) && - (preg_match('/^'.Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) { + if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && + (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) { $namedRange = NamedRange::resolveRange($pCoordinate, $this); if ($namedRange !== null) { $pCoordinate = $namedRange->getRange(); @@ -1292,7 +1307,7 @@ class Worksheet implements IComparable * * @param string $pColumn Numeric column coordinate of the cell * @param string $pRow Numeric row coordinate of the cell - * @return boolean + * @return bool */ public function cellExistsByColumnAndRow($pColumn = 0, $pRow = 1) { @@ -1319,6 +1334,7 @@ class Worksheet implements IComparable $this->cachedHighestRow = max($this->cachedHighestRow, $pRow); } + return $this->rowDimensions[$pRow]; } @@ -1344,6 +1360,7 @@ class Worksheet implements IComparable $this->cachedHighestColumn = $pColumn; } } + return $this->columnDimensions[$pColumn]; } @@ -1372,8 +1389,8 @@ class Worksheet implements IComparable * Get default style of workbook. * * @deprecated - * @return Style * @throws Exception + * @return Style */ public function getDefaultStyle() { @@ -1390,12 +1407,13 @@ class Worksheet implements IComparable */ public function setDefaultStyle(Style $pValue) { - $this->parent->getDefaultStyle()->applyFromArray(array( - 'font' => array( + $this->parent->getDefaultStyle()->applyFromArray([ + 'font' => [ 'name' => $pValue->getFont()->getName(), 'size' => $pValue->getFont()->getSize(), - ), - )); + ], + ]); + return $this; } @@ -1403,8 +1421,8 @@ class Worksheet implements IComparable * Get style for cell * * @param string $pCellCoordinate Cell coordinate (or range) to get style for - * @return Style * @throws Exception + * @return Style */ public function getStyle($pCellCoordinate = 'A1') { @@ -1427,8 +1445,9 @@ class Worksheet implements IComparable { $pCoordinate = strtoupper($pCoordinate); if (!isset($this->conditionalStylesCollection[$pCoordinate])) { - $this->conditionalStylesCollection[$pCoordinate] = array(); + $this->conditionalStylesCollection[$pCoordinate] = []; } + return $this->conditionalStylesCollection[$pCoordinate]; } @@ -1436,13 +1455,14 @@ class Worksheet implements IComparable * Do conditional styles exist for this cell? * * @param string $pCoordinate - * @return boolean + * @return bool */ public function conditionalStylesExists($pCoordinate = 'A1') { if (isset($this->conditionalStylesCollection[strtoupper($pCoordinate)])) { return true; } + return false; } @@ -1455,6 +1475,7 @@ class Worksheet implements IComparable public function removeConditionalStyles($pCoordinate = 'A1') { unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]); + return $this; } @@ -1478,6 +1499,7 @@ class Worksheet implements IComparable public function setConditionalStyles($pCoordinate, $pValue) { $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue; + return $this; } @@ -1494,6 +1516,7 @@ class Worksheet implements IComparable { if (!is_null($pColumn2) && !is_null($pRow2)) { $cellRange = Cell::stringFromColumnIndex($pColumn) . $pRow . ':' . Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->getStyle($cellRange); } @@ -1514,6 +1537,7 @@ class Worksheet implements IComparable public function setSharedStyle(Style $pSharedCellStyle = null, $pRange = '') { $this->duplicateStyle($pSharedCellStyle, $pRange); + return $this; } @@ -1611,13 +1635,14 @@ class Worksheet implements IComparable * @deprecated * @param array $pStyles Array containing style information * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") - * @param boolean $pAdvanced Advanced mode for setting borders. + * @param bool $pAdvanced Advanced mode for setting borders. * @throws Exception * @return Worksheet */ public function duplicateStyleArray($pStyles = null, $pRange = '', $pAdvanced = true) { $this->getStyle($pRange)->applyFromArray($pStyles, $pAdvanced); + return $this; } @@ -1629,13 +1654,13 @@ class Worksheet implements IComparable * @throws Exception * @return Worksheet */ - public function setBreak($pCell = 'A1', $pBreak = Worksheet::BREAK_NONE) + public function setBreak($pCell = 'A1', $pBreak = self::BREAK_NONE) { // Uppercase coordinate $pCell = strtoupper($pCell); if ($pCell != '') { - if ($pBreak == Worksheet::BREAK_NONE) { + if ($pBreak == self::BREAK_NONE) { if (isset($this->breaks[$pCell])) { unset($this->breaks[$pCell]); } @@ -1652,12 +1677,12 @@ class Worksheet implements IComparable /** * Set break on a cell by using numeric cell coordinates * - * @param integer $pColumn Numeric column coordinate of the cell - * @param integer $pRow Numeric row coordinate of the cell - * @param integer $pBreak Break type (type of \PhpSpreadsheet\Worksheet::BREAK_*) + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @param int $pBreak Break type (type of \PhpSpreadsheet\Worksheet::BREAK_*) * @return Worksheet */ - public function setBreakByColumnAndRow($pColumn = 0, $pRow = 1, $pBreak = Worksheet::BREAK_NONE) + public function setBreakByColumnAndRow($pColumn = 0, $pRow = 1, $pBreak = self::BREAK_NONE) { return $this->setBreak(Cell::stringFromColumnIndex($pColumn) . $pRow, $pBreak); } @@ -1700,7 +1725,7 @@ class Worksheet implements IComparable // Blank out the rest of the cells in the range (if they exist) $count = count($aReferences); - for ($i = 1; $i < $count; $i++) { + for ($i = 1; $i < $count; ++$i) { if ($this->cellExists($aReferences[$i])) { $this->getCell($aReferences[$i])->setValueExplicit(null, Cell\DataType::TYPE_NULL); } @@ -1725,6 +1750,7 @@ class Worksheet implements IComparable public function mergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) { $cellRange = Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->mergeCells($cellRange); } @@ -1766,6 +1792,7 @@ class Worksheet implements IComparable public function unmergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) { $cellRange = Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->unmergeCells($cellRange); } @@ -1785,9 +1812,10 @@ class Worksheet implements IComparable * * @param array */ - public function setMergeCells($pValue = array()) + public function setMergeCells($pValue = []) { $this->mergeCells = $pValue; + return $this; } @@ -1796,7 +1824,7 @@ class Worksheet implements IComparable * * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) * @param string $pPassword Password to unlock the protection - * @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 * @throws Exception * @return Worksheet */ @@ -1821,13 +1849,14 @@ class Worksheet implements IComparable * @param int $pColumn2 Numeric column coordinate of the last cell * @param int $pRow2 Numeric row coordinate of the last cell * @param string $pPassword Password to unlock the protection - * @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 * @throws Exception * @return Worksheet */ public function protectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false) { $cellRange = Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->protectCells($cellRange, $pPassword, $pAlreadyHashed); } @@ -1848,6 +1877,7 @@ class Worksheet implements IComparable } else { throw new Exception('Cell range ' . $pRange . ' not known as protected.'); } + return $this; } @@ -1859,13 +1889,14 @@ class Worksheet implements IComparable * @param int $pColumn2 Numeric column coordinate of the last cell * @param int $pRow2 Numeric row coordinate of the last cell * @param string $pPassword Password to unlock the protection - * @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 * @throws Exception * @return Worksheet */ public function unprotectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false) { $cellRange = Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->unprotectCells($cellRange, $pPassword, $pAlreadyHashed); } @@ -1905,16 +1936,17 @@ class Worksheet implements IComparable } elseif (is_object($pValue) && ($pValue instanceof Worksheet\AutoFilter)) { $this->autoFilter = $pValue; } + return $this; } /** * Set Autofilter Range by using numeric cell coordinates * - * @param integer $pColumn1 Numeric column coordinate of the first cell - * @param integer $pRow1 Numeric row coordinate of the first cell - * @param integer $pColumn2 Numeric column coordinate of the second cell - * @param integer $pRow2 Numeric row coordinate of the second cell + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the second cell + * @param int $pRow2 Numeric row coordinate of the second cell * @throws Exception * @return Worksheet */ @@ -1935,6 +1967,7 @@ class Worksheet implements IComparable public function removeAutoFilter() { $this->autoFilter->setRange(null); + return $this; } @@ -1969,6 +2002,7 @@ class Worksheet implements IComparable } else { throw new Exception('Freeze pane can not be set on a range of cells.'); } + return $this; } @@ -2009,8 +2043,9 @@ class Worksheet implements IComparable $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this); } else { - throw new Exception("Rows can only be inserted before at least row 1."); + throw new Exception('Rows can only be inserted before at least row 1.'); } + return $this; } @@ -2028,8 +2063,9 @@ class Worksheet implements IComparable $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this); } else { - throw new Exception("Column references should not be numeric."); + throw new Exception('Column references should not be numeric.'); } + return $this; } @@ -2046,7 +2082,7 @@ class Worksheet implements IComparable if ($pBefore >= 0) { return $this->insertNewColumnBefore(Cell::stringFromColumnIndex($pBefore), $pNumCols); } else { - throw new Exception("Columns can only be inserted before at least column A (0)."); + throw new Exception('Columns can only be inserted before at least column A (0).'); } } @@ -2069,8 +2105,9 @@ class Worksheet implements IComparable --$highestRow; } } else { - throw new Exception("Rows to be deleted should at least start from row 1."); + throw new Exception('Rows to be deleted should at least start from row 1.'); } + return $this; } @@ -2094,8 +2131,9 @@ class Worksheet implements IComparable $highestColumn = Cell::stringFromColumnIndex(Cell::columnIndexFromString($highestColumn) - 2); } } else { - throw new Exception("Column references should not be numeric."); + throw new Exception('Column references should not be numeric.'); } + return $this; } @@ -2112,14 +2150,14 @@ class Worksheet implements IComparable if ($pColumn >= 0) { return $this->removeColumn(Cell::stringFromColumnIndex($pColumn), $pNumCols); } else { - throw new Exception("Columns to be deleted should at least start from column 0"); + throw new Exception('Columns to be deleted should at least start from column 0'); } } /** * Show gridlines? * - * @return boolean + * @return bool */ public function getShowGridlines() { @@ -2129,63 +2167,66 @@ class Worksheet implements IComparable /** * Set show gridlines * - * @param boolean $pValue Show gridlines (true/false) + * @param bool $pValue Show gridlines (true/false) * @return Worksheet */ public function setShowGridlines($pValue = false) { $this->showGridlines = $pValue; + return $this; } /** - * Print gridlines? - * - * @return boolean - */ + * Print gridlines? + * + * @return bool + */ public function getPrintGridlines() { return $this->printGridlines; } /** - * Set print gridlines - * - * @param boolean $pValue Print gridlines (true/false) - * @return Worksheet - */ + * Set print gridlines + * + * @param bool $pValue Print gridlines (true/false) + * @return Worksheet + */ public function setPrintGridlines($pValue = false) { $this->printGridlines = $pValue; + return $this; } /** - * Show row and column headers? - * - * @return boolean - */ + * Show row and column headers? + * + * @return bool + */ public function getShowRowColHeaders() { return $this->showRowColHeaders; } /** - * Set show row and column headers - * - * @param boolean $pValue Show row and column headers (true/false) - * @return Worksheet - */ + * Set show row and column headers + * + * @param bool $pValue Show row and column headers (true/false) + * @return Worksheet + */ public function setShowRowColHeaders($pValue = false) { $this->showRowColHeaders = $pValue; + return $this; } /** * Show summary below? (Row/Column outlining) * - * @return boolean + * @return bool */ public function getShowSummaryBelow() { @@ -2195,19 +2236,20 @@ class Worksheet implements IComparable /** * Set show summary below * - * @param boolean $pValue Show summary below (true/false) + * @param bool $pValue Show summary below (true/false) * @return Worksheet */ public function setShowSummaryBelow($pValue = true) { $this->showSummaryBelow = $pValue; + return $this; } /** * Show summary right? (Row/Column outlining) * - * @return boolean + * @return bool */ public function getShowSummaryRight() { @@ -2217,12 +2259,13 @@ class Worksheet implements IComparable /** * Set show summary right * - * @param boolean $pValue Show summary right (true/false) + * @param bool $pValue Show summary right (true/false) * @return Worksheet */ public function setShowSummaryRight($pValue = true) { $this->showSummaryRight = $pValue; + return $this; } @@ -2242,7 +2285,7 @@ class Worksheet implements IComparable * @param array of Comment * @return Worksheet */ - public function setComments($pValue = array()) + public function setComments($pValue = []) { $this->comments = $pValue; @@ -2253,8 +2296,8 @@ class Worksheet implements IComparable * Get comment for cell * * @param string $pCellCoordinate Cell coordinate to get comment for - * @return Comment * @throws Exception + * @return Comment */ public function getComment($pCellCoordinate = 'A1') { @@ -2275,6 +2318,7 @@ class Worksheet implements IComparable } else { $newComment = new Comment(); $this->comments[$pCellCoordinate] = $newComment; + return $newComment; } } @@ -2359,12 +2403,13 @@ class Worksheet implements IComparable $pCoordinate = preg_replace('/^([0-9]+):([0-9]+)$/', 'A${1}:XFD${2}', $pCoordinate); if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) { - list($first, ) = Cell::splitRange($pCoordinate); + list($first) = Cell::splitRange($pCoordinate); $this->activeCell = $first[0]; } else { $this->activeCell = $pCoordinate; } $this->selectedCells = $pCoordinate; + return $this; } @@ -2384,7 +2429,7 @@ class Worksheet implements IComparable /** * Get right-to-left * - * @return boolean + * @return bool */ public function getRightToLeft() { @@ -2394,12 +2439,13 @@ class Worksheet implements IComparable /** * Set right-to-left * - * @param boolean $value Right-to-left true/false + * @param bool $value Right-to-left true/false * @return Worksheet */ public function setRightToLeft($value = false) { $this->rightToLeft = $value; + return $this; } @@ -2409,7 +2455,7 @@ class Worksheet implements IComparable * @param array $source Source array * @param mixed $nullValue Value in source array that stands for blank cell * @param string $startCell Insert array starting from this cell address as the top left coordinate - * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array + * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array * @throws Exception * @return Worksheet */ @@ -2418,11 +2464,11 @@ class Worksheet implements IComparable if (is_array($source)) { // Convert a 1-D array to 2-D (for ease of looping) if (!is_array(end($source))) { - $source = array($source); + $source = [$source]; } // start coordinate - list ($startColumn, $startRow) = Cell::coordinateFromString($startCell); + list($startColumn, $startRow) = Cell::coordinateFromString($startCell); // Loop through $source foreach ($source as $rowData) { @@ -2444,8 +2490,9 @@ class Worksheet implements IComparable ++$startRow; } } else { - throw new Exception("Parameter \$source should be an array."); + throw new Exception('Parameter $source should be an array.'); } + return $this; } @@ -2454,24 +2501,24 @@ class Worksheet implements IComparable * * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist - * @param boolean $calculateFormulas Should formulas be calculated? - * @param boolean $formatData Should formatting be applied to cell values? - * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * @param bool $calculateFormulas Should formulas be calculated? + * @param bool $formatData Should formatting be applied to cell values? + * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @return array */ public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { // Returnvalue - $returnValue = array(); + $returnValue = []; // Identify the range that we need to extract from the worksheet list($rangeStart, $rangeEnd) = Cell::rangeBoundaries($pRange); - $minCol = Cell::stringFromColumnIndex($rangeStart[0] -1); + $minCol = Cell::stringFromColumnIndex($rangeStart[0] - 1); $minRow = $rangeStart[1]; - $maxCol = Cell::stringFromColumnIndex($rangeEnd[0] -1); + $maxCol = Cell::stringFromColumnIndex($rangeEnd[0] - 1); $maxRow = $rangeEnd[1]; - $maxCol++; + ++$maxCol; // Loop through rows $r = -1; for ($row = $minRow; $row <= $maxRow; ++$row) { @@ -2482,9 +2529,9 @@ class Worksheet implements IComparable $cRef = ($returnCellRef) ? $col : ++$c; // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen // so we test and retrieve directly against cellCollection - if ($this->cellCollection->isDataSet($col.$row)) { + if ($this->cellCollection->isDataSet($col . $row)) { // Cell exists - $cell = $this->cellCollection->getCacheData($col.$row); + $cell = $this->cellCollection->getCacheData($col . $row); if ($cell->getValue() !== null) { if ($cell->getValue() instanceof RichText) { $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText(); @@ -2518,18 +2565,17 @@ class Worksheet implements IComparable return $returnValue; } - /** * Create array from a range of cells * * @param string $pNamedRange Name of the Named Range * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist - * @param boolean $calculateFormulas Should formulas be calculated? - * @param boolean $formatData Should formatting be applied to cell values? - * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * @param bool $calculateFormulas Should formulas be calculated? + * @param bool $formatData Should formatting be applied to cell values? + * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs - * @return array * @throws Exception + * @return array */ public function namedRangeToArray($pNamedRange = '', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { @@ -2541,17 +2587,16 @@ class Worksheet implements IComparable return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } - throw new Exception('Named Range '.$pNamedRange.' does not exist.'); + throw new Exception('Named Range ' . $pNamedRange . ' does not exist.'); } - /** * Create array from worksheet * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist - * @param boolean $calculateFormulas Should formulas be calculated? - * @param boolean $formatData Should formatting be applied to cell values? - * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * @param bool $calculateFormulas Should formulas be calculated? + * @param bool $formatData Should formatting be applied to cell values? + * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @return array */ @@ -2564,14 +2609,14 @@ class Worksheet implements IComparable $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); // Return - return $this->rangeToArray('A1:'.$maxCol.$maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef); + return $this->rangeToArray('A1:' . $maxCol . $maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } /** * Get row iterator * - * @param integer $startRow The row number at which to start iterating - * @param integer $endRow The row number at which to stop iterating + * @param int $startRow The row number at which to start iterating + * @param int $endRow The row number at which to stop iterating * * @return Worksheet\RowIterator */ @@ -2649,6 +2694,7 @@ class Worksheet implements IComparable $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__); $this->dirty = false; } + return $this->hash; } @@ -2670,7 +2716,7 @@ class Worksheet implements IComparable } if ($returnRange) { - return array(trim(substr($pRange, 0, $sep), "'"), substr($pRange, $sep + 1)); + return [trim(substr($pRange, 0, $sep), "'"), substr($pRange, $sep + 1)]; } return substr($pRange, $sep + 1); @@ -2690,6 +2736,7 @@ class Worksheet implements IComparable // else create hyperlink $this->hyperlinkCollection[$pCellCoordinate] = new Cell\Hyperlink(); + return $this->hyperlinkCollection[$pCellCoordinate]; } @@ -2707,6 +2754,7 @@ class Worksheet implements IComparable } else { $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink; } + return $this; } @@ -2714,7 +2762,7 @@ class Worksheet implements IComparable * Hyperlink at a specific coordinate exists? * * @param string $pCoordinate - * @return boolean + * @return bool */ public function hyperlinkExists($pCoordinate = 'A1') { @@ -2745,6 +2793,7 @@ class Worksheet implements IComparable // else create data validation $this->dataValidationCollection[$pCellCoordinate] = new Cell\DataValidation(); + return $this->dataValidationCollection[$pCellCoordinate]; } @@ -2762,6 +2811,7 @@ class Worksheet implements IComparable } else { $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation; } + return $this; } @@ -2769,7 +2819,7 @@ class Worksheet implements IComparable * Data validation at a specific coordinate exists? * * @param string $pCoordinate - * @return boolean + * @return bool */ public function dataValidationExists($pCoordinate = 'A1') { @@ -2814,7 +2864,7 @@ class Worksheet implements IComparable if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; } - $rangeSet = $rangeBoundaries[0][0].$rangeBoundaries[0][1].':'.$rangeBoundaries[1][0].$rangeBoundaries[1][1]; + $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1]; } unset($rangeSet); $stRange = implode(' ', $rangeBlocks); @@ -2832,6 +2882,7 @@ class Worksheet implements IComparable if ($this->tabColor === null) { $this->tabColor = new Style\Color(); } + return $this->tabColor; } @@ -2851,11 +2902,11 @@ class Worksheet implements IComparable /** * Tab color set? * - * @return boolean + * @return bool */ public function isTabColorSet() { - return ($this->tabColor !== null); + return $this->tabColor !== null; } /** @@ -2898,13 +2949,13 @@ class Worksheet implements IComparable } } } -/** + /** * Define the code name of the sheet * * @param null|string Same rule as Title minus space not allowed (but, like Excel, change silently space to underscore) - * @return objWorksheet * @throws Exception - */ + * @return objWorksheet + */ public function setCodeName($pValue = null) { // Is this a 'rename' or not? @@ -2946,22 +2997,23 @@ class Worksheet implements IComparable } } - $this->codeName=$pValue; + $this->codeName = $pValue; + return $this; } /** * Return the code name of the sheet * * @return null|string - */ + */ public function getCodeName() { return $this->codeName; } /** * Sheet has a code name ? - * @return boolean - */ + * @return bool + */ public function hasCodeName() { return !(is_null($this->codeName)); diff --git a/src/PhpSpreadsheet/Worksheet/AutoFilter.php b/src/PhpSpreadsheet/Worksheet/AutoFilter.php index 57e05ebf..01886612 100644 --- a/src/PhpSpreadsheet/Worksheet/AutoFilter.php +++ b/src/PhpSpreadsheet/Worksheet/AutoFilter.php @@ -35,7 +35,6 @@ class AutoFilter */ private $workSheet; - /** * Autofilter Range * @@ -43,14 +42,12 @@ class AutoFilter */ private $range = ''; - /** * Autofilter Column Ruleset * * @var AutoFilter\Column[] */ - private $columns = array(); - + private $columns = []; /** * Create a new AutoFilter @@ -122,7 +119,7 @@ class AutoFilter if (empty($pRange)) { // Discard all column rules - $this->columns = array(); + $this->columns = []; } else { // Discard any column rules that are no longer valid within this range list($rangeStart, $rangeEnd) = \PhpSpreadsheet\Cell::rangeBoundaries($this->range); @@ -153,18 +150,18 @@ class AutoFilter * * @param string $column Column name (e.g. A) * @throws \PhpSpreadsheet\Exception - * @return integer The column offset within the autofilter range + * @return int The column offset within the autofilter range */ public function testColumnInRange($column) { if (empty($this->range)) { - throw new \PhpSpreadsheet\Exception("No autofilter range is defined."); + throw new \PhpSpreadsheet\Exception('No autofilter range is defined.'); } $columnIndex = \PhpSpreadsheet\Cell::columnIndexFromString($column); list($rangeStart, $rangeEnd) = \PhpSpreadsheet\Cell::rangeBoundaries($this->range); if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { - throw new \PhpSpreadsheet\Exception("Column is outside of current autofilter range."); + throw new \PhpSpreadsheet\Exception('Column is outside of current autofilter range.'); } return $columnIndex - $rangeStart[0]; @@ -175,7 +172,7 @@ class AutoFilter * * @param string $pColumn Column name (e.g. A) * @throws \PhpSpreadsheet\Exception - * @return integer The offset of the specified column within the autofilter range + * @return int The offset of the specified column within the autofilter range */ public function getColumnOffset($pColumn) { @@ -203,7 +200,7 @@ class AutoFilter /** * Get a specified AutoFilter Column by it's offset * - * @param integer $pColumnOffset Column offset within range (starting from 0) + * @param int $pColumnOffset Column offset within range (starting from 0) * @throws \PhpSpreadsheet\Exception * @return AutoFilter\Column */ @@ -230,7 +227,7 @@ class AutoFilter } elseif (is_object($pColumn) && ($pColumn instanceof AutoFilter\Column)) { $column = $pColumn->getColumnIndex(); } else { - throw new \PhpSpreadsheet\Exception("Column is not within the autofilter range."); + throw new \PhpSpreadsheet\Exception('Column is not within the autofilter range.'); } $this->testColumnInRange($column); @@ -292,13 +289,12 @@ class AutoFilter return $this; } - /** * Test if cell value is in the defined set of values * * @param mixed $cellValue * @param mixed[] $dataSet - * @return boolean + * @return bool */ private static function filterTestInSimpleDataSet($cellValue, $dataSet) { @@ -307,6 +303,7 @@ class AutoFilter if (($cellValue == '') || ($cellValue === null)) { return $blanks; } + return in_array($cellValue, $dataSetValues); } @@ -315,7 +312,7 @@ class AutoFilter * * @param mixed $cellValue * @param mixed[] $dataSet - * @return boolean + * @return bool */ private static function filterTestInDateGroupSet($cellValue, $dataSet) { @@ -347,6 +344,7 @@ class AutoFilter } } } + return false; } @@ -355,7 +353,7 @@ class AutoFilter * * @param mixed $cellValue * @param mixed[] $ruleSet - * @return boolean + * @return bool */ private static function filterTestInCustomDataSet($cellValue, $ruleSet) { @@ -375,39 +373,39 @@ class AutoFilter // Numeric values are tested using the appropriate operator switch ($rule['operator']) { case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL: - $retVal = ($cellValue == $rule['value']); + $retVal = ($cellValue == $rule['value']); break; case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: - $retVal = ($cellValue != $rule['value']); + $retVal = ($cellValue != $rule['value']); break; case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: - $retVal = ($cellValue > $rule['value']); + $retVal = ($cellValue > $rule['value']); break; case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: - $retVal = ($cellValue >= $rule['value']); + $retVal = ($cellValue >= $rule['value']); break; case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: - $retVal = ($cellValue < $rule['value']); + $retVal = ($cellValue < $rule['value']); break; case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: - $retVal = ($cellValue <= $rule['value']); + $retVal = ($cellValue <= $rule['value']); break; } } elseif ($rule['value'] == '') { switch ($rule['operator']) { case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL: - $retVal = (($cellValue == '') || ($cellValue === null)); + $retVal = (($cellValue == '') || ($cellValue === null)); break; case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: - $retVal = (($cellValue != '') && ($cellValue !== null)); + $retVal = (($cellValue != '') && ($cellValue !== null)); break; default: - $retVal = true; + $retVal = true; break; } } else { // String values are always tested for equality, factoring in for wildcards (hence a regexp test) - $retVal = preg_match('/^'.$rule['value'].'$/i', $cellValue); + $retVal = preg_match('/^' . $rule['value'] . '$/i', $cellValue); } // If there are multiple conditions, then we need to test both using the appropriate join operator switch ($join) { @@ -433,7 +431,7 @@ class AutoFilter * * @param mixed $cellValue * @param mixed[] $monthSet - * @return boolean + * @return bool */ private static function filterTestInPeriodDateSet($cellValue, $monthSet) { @@ -457,9 +455,8 @@ class AutoFilter * * @var array */ - private static $fromReplace = array('\*', '\?', '~~', '~.*', '~.?'); - private static $toReplace = array('.*', '.', '~', '\*', '\?'); - + private static $fromReplace = ['\*', '\?', '~~', '~.*', '~.?']; + private static $toReplace = ['.*', '.', '~', '\*', '\?']; /** * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation @@ -474,7 +471,7 @@ class AutoFilter \PhpSpreadsheet\Calculation\Functions::setReturnDateType(\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_NUMERIC); $val = $maxVal = null; - $ruleValues = array(); + $ruleValues = []; $baseDate = \PhpSpreadsheet\Calculation\DateTime::DATENOW(); // Calculate start/end dates for the required date range based on current date switch ($dynamicRuleType) { @@ -527,9 +524,9 @@ class AutoFilter case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER: $thisMonth = date('m', $baseDate); $thisQuarter = floor(--$thisMonth / 3); - $maxVal = (int) \PhpSpreadsheet\Shared\Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1+$thisQuarter)*3, date('Y', $baseDate))); + $maxVal = (int) \PhpSpreadsheet\Shared\Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1 + $thisQuarter) * 3, date('Y', $baseDate))); ++$maxVal; - $val = (int) \PhpSpreadsheet\Shared\Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1+$thisQuarter*3, date('Y', $baseDate))); + $val = (int) \PhpSpreadsheet\Shared\Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1 + $thisQuarter * 3, date('Y', $baseDate))); break; case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH: case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH: @@ -560,19 +557,19 @@ class AutoFilter } // Set the filter column rule attributes ready for writing - $filterColumn->setAttributes(array('val' => $val, 'maxVal' => $maxVal)); + $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxVal]); // Set the rules for identifying rows for hide/show - $ruleValues[] = array('operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val); - $ruleValues[] = array('operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal); + $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; + $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal]; \PhpSpreadsheet\Calculation\Functions::setReturnDateType($rDateType); - return array('method' => 'filterTestInCustomDataSet', 'arguments' => array('filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND)); + return ['method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND]]; } private function calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) { - $range = $columnID.$startRow.':'.$columnID.$endRow; + $range = $columnID . $startRow . ':' . $columnID . $endRow; $dataValues = \PhpSpreadsheet\Calculation\Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); $dataValues = array_filter($dataValues); @@ -599,12 +596,12 @@ class AutoFilter // echo 'AutoFilter Heading Row ', $rangeStart[1],' is always SHOWN',PHP_EOL; $this->workSheet->getRowDimension($rangeStart[1])->setVisible(true); - $columnFilterTests = array(); + $columnFilterTests = []; foreach ($this->columns as $columnID => $filterColumn) { $rules = $filterColumn->getRules(); switch ($filterColumn->getFilterType()) { case AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER: - $ruleValues = array(); + $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleType = $rule->getRuleType(); @@ -618,17 +615,17 @@ class AutoFilter } if ($ruleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_FILTER) { // Filter on absolute values - $columnFilterTests[$columnID] = array( + $columnFilterTests[$columnID] = [ 'method' => 'filterTestInSimpleDataSet', - 'arguments' => array('filterValues' => $ruleDataSet, 'blanks' => $blanks) - ); + 'arguments' => ['filterValues' => $ruleDataSet, 'blanks' => $blanks], + ]; } else { // Filter on date group values - $arguments = array( - 'date' => array(), - 'time' => array(), - 'dateTime' => array(), - ); + $arguments = [ + 'date' => [], + 'time' => [], + 'dateTime' => [], + ]; foreach ($ruleDataSet as $ruleValue) { $date = $time = ''; if ((isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && @@ -664,15 +661,15 @@ class AutoFilter $arguments['date'] = array_filter($arguments['date']); $arguments['time'] = array_filter($arguments['time']); $arguments['dateTime'] = array_filter($arguments['dateTime']); - $columnFilterTests[$columnID] = array( + $columnFilterTests[$columnID] = [ 'method' => 'filterTestInDateGroupSet', - 'arguments' => array('filterValues' => $arguments, 'blanks' => $blanks) - ); + 'arguments' => ['filterValues' => $arguments, 'blanks' => $blanks], + ]; } break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER: $customRuleForBlanks = false; - $ruleValues = array(); + $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleType = $rule->getRuleType(); @@ -686,16 +683,16 @@ class AutoFilter $ruleValue = trim($ruleValue); } } - $ruleValues[] = array('operator' => $rule->getOperator(), 'value' => $ruleValue); + $ruleValues[] = ['operator' => $rule->getOperator(), 'value' => $ruleValue]; } $join = $filterColumn->getJoin(); - $columnFilterTests[$columnID] = array( + $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', - 'arguments' => array('filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks) - ); + 'arguments' => ['filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks], + ]; break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER: - $ruleValues = array(); + $ruleValues = []; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $dynamicRuleType = $rule->getGrouping(); @@ -703,37 +700,37 @@ class AutoFilter ($dynamicRuleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE)) { // Number (Average) based // Calculate the average - $averageFormula = '=AVERAGE('.$columnID.($rangeStart[1]+1).':'.$columnID.$rangeEnd[1].')'; + $averageFormula = '=AVERAGE(' . $columnID . ($rangeStart[1] + 1) . ':' . $columnID . $rangeEnd[1] . ')'; $average = \PhpSpreadsheet\Calculation::getInstance()->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); // Set above/below rule based on greaterThan or LessTan $operator = ($dynamicRuleType === AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; - $ruleValues[] = array('operator' => $operator, - 'value' => $average - ); - $columnFilterTests[$columnID] = array( + $ruleValues[] = ['operator' => $operator, + 'value' => $average, + ]; + $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', - 'arguments' => array('filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR) - ); + 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR], + ]; } else { // Date based if ($dynamicRuleType{0} == 'M' || $dynamicRuleType{0} == 'Q') { // Month or Quarter sscanf($dynamicRuleType, '%[A-Z]%d', $periodType, $period); if ($periodType == 'M') { - $ruleValues = array($period); + $ruleValues = [$period]; } else { --$period; - $periodEnd = (1+$period)*3; - $periodStart = 1+$period*3; + $periodEnd = (1 + $period) * 3; + $periodStart = 1 + $period * 3; $ruleValues = range($periodStart, $periodEnd); } - $columnFilterTests[$columnID] = array( + $columnFilterTests[$columnID] = [ 'method' => 'filterTestInPeriodDateSet', - 'arguments' => $ruleValues - ); - $filterColumn->setAttributes(array()); + 'arguments' => $ruleValues, + ]; + $filterColumn->setAttributes([]); } else { // Date Range $columnFilterTests[$columnID] = $this->dynamicFilterDateRange($dynamicRuleType, $filterColumn); @@ -743,7 +740,7 @@ class AutoFilter } break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER: - $ruleValues = array(); + $ruleValues = []; $dataRowCount = $rangeEnd[1] - $rangeStart[1]; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway @@ -761,17 +758,17 @@ class AutoFilter $ruleValue = 500; } - $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1]+1, $rangeEnd[1], $toptenRuleType, $ruleValue); + $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, $rangeEnd[1], $toptenRuleType, $ruleValue); $operator = ($toptenRuleType == AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; - $ruleValues[] = array('operator' => $operator, 'value' => $maxVal); - $columnFilterTests[$columnID] = array( + $ruleValues[] = ['operator' => $operator, 'value' => $maxVal]; + $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', - 'arguments' => array('filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR) - ); - $filterColumn->setAttributes(array('maxVal' => $maxVal)); + 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR], + ]; + $filterColumn->setAttributes(['maxVal' => $maxVal]); break; } } @@ -780,18 +777,18 @@ class AutoFilter // var_dump($columnFilterTests); // // Execute the column tests for each row in the autoFilter range to determine show/hide, - for ($row = $rangeStart[1]+1; $row <= $rangeEnd[1]; ++$row) { -// echo 'Testing Row = ', $row,PHP_EOL; + for ($row = $rangeStart[1] + 1; $row <= $rangeEnd[1]; ++$row) { + // echo 'Testing Row = ', $row,PHP_EOL; $result = true; foreach ($columnFilterTests as $columnID => $columnFilterTest) { -// echo 'Testing cell ', $columnID.$row,PHP_EOL; - $cellValue = $this->workSheet->getCell($columnID.$row)->getCalculatedValue(); + // echo 'Testing cell ', $columnID.$row,PHP_EOL; + $cellValue = $this->workSheet->getCell($columnID . $row)->getCalculatedValue(); // echo 'Value is ', $cellValue,PHP_EOL; // Execute the filter test $result = $result && call_user_func_array( - array('\\PhpSpreadsheet\\Worksheet\\AutoFilter', $columnFilterTest['method']), - array($cellValue, $columnFilterTest['arguments']) + ['\\PhpSpreadsheet\\Worksheet\\AutoFilter', $columnFilterTest['method']], + [$cellValue, $columnFilterTest['arguments']] ); // echo (($result) ? 'VALID' : 'INVALID'),PHP_EOL; // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests @@ -807,7 +804,6 @@ class AutoFilter return $this; } - /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ @@ -824,7 +820,7 @@ class AutoFilter } } elseif ((is_array($value)) && ($key == 'columns')) { // The columns array of \PhpSpreadsheet\Worksheet\AutoFilter objects - $this->{$key} = array(); + $this->{$key} = []; foreach ($value as $k => $v) { $this->{$key}[$k] = clone $v; // attach the new cloned Column to this new cloned Autofilter object diff --git a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php index 33589163..ec205e62 100644 --- a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php +++ b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php @@ -28,21 +28,21 @@ namespace PhpSpreadsheet\Worksheet\AutoFilter; */ class Column { - const AUTOFILTER_FILTERTYPE_FILTER = 'filters'; - const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters'; + const AUTOFILTER_FILTERTYPE_FILTER = 'filters'; + const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters'; // Supports no more than 2 rules, with an And/Or join criteria // if more than 1 rule is defined - const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter'; + const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter'; // Even though the filter rule is constant, the filtered data can vary // e.g. filtered by date = TODAY - const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10'; + const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10'; /** * Types of autofilter rules * * @var string[] */ - private static $filterTypes = array( + private static $filterTypes = [ // Currently we're not handling // colorFilter // extLst @@ -51,21 +51,21 @@ class Column self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER, self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, self::AUTOFILTER_FILTERTYPE_TOPTENFILTER, - ); + ]; /* Multiple Rule Connections */ const AUTOFILTER_COLUMN_JOIN_AND = 'and'; - const AUTOFILTER_COLUMN_JOIN_OR = 'or'; + const AUTOFILTER_COLUMN_JOIN_OR = 'or'; /** * Join options for autofilter rules * * @var string[] */ - private static $ruleJoins = array( + private static $ruleJoins = [ self::AUTOFILTER_COLUMN_JOIN_AND, self::AUTOFILTER_COLUMN_JOIN_OR, - ); + ]; /** * Autofilter @@ -74,7 +74,6 @@ class Column */ private $parent; - /** * Autofilter Column Index * @@ -82,7 +81,6 @@ class Column */ private $columnIndex = ''; - /** * Autofilter Column Filter Type * @@ -90,7 +88,6 @@ class Column */ private $filterType = self::AUTOFILTER_FILTERTYPE_FILTER; - /** * Autofilter Multiple Rules And/Or * @@ -98,22 +95,19 @@ class Column */ private $join = self::AUTOFILTER_COLUMN_JOIN_OR; - /** * Autofilter Column Rules * * @var array of Column\Rule */ - private $ruleset = array(); - + private $ruleset = []; /** * Autofilter Column Dynamic Attributes * * @var array of mixed */ - private $attributes = array(); - + private $attributes = []; /** * Create a new Column @@ -245,7 +239,7 @@ class Column * @throws \PhpSpreadsheet\Exception * @return Column */ - public function setAttributes($pAttributes = array()) + public function setAttributes($pAttributes = []) { $this->attributes = $pAttributes; @@ -288,6 +282,7 @@ class Column if (isset($this->attributes[$pName])) { return $this->attributes[$pName]; } + return null; } @@ -305,7 +300,7 @@ class Column /** * Get a specified AutoFilter Column Rule * - * @param integer $pIndex Rule index in the ruleset array + * @param int $pIndex Rule index in the ruleset array * @return Column\Rule */ public function getRule($pIndex) @@ -313,6 +308,7 @@ class Column if (!isset($this->ruleset[$pIndex])) { $this->ruleset[$pIndex] = new Column\Rule($this); } + return $this->ruleset[$pIndex]; } @@ -332,7 +328,7 @@ class Column * Add a new AutoFilter Column Rule to the ruleset * * @param Column\Rule $pRule - * @param boolean $returnRule Flag indicating whether the rule object or the column object should be returned + * @param bool $returnRule Flag indicating whether the rule object or the column object should be returned * @return Column|Column\Rule */ public function addRule(Column\Rule $pRule, $returnRule = true) @@ -347,7 +343,7 @@ class Column * Delete a specified AutoFilter Column Rule * If the number of rules is reduced to 1, then we reset And/Or logic to Or * - * @param integer $pIndex Rule index in the ruleset array + * @param int $pIndex Rule index in the ruleset array * @return Column */ public function deleteRule($pIndex) @@ -370,7 +366,7 @@ class Column */ public function clearRules() { - $this->ruleset = array(); + $this->ruleset = []; $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); return $this; @@ -392,7 +388,7 @@ class Column } } elseif ((is_array($value)) && ($key == 'ruleset')) { // The columns array of \PhpSpreadsheet\Worksheet\AutoFilter objects - $this->$key = array(); + $this->$key = []; foreach ($value as $k => $v) { $this->$key[$k] = clone $v; // attach the new cloned Rule to this new cloned Autofilter Cloned object diff --git a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php index faba6316..b0c8c49f 100644 --- a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php +++ b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php @@ -28,13 +28,13 @@ namespace PhpSpreadsheet\Worksheet\AutoFilter\Column; */ class Rule { - const AUTOFILTER_RULETYPE_FILTER = 'filter'; - const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem'; - const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter'; + const AUTOFILTER_RULETYPE_FILTER = 'filter'; + const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem'; + const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter'; const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; - const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; + const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; - private static $ruleTypes = array( + private static $ruleTypes = [ // Currently we're not handling // colorFilter // extLst @@ -44,72 +44,72 @@ class Rule self::AUTOFILTER_RULETYPE_CUSTOMFILTER, self::AUTOFILTER_RULETYPE_DYNAMICFILTER, self::AUTOFILTER_RULETYPE_TOPTENFILTER, - ); + ]; - const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year'; - const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month'; - const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day'; - const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour'; + const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year'; + const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month'; + const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day'; + const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour'; const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; - private static $dateTimeGroups = array( + private static $dateTimeGroups = [ self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR, self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE, self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND, - ); + ]; - const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday'; - const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today'; - const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow'; - const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate'; - const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear'; - const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter'; - const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth'; - const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek'; - const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear'; - const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter'; - const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth'; - const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek'; - const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear'; - const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter'; - const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth'; - const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek'; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1'; - const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2'; - const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3'; - const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4'; - const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5'; - const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6'; - const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7'; - const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8'; - const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9'; - const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10'; - const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11'; - const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11; - const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12'; - const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12; - const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1'; - const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2'; - const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3'; - const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4'; + const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday'; + const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today'; + const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow'; + const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1'; + const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2'; + const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3'; + const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4'; + const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5'; + const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6'; + const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7'; + const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8'; + const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9'; + const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10'; + const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11'; + const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12'; + const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4'; const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; - private static $dynamicTypes = array( + private static $dynamicTypes = [ self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, @@ -144,7 +144,7 @@ class Rule self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4, self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE, self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE, - ); + ]; /* * The only valid filter rule operators for filter and customFilter types are: @@ -155,38 +155,37 @@ class Rule * * */ - const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; - const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; - const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; + const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; + const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; + const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; const AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL = 'greaterThanOrEqual'; - const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; - const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; + const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; + const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; - private static $operators = array( + private static $operators = [ self::AUTOFILTER_COLUMN_RULE_EQUAL, self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, self::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, self::AUTOFILTER_COLUMN_RULE_LESSTHAN, self::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, - ); + ]; const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; - const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; + const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; - private static $topTenValue = array( + private static $topTenValue = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, - ); + ]; - const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; + const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; - private static $topTenType = array( + private static $topTenType = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, - ); - + ]; /* Rule Operators (Numeric, Boolean etc) */ // const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 @@ -229,7 +228,6 @@ class Rule */ private $parent = null; - /** * Autofilter Rule Type * @@ -237,7 +235,6 @@ class Rule */ private $ruleType = self::AUTOFILTER_RULETYPE_FILTER; - /** * Autofilter Rule Value * @@ -259,7 +256,6 @@ class Rule */ private $grouping = ''; - /** * Create a new Rule * diff --git a/src/PhpSpreadsheet/Worksheet/BaseDrawing.php b/src/PhpSpreadsheet/Worksheet/BaseDrawing.php index 99130af5..3a79c1c8 100644 --- a/src/PhpSpreadsheet/Worksheet/BaseDrawing.php +++ b/src/PhpSpreadsheet/Worksheet/BaseDrawing.php @@ -101,7 +101,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable /** * Proportional resize * - * @var boolean + * @var bool */ protected $resizeProportional; @@ -125,21 +125,21 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable public function __construct() { // Initialise values - $this->name = ''; - $this->description = ''; - $this->worksheet = null; - $this->coordinates = 'A1'; - $this->offsetX = 0; - $this->offsetY = 0; - $this->width = 0; - $this->height = 0; + $this->name = ''; + $this->description = ''; + $this->worksheet = null; + $this->coordinates = 'A1'; + $this->offsetX = 0; + $this->offsetY = 0; + $this->width = 0; + $this->height = 0; $this->resizeProportional = true; - $this->rotation = 0; - $this->shadow = new Drawing\Shadow(); + $this->rotation = 0; + $this->shadow = new Drawing\Shadow(); // Set image index - self::$imageCounter++; - $this->imageIndex = self::$imageCounter; + ++self::$imageCounter; + $this->imageIndex = self::$imageCounter; } /** @@ -171,6 +171,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable public function setName($pValue = '') { $this->name = $pValue; + return $this; } @@ -193,6 +194,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable public function setDescription($pValue = '') { $this->description = $pValue; + return $this; } @@ -210,7 +212,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable * Set Worksheet * * @param \PhpSpreadsheet\Worksheet $pValue - * @param boolean $pOverrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? + * @param bool $pOverrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? * @throws \PhpSpreadsheet\Exception * @return BaseDrawing */ @@ -240,6 +242,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable throw new \PhpSpreadsheet\Exception("A \PhpSpreadsheet\Worksheet has already been assigned. Drawings can only exist on one \PhpSpreadsheet\Worksheet."); } } + return $this; } @@ -262,6 +265,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable public function setCoordinates($pValue = 'A1') { $this->coordinates = $pValue; + return $this; } @@ -284,6 +288,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable public function setOffsetX($pValue = 0) { $this->offsetX = $pValue; + return $this; } @@ -306,6 +311,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable public function setOffsetY($pValue = 0) { $this->offsetY = $pValue; + return $this; } @@ -389,10 +395,10 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable if ($this->resizeProportional && !($width == 0 || $height == 0)) { if (($xratio * $this->height) < $height) { $this->height = ceil($xratio * $this->height); - $this->width = $width; + $this->width = $width; } else { - $this->width = ceil($yratio * $this->width); - $this->height = $height; + $this->width = ceil($yratio * $this->width); + $this->height = $height; } } else { $this->width = $width; @@ -405,7 +411,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable /** * Get ResizeProportional * - * @return boolean + * @return bool */ public function getResizeProportional() { @@ -415,12 +421,13 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable /** * Set ResizeProportional * - * @param boolean $pValue + * @param bool $pValue * @return BaseDrawing */ public function setResizeProportional($pValue = true) { $this->resizeProportional = $pValue; + return $this; } @@ -443,6 +450,7 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable public function setRotation($pValue = 0) { $this->rotation = $pValue; + return $this; } @@ -465,8 +473,9 @@ class BaseDrawing implements \PhpSpreadsheet\IComparable */ public function setShadow(Drawing\Shadow $pValue = null) { - $this->shadow = $pValue; - return $this; + $this->shadow = $pValue; + + return $this; } /** diff --git a/src/PhpSpreadsheet/Worksheet/CellIterator.php b/src/PhpSpreadsheet/Worksheet/CellIterator.php index 75494fe4..dcc285ff 100644 --- a/src/PhpSpreadsheet/Worksheet/CellIterator.php +++ b/src/PhpSpreadsheet/Worksheet/CellIterator.php @@ -45,7 +45,7 @@ abstract class CellIterator /** * Iterate only existing cells * - * @var boolean + * @var bool */ protected $onlyExistingCells = false; @@ -60,7 +60,7 @@ abstract class CellIterator /** * Get loop only existing cells * - * @return boolean + * @return bool */ public function getIterateOnlyExistingCells() { @@ -77,7 +77,7 @@ abstract class CellIterator /** * Set the iterator to loop only existing cells * - * @param boolean $value + * @param bool $value * @throws \PhpSpreadsheet\Exception */ public function setIterateOnlyExistingCells($value = true) diff --git a/src/PhpSpreadsheet/Worksheet/Column.php b/src/PhpSpreadsheet/Worksheet/Column.php index 1cba6e0c..deec3f77 100644 --- a/src/PhpSpreadsheet/Worksheet/Column.php +++ b/src/PhpSpreadsheet/Worksheet/Column.php @@ -51,7 +51,7 @@ class Column public function __construct(\PhpSpreadsheet\Worksheet $parent = null, $columnIndex = 'A') { // Set parent and column index - $this->parent = $parent; + $this->parent = $parent; $this->columnIndex = $columnIndex; } @@ -76,8 +76,8 @@ class Column /** * Get cell iterator * - * @param integer $startRow The row number at which to start iterating - * @param integer $endRow Optionally, the row number at which to stop iterating + * @param int $startRow The row number at which to start iterating + * @param int $endRow Optionally, the row number at which to stop iterating * @return ColumnCellIterator */ public function getCellIterator($startRow = 1, $endRow = null) diff --git a/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php b/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php index ce21fa51..a6a4714f 100644 --- a/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php +++ b/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php @@ -54,8 +54,8 @@ class ColumnCellIterator extends CellIterator implements \Iterator * * @param \PhpSpreadsheet\Worksheet $subject The worksheet to iterate over * @param string $columnIndex The column that we want to iterate - * @param integer $startRow The row number at which to start iterating - * @param integer $endRow Optionally, the row number at which to stop iterating + * @param int $startRow The row number at which to start iterating + * @param int $endRow Optionally, the row number at which to stop iterating */ public function __construct(\PhpSpreadsheet\Worksheet $subject = null, $columnIndex = 'A', $startRow = 1, $endRow = null) { @@ -77,9 +77,9 @@ class ColumnCellIterator extends CellIterator implements \Iterator /** * (Re)Set the start row and the current row pointer * - * @param integer $startRow The row number at which to start iterating - * @return ColumnCellIterator + * @param int $startRow The row number at which to start iterating * @throws \PhpSpreadsheet\Exception + * @return ColumnCellIterator */ public function resetStart($startRow = 1) { @@ -93,9 +93,9 @@ class ColumnCellIterator extends CellIterator implements \Iterator /** * (Re)Set the end row * - * @param integer $endRow The row number at which to stop iterating - * @return ColumnCellIterator + * @param int $endRow The row number at which to stop iterating * @throws \PhpSpreadsheet\Exception + * @return ColumnCellIterator */ public function resetEnd($endRow = null) { @@ -108,9 +108,9 @@ class ColumnCellIterator extends CellIterator implements \Iterator /** * Set the row pointer to the selected row * - * @param integer $row The row number to set the current pointer at - * @return ColumnCellIterator + * @param int $row The row number to set the current pointer at * @throws \PhpSpreadsheet\Exception + * @return ColumnCellIterator */ public function seek($row = 1) { @@ -183,7 +183,7 @@ class ColumnCellIterator extends CellIterator implements \Iterator /** * Indicate if more rows exist in the worksheet range of rows that we're iterating * - * @return boolean + * @return bool */ public function valid() { diff --git a/src/PhpSpreadsheet/Worksheet/ColumnDimension.php b/src/PhpSpreadsheet/Worksheet/ColumnDimension.php index 7254ebdd..4f7bc3c7 100644 --- a/src/PhpSpreadsheet/Worksheet/ColumnDimension.php +++ b/src/PhpSpreadsheet/Worksheet/ColumnDimension.php @@ -40,7 +40,7 @@ class ColumnDimension extends Dimension * * When this is set to a negative value, the column width should be ignored by IWriter * - * @var double + * @var float */ private $width = -1; @@ -84,13 +84,14 @@ class ColumnDimension extends Dimension public function setColumnIndex($pValue) { $this->columnIndex = $pValue; + return $this; } /** * Get Width * - * @return double + * @return float */ public function getWidth() { @@ -100,12 +101,13 @@ class ColumnDimension extends Dimension /** * Set Width * - * @param double $pValue + * @param float $pValue * @return ColumnDimension */ public function setWidth($pValue = -1) { $this->width = $pValue; + return $this; } @@ -128,6 +130,7 @@ class ColumnDimension extends Dimension public function setAutoSize($pValue = false) { $this->autoSize = $pValue; + return $this; } } diff --git a/src/PhpSpreadsheet/Worksheet/ColumnIterator.php b/src/PhpSpreadsheet/Worksheet/ColumnIterator.php index a9249e14..a37f09a2 100644 --- a/src/PhpSpreadsheet/Worksheet/ColumnIterator.php +++ b/src/PhpSpreadsheet/Worksheet/ColumnIterator.php @@ -52,7 +52,6 @@ class ColumnIterator implements \Iterator */ private $startColumn = 0; - /** * End position * @@ -60,7 +59,6 @@ class ColumnIterator implements \Iterator */ private $endColumn = 0; - /** * Create a new column iterator * @@ -87,9 +85,9 @@ class ColumnIterator implements \Iterator /** * (Re)Set the start column and the current column pointer * - * @param integer $startColumn The column address at which to start iterating - * @return ColumnIterator + * @param int $startColumn The column address at which to start iterating * @throws Exception + * @return ColumnIterator */ public function resetStart($startColumn = 'A') { @@ -125,8 +123,8 @@ class ColumnIterator implements \Iterator * Set the column pointer to the selected column * * @param string $column The column address to set the current pointer at - * @return ColumnIterator * @throws \PhpSpreadsheet\Exception + * @return ColumnIterator */ public function seek($column = 'A') { @@ -184,9 +182,9 @@ class ColumnIterator implements \Iterator { if ($this->position <= $this->startColumn) { throw new \PhpSpreadsheet\Exception( - "Column is already at the beginning of range (" . - \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . " - " . - \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . ")" + 'Column is already at the beginning of range (' . + \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . ' - ' . + \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . ')' ); } @@ -196,7 +194,7 @@ class ColumnIterator implements \Iterator /** * Indicate if more columns exist in the worksheet range of columns that we're iterating * - * @return boolean + * @return bool */ public function valid() { diff --git a/src/PhpSpreadsheet/Worksheet/Dimension.php b/src/PhpSpreadsheet/Worksheet/Dimension.php index 13d196da..d5b638e6 100644 --- a/src/PhpSpreadsheet/Worksheet/Dimension.php +++ b/src/PhpSpreadsheet/Worksheet/Dimension.php @@ -86,6 +86,7 @@ abstract class Dimension public function setVisible($pValue = true) { $this->visible = $pValue; + return $this; } @@ -104,17 +105,18 @@ abstract class Dimension * * Value must be between 0 and 7 * - * @param integer $pValue + * @param int $pValue * @throws \PhpSpreadsheet\Exception * @return Dimension */ public function setOutlineLevel($pValue) { if ($pValue < 0 || $pValue > 7) { - throw new \PhpSpreadsheet\Exception("Outline level must range between 0 and 7."); + throw new \PhpSpreadsheet\Exception('Outline level must range between 0 and 7.'); } $this->outlineLevel = $pValue; + return $this; } @@ -131,12 +133,13 @@ abstract class Dimension /** * Set Collapsed * - * @param boolean $pValue + * @param bool $pValue * @return Dimension */ public function setCollapsed($pValue = true) { $this->collapsed = $pValue; + return $this; } @@ -153,12 +156,13 @@ abstract class Dimension /** * Set index to cellXf * - * @param integer $pValue + * @param int $pValue * @return Dimension */ public function setXfIndex($pValue = 0) { $this->xfIndex = $pValue; + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/Drawing.php b/src/PhpSpreadsheet/Worksheet/Drawing.php index 025d1d1d..145443cb 100644 --- a/src/PhpSpreadsheet/Worksheet/Drawing.php +++ b/src/PhpSpreadsheet/Worksheet/Drawing.php @@ -66,6 +66,7 @@ class Drawing extends BaseDrawing implements \PhpSpreadsheet\IComparable { $fileName = $this->getFilename(); $fileName = str_replace(' ', '_', $fileName); + return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension(); } @@ -76,7 +77,8 @@ class Drawing extends BaseDrawing implements \PhpSpreadsheet\IComparable */ public function getExtension() { - $exploded = explode(".", basename($this->path)); + $exploded = explode('.', basename($this->path)); + return $exploded[count($exploded) - 1]; } @@ -94,7 +96,7 @@ class Drawing extends BaseDrawing implements \PhpSpreadsheet\IComparable * Set Path * * @param string $pValue File path - * @param boolean $pVerifyFile Verify file + * @param bool $pVerifyFile Verify file * @throws \PhpSpreadsheet\Exception * @return Drawing */ @@ -114,6 +116,7 @@ class Drawing extends BaseDrawing implements \PhpSpreadsheet\IComparable } else { $this->path = $pValue; } + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php b/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php index 56194e0a..037eee47 100644 --- a/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php +++ b/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php @@ -29,19 +29,19 @@ namespace PhpSpreadsheet\Worksheet\Drawing; class Shadow implements \PhpSpreadsheet\IComparable { /* Shadow alignment */ - const SHADOW_BOTTOM = 'b'; - const SHADOW_BOTTOM_LEFT = 'bl'; + const SHADOW_BOTTOM = 'b'; + const SHADOW_BOTTOM_LEFT = 'bl'; const SHADOW_BOTTOM_RIGHT = 'br'; - const SHADOW_CENTER = 'ctr'; - const SHADOW_LEFT = 'l'; - const SHADOW_TOP = 't'; - const SHADOW_TOP_LEFT = 'tl'; - const SHADOW_TOP_RIGHT = 'tr'; + const SHADOW_CENTER = 'ctr'; + const SHADOW_LEFT = 'l'; + const SHADOW_TOP = 't'; + const SHADOW_TOP_LEFT = 'tl'; + const SHADOW_TOP_RIGHT = 'tr'; /** * Visible * - * @var boolean + * @var bool */ private $visible; @@ -97,19 +97,19 @@ class Shadow implements \PhpSpreadsheet\IComparable public function __construct() { // Initialise values - $this->visible = false; - $this->blurRadius = 6; - $this->distance = 2; - $this->direction = 0; - $this->alignment = self::SHADOW_BOTTOM_RIGHT; - $this->color = new \PhpSpreadsheet\Style\Color(\PhpSpreadsheet\Style\Color::COLOR_BLACK); - $this->alpha = 50; + $this->visible = false; + $this->blurRadius = 6; + $this->distance = 2; + $this->direction = 0; + $this->alignment = self::SHADOW_BOTTOM_RIGHT; + $this->color = new \PhpSpreadsheet\Style\Color(\PhpSpreadsheet\Style\Color::COLOR_BLACK); + $this->alpha = 50; } /** * Get Visible * - * @return boolean + * @return bool */ public function getVisible() { @@ -119,12 +119,13 @@ class Shadow implements \PhpSpreadsheet\IComparable /** * Set Visible * - * @param boolean $pValue + * @param bool $pValue * @return Shadow */ public function setVisible($pValue = false) { $this->visible = $pValue; + return $this; } @@ -147,6 +148,7 @@ class Shadow implements \PhpSpreadsheet\IComparable public function setBlurRadius($pValue = 6) { $this->blurRadius = $pValue; + return $this; } @@ -169,6 +171,7 @@ class Shadow implements \PhpSpreadsheet\IComparable public function setDistance($pValue = 2) { $this->distance = $pValue; + return $this; } @@ -191,10 +194,11 @@ class Shadow implements \PhpSpreadsheet\IComparable public function setDirection($pValue = 0) { $this->direction = $pValue; + return $this; } - /** + /** * Get Shadow alignment * * @return int @@ -213,10 +217,11 @@ class Shadow implements \PhpSpreadsheet\IComparable public function setAlignment($pValue = 0) { $this->alignment = $pValue; + return $this; } - /** + /** * Get Color * * @return \PhpSpreadsheet\Style\Color @@ -235,11 +240,12 @@ class Shadow implements \PhpSpreadsheet\IComparable */ public function setColor(\PhpSpreadsheet\Style\Color $pValue = null) { - $this->color = $pValue; - return $this; + $this->color = $pValue; + + return $this; } - /** + /** * Get Alpha * * @return int @@ -258,6 +264,7 @@ class Shadow implements \PhpSpreadsheet\IComparable public function setAlpha($pValue = 0) { $this->alpha = $pValue; + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/HeaderFooter.php b/src/PhpSpreadsheet/Worksheet/HeaderFooter.php index d075fe3e..2e54dff2 100644 --- a/src/PhpSpreadsheet/Worksheet/HeaderFooter.php +++ b/src/PhpSpreadsheet/Worksheet/HeaderFooter.php @@ -85,17 +85,16 @@ namespace PhpSpreadsheet\Worksheet; * &O - code for "outline style" * &H - code for "shadow style" * - * */ class HeaderFooter { /* Header/footer image location */ - const IMAGE_HEADER_LEFT = 'LH'; + const IMAGE_HEADER_LEFT = 'LH'; const IMAGE_HEADER_CENTER = 'CH'; - const IMAGE_HEADER_RIGHT = 'RH'; - const IMAGE_FOOTER_LEFT = 'LF'; + const IMAGE_HEADER_RIGHT = 'RH'; + const IMAGE_FOOTER_LEFT = 'LF'; const IMAGE_FOOTER_CENTER = 'CF'; - const IMAGE_FOOTER_RIGHT = 'RF'; + const IMAGE_FOOTER_RIGHT = 'RF'; /** * OddHeader @@ -142,28 +141,28 @@ class HeaderFooter /** * Different header for Odd/Even, defaults to false * - * @var boolean + * @var bool */ private $differentOddEven = false; /** * Different header for first page, defaults to false * - * @var boolean + * @var bool */ private $differentFirst = false; /** * Scale with document, defaults to true * - * @var boolean + * @var bool */ private $scaleWithDocument = true; /** * Align with margins, defaults to true * - * @var boolean + * @var bool */ private $alignWithMargins = true; @@ -172,7 +171,7 @@ class HeaderFooter * * @var HeaderFooterDrawing[] */ - private $headerFooterImages = array(); + private $headerFooterImages = []; /** * Create a new HeaderFooter @@ -200,6 +199,7 @@ class HeaderFooter public function setOddHeader($pValue) { $this->oddHeader = $pValue; + return $this; } @@ -222,6 +222,7 @@ class HeaderFooter public function setOddFooter($pValue) { $this->oddFooter = $pValue; + return $this; } @@ -244,6 +245,7 @@ class HeaderFooter public function setEvenHeader($pValue) { $this->evenHeader = $pValue; + return $this; } @@ -266,6 +268,7 @@ class HeaderFooter public function setEvenFooter($pValue) { $this->evenFooter = $pValue; + return $this; } @@ -288,6 +291,7 @@ class HeaderFooter public function setFirstHeader($pValue) { $this->firstHeader = $pValue; + return $this; } @@ -310,13 +314,14 @@ class HeaderFooter public function setFirstFooter($pValue) { $this->firstFooter = $pValue; + return $this; } /** * Get DifferentOddEven * - * @return boolean + * @return bool */ public function getDifferentOddEven() { @@ -326,19 +331,20 @@ class HeaderFooter /** * Set DifferentOddEven * - * @param boolean $pValue + * @param bool $pValue * @return HeaderFooter */ public function setDifferentOddEven($pValue = false) { $this->differentOddEven = $pValue; + return $this; } /** * Get DifferentFirst * - * @return boolean + * @return bool */ public function getDifferentFirst() { @@ -348,19 +354,20 @@ class HeaderFooter /** * Set DifferentFirst * - * @param boolean $pValue + * @param bool $pValue * @return HeaderFooter */ public function setDifferentFirst($pValue = false) { $this->differentFirst = $pValue; + return $this; } /** * Get ScaleWithDocument * - * @return boolean + * @return bool */ public function getScaleWithDocument() { @@ -370,19 +377,20 @@ class HeaderFooter /** * Set ScaleWithDocument * - * @param boolean $pValue + * @param bool $pValue * @return HeaderFooter */ public function setScaleWithDocument($pValue = true) { $this->scaleWithDocument = $pValue; + return $this; } /** * Get AlignWithMargins * - * @return boolean + * @return bool */ public function getAlignWithMargins() { @@ -392,12 +400,13 @@ class HeaderFooter /** * Set AlignWithMargins * - * @param boolean $pValue + * @param bool $pValue * @return HeaderFooter */ public function setAlignWithMargins($pValue = true) { $this->alignWithMargins = $pValue; + return $this; } @@ -412,6 +421,7 @@ class HeaderFooter public function addImage(HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT) { $this->headerFooterImages[$location] = $image; + return $this; } @@ -427,6 +437,7 @@ class HeaderFooter if (isset($this->headerFooterImages[$location])) { unset($this->headerFooterImages[$location]); } + return $this; } @@ -444,6 +455,7 @@ class HeaderFooter } $this->headerFooterImages = $images; + return $this; } @@ -455,24 +467,24 @@ class HeaderFooter public function getImages() { // Sort array - $images = array(); + $images = []; if (isset($this->headerFooterImages[self::IMAGE_HEADER_LEFT])) { - $images[self::IMAGE_HEADER_LEFT] = $this->headerFooterImages[self::IMAGE_HEADER_LEFT]; + $images[self::IMAGE_HEADER_LEFT] = $this->headerFooterImages[self::IMAGE_HEADER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_CENTER])) { - $images[self::IMAGE_HEADER_CENTER] = $this->headerFooterImages[self::IMAGE_HEADER_CENTER]; + $images[self::IMAGE_HEADER_CENTER] = $this->headerFooterImages[self::IMAGE_HEADER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_RIGHT])) { - $images[self::IMAGE_HEADER_RIGHT] = $this->headerFooterImages[self::IMAGE_HEADER_RIGHT]; + $images[self::IMAGE_HEADER_RIGHT] = $this->headerFooterImages[self::IMAGE_HEADER_RIGHT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_LEFT])) { - $images[self::IMAGE_FOOTER_LEFT] = $this->headerFooterImages[self::IMAGE_FOOTER_LEFT]; + $images[self::IMAGE_FOOTER_LEFT] = $this->headerFooterImages[self::IMAGE_FOOTER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_CENTER])) { - $images[self::IMAGE_FOOTER_CENTER] = $this->headerFooterImages[self::IMAGE_FOOTER_CENTER]; + $images[self::IMAGE_FOOTER_CENTER] = $this->headerFooterImages[self::IMAGE_FOOTER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_RIGHT])) { - $images[self::IMAGE_FOOTER_RIGHT] = $this->headerFooterImages[self::IMAGE_FOOTER_RIGHT]; + $images[self::IMAGE_FOOTER_RIGHT] = $this->headerFooterImages[self::IMAGE_FOOTER_RIGHT]; } $this->headerFooterImages = $images; diff --git a/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php b/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php index 26ad3ef4..28d76dd9 100644 --- a/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php +++ b/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php @@ -73,7 +73,7 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable /** * Proportional resize * - * @var boolean + * @var bool */ protected $resizeProportional; @@ -83,13 +83,13 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable public function __construct() { // Initialise values - $this->path = ''; - $this->name = ''; - $this->offsetX = 0; - $this->offsetY = 0; - $this->width = 0; - $this->height = 0; - $this->resizeProportional = true; + $this->path = ''; + $this->name = ''; + $this->offsetX = 0; + $this->offsetY = 0; + $this->width = 0; + $this->height = 0; + $this->resizeProportional = true; } /** @@ -111,6 +111,7 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable public function setName($pValue = '') { $this->name = $pValue; + return $this; } @@ -133,6 +134,7 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable public function setOffsetX($pValue = 0) { $this->offsetX = $pValue; + return $this; } @@ -155,6 +157,7 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable public function setOffsetY($pValue = 0) { $this->offsetY = $pValue; + return $this; } @@ -238,19 +241,20 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable if ($this->resizeProportional && !($width == 0 || $height == 0)) { if (($xratio * $this->height) < $height) { $this->height = ceil($xratio * $this->height); - $this->width = $width; + $this->width = $width; } else { - $this->width = ceil($yratio * $this->width); - $this->height = $height; + $this->width = ceil($yratio * $this->width); + $this->height = $height; } } + return $this; } /** * Get ResizeProportional * - * @return boolean + * @return bool */ public function getResizeProportional() { @@ -260,12 +264,13 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable /** * Set ResizeProportional * - * @param boolean $pValue + * @param bool $pValue * @return HeaderFooterDrawing */ public function setResizeProportional($pValue = true) { $this->resizeProportional = $pValue; + return $this; } @@ -286,7 +291,8 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable */ public function getExtension() { - $parts = explode(".", basename($this->path)); + $parts = explode('.', basename($this->path)); + return end($parts); } @@ -304,7 +310,7 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable * Set Path * * @param string $pValue File path - * @param boolean $pVerifyFile Verify file + * @param bool $pVerifyFile Verify file * @throws \PhpSpreadsheet\Exception * @return HeaderFooterDrawing */ @@ -324,6 +330,7 @@ class HeaderFooterDrawing extends Drawing implements \PhpSpreadsheet\IComparable } else { $this->path = $pValue; } + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/Iterator.php b/src/PhpSpreadsheet/Worksheet/Iterator.php index 955051f7..1a6ab714 100644 --- a/src/PhpSpreadsheet/Worksheet/Iterator.php +++ b/src/PhpSpreadsheet/Worksheet/Iterator.php @@ -100,7 +100,7 @@ class Iterator implements \Iterator /** * Are there more Worksheet instances available? * - * @return boolean + * @return bool */ public function valid() { diff --git a/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php b/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php index f952fc2f..2b4c0026 100644 --- a/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php +++ b/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php @@ -30,15 +30,15 @@ class MemoryDrawing extends BaseDrawing implements \PhpSpreadsheet\IComparable { /* Rendering functions */ const RENDERING_DEFAULT = 'imagepng'; - const RENDERING_PNG = 'imagepng'; - const RENDERING_GIF = 'imagegif'; - const RENDERING_JPEG = 'imagejpeg'; + const RENDERING_PNG = 'imagepng'; + const RENDERING_GIF = 'imagegif'; + const RENDERING_JPEG = 'imagejpeg'; /* MIME types */ - const MIMETYPE_DEFAULT = 'image/png'; - const MIMETYPE_PNG = 'image/png'; - const MIMETYPE_GIF = 'image/gif'; - const MIMETYPE_JPEG = 'image/jpeg'; + const MIMETYPE_DEFAULT = 'image/png'; + const MIMETYPE_PNG = 'image/png'; + const MIMETYPE_GIF = 'image/gif'; + const MIMETYPE_JPEG = 'image/jpeg'; /** * Image resource @@ -74,10 +74,10 @@ class MemoryDrawing extends BaseDrawing implements \PhpSpreadsheet\IComparable public function __construct() { // Initialise values - $this->imageResource = null; + $this->imageResource = null; $this->renderingFunction = self::RENDERING_DEFAULT; - $this->mimeType = self::MIMETYPE_DEFAULT; - $this->uniqueName = md5(rand(0, 9999). time() . rand(0, 9999)); + $this->mimeType = self::MIMETYPE_DEFAULT; + $this->uniqueName = md5(rand(0, 9999) . time() . rand(0, 9999)); // Initialize parent parent::__construct(); @@ -105,9 +105,10 @@ class MemoryDrawing extends BaseDrawing implements \PhpSpreadsheet\IComparable if (!is_null($this->imageResource)) { // Get width/height - $this->width = imagesx($this->imageResource); + $this->width = imagesx($this->imageResource); $this->height = imagesy($this->imageResource); } + return $this; } @@ -130,6 +131,7 @@ class MemoryDrawing extends BaseDrawing implements \PhpSpreadsheet\IComparable public function setRenderingFunction($value = self::RENDERING_DEFAULT) { $this->renderingFunction = $value; + return $this; } @@ -152,6 +154,7 @@ class MemoryDrawing extends BaseDrawing implements \PhpSpreadsheet\IComparable public function setMimeType($value = self::MIMETYPE_DEFAULT) { $this->mimeType = $value; + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/PageMargins.php b/src/PhpSpreadsheet/Worksheet/PageMargins.php index 570bec4b..c06089fd 100644 --- a/src/PhpSpreadsheet/Worksheet/PageMargins.php +++ b/src/PhpSpreadsheet/Worksheet/PageMargins.php @@ -31,44 +31,44 @@ class PageMargins /** * Left * - * @var double + * @var float */ - private $left = 0.7; + private $left = 0.7; /** * Right * - * @var double + * @var float */ - private $right = 0.7; + private $right = 0.7; /** * Top * - * @var double + * @var float */ - private $top = 0.75; + private $top = 0.75; /** * Bottom * - * @var double + * @var float */ - private $bottom = 0.75; + private $bottom = 0.75; /** * Header * - * @var double + * @var float */ - private $header = 0.3; + private $header = 0.3; /** * Footer * - * @var double + * @var float */ - private $footer = 0.3; + private $footer = 0.3; /** * Create a new PageMargins @@ -80,7 +80,7 @@ class PageMargins /** * Get Left * - * @return double + * @return float */ public function getLeft() { @@ -90,19 +90,20 @@ class PageMargins /** * Set Left * - * @param double $pValue + * @param float $pValue * @return PageMargins */ public function setLeft($pValue) { $this->left = $pValue; + return $this; } /** * Get Right * - * @return double + * @return float */ public function getRight() { @@ -112,19 +113,20 @@ class PageMargins /** * Set Right * - * @param double $pValue + * @param float $pValue * @return PageMargins */ public function setRight($pValue) { $this->right = $pValue; + return $this; } /** * Get Top * - * @return double + * @return float */ public function getTop() { @@ -134,19 +136,20 @@ class PageMargins /** * Set Top * - * @param double $pValue + * @param float $pValue * @return PageMargins */ public function setTop($pValue) { $this->top = $pValue; + return $this; } /** * Get Bottom * - * @return double + * @return float */ public function getBottom() { @@ -156,19 +159,20 @@ class PageMargins /** * Set Bottom * - * @param double $pValue + * @param float $pValue * @return PageMargins */ public function setBottom($pValue) { $this->bottom = $pValue; + return $this; } /** * Get Header * - * @return double + * @return float */ public function getHeader() { @@ -178,19 +182,20 @@ class PageMargins /** * Set Header * - * @param double $pValue + * @param float $pValue * @return PageMargins */ public function setHeader($pValue) { $this->header = $pValue; + return $this; } /** * Get Footer * - * @return double + * @return float */ public function getFooter() { @@ -200,12 +205,13 @@ class PageMargins /** * Set Footer * - * @param double $pValue + * @param float $pValue * @return PageMargins */ public function setFooter($pValue) { $this->footer = $pValue; + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/PageSetup.php b/src/PhpSpreadsheet/Worksheet/PageSetup.php index 63ed3c22..47da4257 100644 --- a/src/PhpSpreadsheet/Worksheet/PageSetup.php +++ b/src/PhpSpreadsheet/Worksheet/PageSetup.php @@ -103,82 +103,81 @@ namespace PhpSpreadsheet\Worksheet; class PageSetup { /* Paper size */ - const PAPERSIZE_LETTER = 1; - const PAPERSIZE_LETTER_SMALL = 2; - const PAPERSIZE_TABLOID = 3; - const PAPERSIZE_LEDGER = 4; - const PAPERSIZE_LEGAL = 5; - const PAPERSIZE_STATEMENT = 6; - const PAPERSIZE_EXECUTIVE = 7; - const PAPERSIZE_A3 = 8; - const PAPERSIZE_A4 = 9; - const PAPERSIZE_A4_SMALL = 10; - const PAPERSIZE_A5 = 11; - const PAPERSIZE_B4 = 12; - const PAPERSIZE_B5 = 13; - const PAPERSIZE_FOLIO = 14; - const PAPERSIZE_QUARTO = 15; - const PAPERSIZE_STANDARD_1 = 16; - const PAPERSIZE_STANDARD_2 = 17; - const PAPERSIZE_NOTE = 18; - const PAPERSIZE_NO9_ENVELOPE = 19; - const PAPERSIZE_NO10_ENVELOPE = 20; - const PAPERSIZE_NO11_ENVELOPE = 21; - const PAPERSIZE_NO12_ENVELOPE = 22; - const PAPERSIZE_NO14_ENVELOPE = 23; - const PAPERSIZE_C = 24; - const PAPERSIZE_D = 25; - const PAPERSIZE_E = 26; - const PAPERSIZE_DL_ENVELOPE = 27; - const PAPERSIZE_C5_ENVELOPE = 28; - const PAPERSIZE_C3_ENVELOPE = 29; - const PAPERSIZE_C4_ENVELOPE = 30; - const PAPERSIZE_C6_ENVELOPE = 31; - const PAPERSIZE_C65_ENVELOPE = 32; - const PAPERSIZE_B4_ENVELOPE = 33; - const PAPERSIZE_B5_ENVELOPE = 34; - const PAPERSIZE_B6_ENVELOPE = 35; - const PAPERSIZE_ITALY_ENVELOPE = 36; - const PAPERSIZE_MONARCH_ENVELOPE = 37; - const PAPERSIZE_6_3_4_ENVELOPE = 38; - const PAPERSIZE_US_STANDARD_FANFOLD = 39; - const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; - const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; - const PAPERSIZE_ISO_B4 = 42; - const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; - const PAPERSIZE_STANDARD_PAPER_1 = 44; - const PAPERSIZE_STANDARD_PAPER_2 = 45; - const PAPERSIZE_STANDARD_PAPER_3 = 46; - const PAPERSIZE_INVITE_ENVELOPE = 47; - const PAPERSIZE_LETTER_EXTRA_PAPER = 48; - const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; - const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; - const PAPERSIZE_A4_EXTRA_PAPER = 51; - const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; - const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; - const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; - const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; - const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; - const PAPERSIZE_LETTER_PLUS_PAPER = 57; - const PAPERSIZE_A4_PLUS_PAPER = 58; - const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; - const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; - const PAPERSIZE_A3_EXTRA_PAPER = 61; - const PAPERSIZE_A5_EXTRA_PAPER = 62; - const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; - const PAPERSIZE_A2_PAPER = 64; - const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; - const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; + const PAPERSIZE_LETTER = 1; + const PAPERSIZE_LETTER_SMALL = 2; + const PAPERSIZE_TABLOID = 3; + const PAPERSIZE_LEDGER = 4; + const PAPERSIZE_LEGAL = 5; + const PAPERSIZE_STATEMENT = 6; + const PAPERSIZE_EXECUTIVE = 7; + const PAPERSIZE_A3 = 8; + const PAPERSIZE_A4 = 9; + const PAPERSIZE_A4_SMALL = 10; + const PAPERSIZE_A5 = 11; + const PAPERSIZE_B4 = 12; + const PAPERSIZE_B5 = 13; + const PAPERSIZE_FOLIO = 14; + const PAPERSIZE_QUARTO = 15; + const PAPERSIZE_STANDARD_1 = 16; + const PAPERSIZE_STANDARD_2 = 17; + const PAPERSIZE_NOTE = 18; + const PAPERSIZE_NO9_ENVELOPE = 19; + const PAPERSIZE_NO10_ENVELOPE = 20; + const PAPERSIZE_NO11_ENVELOPE = 21; + const PAPERSIZE_NO12_ENVELOPE = 22; + const PAPERSIZE_NO14_ENVELOPE = 23; + const PAPERSIZE_C = 24; + const PAPERSIZE_D = 25; + const PAPERSIZE_E = 26; + const PAPERSIZE_DL_ENVELOPE = 27; + const PAPERSIZE_C5_ENVELOPE = 28; + const PAPERSIZE_C3_ENVELOPE = 29; + const PAPERSIZE_C4_ENVELOPE = 30; + const PAPERSIZE_C6_ENVELOPE = 31; + const PAPERSIZE_C65_ENVELOPE = 32; + const PAPERSIZE_B4_ENVELOPE = 33; + const PAPERSIZE_B5_ENVELOPE = 34; + const PAPERSIZE_B6_ENVELOPE = 35; + const PAPERSIZE_ITALY_ENVELOPE = 36; + const PAPERSIZE_MONARCH_ENVELOPE = 37; + const PAPERSIZE_6_3_4_ENVELOPE = 38; + const PAPERSIZE_US_STANDARD_FANFOLD = 39; + const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; + const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; + const PAPERSIZE_ISO_B4 = 42; + const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; + const PAPERSIZE_STANDARD_PAPER_1 = 44; + const PAPERSIZE_STANDARD_PAPER_2 = 45; + const PAPERSIZE_STANDARD_PAPER_3 = 46; + const PAPERSIZE_INVITE_ENVELOPE = 47; + const PAPERSIZE_LETTER_EXTRA_PAPER = 48; + const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; + const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; + const PAPERSIZE_A4_EXTRA_PAPER = 51; + const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; + const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; + const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; + const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; + const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; + const PAPERSIZE_LETTER_PLUS_PAPER = 57; + const PAPERSIZE_A4_PLUS_PAPER = 58; + const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; + const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; + const PAPERSIZE_A3_EXTRA_PAPER = 61; + const PAPERSIZE_A5_EXTRA_PAPER = 62; + const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; + const PAPERSIZE_A2_PAPER = 64; + const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; + const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; /* Page orientation */ - const ORIENTATION_DEFAULT = 'default'; - const ORIENTATION_LANDSCAPE = 'landscape'; - const ORIENTATION_PORTRAIT = 'portrait'; + const ORIENTATION_DEFAULT = 'default'; + const ORIENTATION_LANDSCAPE = 'landscape'; + const ORIENTATION_PORTRAIT = 'portrait'; /* Print Range Set Method */ - const SETPRINTRANGE_OVERWRITE = 'O'; - const SETPRINTRANGE_INSERT = 'I'; - + const SETPRINTRANGE_OVERWRITE = 'O'; + const SETPRINTRANGE_INSERT = 'I'; /** * Paper size @@ -205,54 +204,54 @@ class PageSetup private $scale = 100; /** - * Fit To Page - * Whether scale or fitToWith / fitToHeight applies - * - * @var boolean - */ + * Fit To Page + * Whether scale or fitToWith / fitToHeight applies + * + * @var bool + */ private $fitToPage = false; /** - * Fit To Height - * Number of vertical pages to fit on - * - * @var int? - */ - private $fitToHeight = 1; + * Fit To Height + * Number of vertical pages to fit on + * + * @var int? + */ + private $fitToHeight = 1; /** - * Fit To Width - * Number of horizontal pages to fit on - * - * @var int? - */ - private $fitToWidth = 1; + * Fit To Width + * Number of horizontal pages to fit on + * + * @var int? + */ + private $fitToWidth = 1; /** * Columns to repeat at left * * @var array Containing start column and end column, empty array if option unset */ - private $columnsToRepeatAtLeft = array('', ''); + private $columnsToRepeatAtLeft = ['', '']; /** * Rows to repeat at top * * @var array Containing start row number and end row number, empty array if option unset */ - private $rowsToRepeatAtTop = array(0, 0); + private $rowsToRepeatAtTop = [0, 0]; /** * Center page horizontally * - * @var boolean + * @var bool */ private $horizontalCentered = false; /** * Center page vertically * - * @var boolean + * @var bool */ private $verticalCentered = false; @@ -296,6 +295,7 @@ class PageSetup public function setPaperSize($pValue = self::PAPERSIZE_LETTER) { $this->paperSize = $pValue; + return $this; } @@ -318,6 +318,7 @@ class PageSetup public function setOrientation($pValue = self::ORIENTATION_DEFAULT) { $this->orientation = $pValue; + return $this; } @@ -338,9 +339,9 @@ class PageSetup * This setting is overridden when fitToWidth and/or fitToHeight are in use * * @param int? $pValue - * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth - * @return PageSetup + * @param bool $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth * @throws \PhpSpreadsheet\Exception + * @return PageSetup */ public function setScale($pValue = 100, $pUpdate = true) { @@ -352,15 +353,16 @@ class PageSetup $this->fitToPage = false; } } else { - throw new \PhpSpreadsheet\Exception("Scale must not be negative"); + throw new \PhpSpreadsheet\Exception('Scale must not be negative'); } + return $this; } /** * Get Fit To Page * - * @return boolean + * @return bool */ public function getFitToPage() { @@ -370,12 +372,13 @@ class PageSetup /** * Set Fit To Page * - * @param boolean $pValue + * @param bool $pValue * @return PageSetup */ public function setFitToPage($pValue = true) { $this->fitToPage = $pValue; + return $this; } @@ -393,7 +396,7 @@ class PageSetup * Set Fit To Height * * @param int? $pValue - * @param boolean $pUpdate Update fitToPage so it applies rather than scaling + * @param bool $pUpdate Update fitToPage so it applies rather than scaling * @return PageSetup */ public function setFitToHeight($pValue = 1, $pUpdate = true) @@ -402,6 +405,7 @@ class PageSetup if ($pUpdate) { $this->fitToPage = true; } + return $this; } @@ -419,7 +423,7 @@ class PageSetup * Set Fit To Width * * @param int? $pValue - * @param boolean $pUpdate Update fitToPage so it applies rather than scaling + * @param bool $pUpdate Update fitToPage so it applies rather than scaling * @return PageSetup */ public function setFitToWidth($pValue = 1, $pUpdate = true) @@ -428,13 +432,14 @@ class PageSetup if ($pUpdate) { $this->fitToPage = true; } + return $this; } /** * Is Columns to repeat at left set? * - * @return boolean + * @return bool */ public function isColumnsToRepeatAtLeftSet() { @@ -468,6 +473,7 @@ class PageSetup if (is_array($pValue)) { $this->columnsToRepeatAtLeft = $pValue; } + return $this; } @@ -480,14 +486,15 @@ class PageSetup */ public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') { - $this->columnsToRepeatAtLeft = array($pStart, $pEnd); + $this->columnsToRepeatAtLeft = [$pStart, $pEnd]; + return $this; } /** * Is Rows to repeat at top set? * - * @return boolean + * @return bool */ public function isRowsToRepeatAtTopSet() { @@ -521,6 +528,7 @@ class PageSetup if (is_array($pValue)) { $this->rowsToRepeatAtTop = $pValue; } + return $this; } @@ -533,7 +541,8 @@ class PageSetup */ public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) { - $this->rowsToRepeatAtTop = array($pStart, $pEnd); + $this->rowsToRepeatAtTop = [$pStart, $pEnd]; + return $this; } @@ -556,6 +565,7 @@ class PageSetup public function setHorizontalCentered($value = false) { $this->horizontalCentered = $value; + return $this; } @@ -578,6 +588,7 @@ class PageSetup public function setVerticalCentered($value = false) { $this->verticalCentered = $value; + return $this; } @@ -597,10 +608,10 @@ class PageSetup return $this->printArea; } $printAreas = explode(',', $this->printArea); - if (isset($printAreas[$index-1])) { - return $printAreas[$index-1]; + if (isset($printAreas[$index - 1])) { + return $printAreas[$index - 1]; } - throw new \PhpSpreadsheet\Exception("Requested Print Area does not exist"); + throw new \PhpSpreadsheet\Exception('Requested Print Area does not exist'); } /** @@ -610,7 +621,7 @@ class PageSetup * Default behaviour, or an index value of 0, will identify whether any print range is set * Otherwise, existence of the range identified by the value of $index will be returned * Print areas are numbered from 1 - * @return boolean + * @return bool */ public function isPrintAreaSet($index = 0) { @@ -618,7 +629,8 @@ class PageSetup return !is_null($this->printArea); } $printAreas = explode(',', $this->printArea); - return isset($printAreas[$index-1]); + + return isset($printAreas[$index - 1]); } /** @@ -636,8 +648,8 @@ class PageSetup $this->printArea = null; } else { $printAreas = explode(',', $this->printArea); - if (isset($printAreas[$index-1])) { - unset($printAreas[$index-1]); + if (isset($printAreas[$index - 1])) { + unset($printAreas[$index - 1]); $this->printArea = implode(',', $printAreas); } } @@ -662,8 +674,8 @@ class PageSetup * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list - * @return PageSetup * @throws \PhpSpreadsheet\Exception + * @return PageSetup */ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { @@ -687,12 +699,12 @@ class PageSetup if (($index <= 0) || ($index > count($printAreas))) { throw new \PhpSpreadsheet\Exception('Invalid index for setting print range.'); } - $printAreas[$index-1] = $value; + $printAreas[$index - 1] = $value; $this->printArea = implode(',', $printAreas); } } elseif ($method == self::SETPRINTRANGE_INSERT) { if ($index == 0) { - $this->printArea .= ($this->printArea == '') ? $value : ','.$value; + $this->printArea .= ($this->printArea == '') ? $value : ',' . $value; } else { $printAreas = explode(',', $this->printArea); if ($index < 0) { @@ -701,7 +713,7 @@ class PageSetup if ($index > count($printAreas)) { throw new \PhpSpreadsheet\Exception('Invalid index for setting print range.'); } - $printAreas = array_merge(array_slice($printAreas, 0, $index), array($value), array_slice($printAreas, $index)); + $printAreas = array_merge(array_slice($printAreas, 0, $index), [$value], array_slice($printAreas, $index)); $this->printArea = implode(',', $printAreas); } } else { @@ -721,8 +733,8 @@ class PageSetup * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 - * @return PageSetup * @throws \PhpSpreadsheet\Exception + * @return PageSetup */ public function addPrintArea($value, $index = -1) { @@ -749,8 +761,8 @@ class PageSetup * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list - * @return PageSetup * @throws \PhpSpreadsheet\Exception + * @return PageSetup */ public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { @@ -774,8 +786,8 @@ class PageSetup * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 - * @return PageSetup * @throws \PhpSpreadsheet\Exception + * @return PageSetup */ public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1) { @@ -805,6 +817,7 @@ class PageSetup public function setFirstPageNumber($value = null) { $this->firstPageNumber = $value; + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/Protection.php b/src/PhpSpreadsheet/Worksheet/Protection.php index a1a1f32b..374a58e2 100644 --- a/src/PhpSpreadsheet/Worksheet/Protection.php +++ b/src/PhpSpreadsheet/Worksheet/Protection.php @@ -31,121 +31,121 @@ class Protection /** * Sheet * - * @var boolean + * @var bool */ - private $sheet = false; + private $sheet = false; /** * Objects * - * @var boolean + * @var bool */ - private $objects = false; + private $objects = false; /** * Scenarios * - * @var boolean + * @var bool */ - private $scenarios = false; + private $scenarios = false; /** * Format cells * - * @var boolean + * @var bool */ - private $formatCells = false; + private $formatCells = false; /** * Format columns * - * @var boolean + * @var bool */ - private $formatColumns = false; + private $formatColumns = false; /** * Format rows * - * @var boolean + * @var bool */ - private $formatRows = false; + private $formatRows = false; /** * Insert columns * - * @var boolean + * @var bool */ - private $insertColumns = false; + private $insertColumns = false; /** * Insert rows * - * @var boolean + * @var bool */ - private $insertRows = false; + private $insertRows = false; /** * Insert hyperlinks * - * @var boolean + * @var bool */ - private $insertHyperlinks = false; + private $insertHyperlinks = false; /** * Delete columns * - * @var boolean + * @var bool */ - private $deleteColumns = false; + private $deleteColumns = false; /** * Delete rows * - * @var boolean + * @var bool */ - private $deleteRows = false; + private $deleteRows = false; /** * Select locked cells * - * @var boolean + * @var bool */ - private $selectLockedCells = false; + private $selectLockedCells = false; /** * Sort * - * @var boolean + * @var bool */ - private $sort = false; + private $sort = false; /** * AutoFilter * - * @var boolean + * @var bool */ - private $autoFilter = false; + private $autoFilter = false; /** * Pivot tables * - * @var boolean + * @var bool */ - private $pivotTables = false; + private $pivotTables = false; /** * Select unlocked cells * - * @var boolean + * @var bool */ - private $selectUnlockedCells = false; + private $selectUnlockedCells = false; /** * Password * * @var string */ - private $password = ''; + private $password = ''; /** * Create a new Protection @@ -157,7 +157,7 @@ class Protection /** * Is some sort of protection enabled? * - * @return boolean + * @return bool */ public function isProtectionEnabled() { @@ -182,7 +182,7 @@ class Protection /** * Get Sheet * - * @return boolean + * @return bool */ public function getSheet() { @@ -192,19 +192,20 @@ class Protection /** * Set Sheet * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setSheet($pValue = false) { $this->sheet = $pValue; + return $this; } /** * Get Objects * - * @return boolean + * @return bool */ public function getObjects() { @@ -214,19 +215,20 @@ class Protection /** * Set Objects * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setObjects($pValue = false) { $this->objects = $pValue; + return $this; } /** * Get Scenarios * - * @return boolean + * @return bool */ public function getScenarios() { @@ -236,19 +238,20 @@ class Protection /** * Set Scenarios * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setScenarios($pValue = false) { $this->scenarios = $pValue; + return $this; } /** * Get FormatCells * - * @return boolean + * @return bool */ public function getFormatCells() { @@ -258,19 +261,20 @@ class Protection /** * Set FormatCells * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setFormatCells($pValue = false) { $this->formatCells = $pValue; + return $this; } /** * Get FormatColumns * - * @return boolean + * @return bool */ public function getFormatColumns() { @@ -280,19 +284,20 @@ class Protection /** * Set FormatColumns * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setFormatColumns($pValue = false) { $this->formatColumns = $pValue; + return $this; } /** * Get FormatRows * - * @return boolean + * @return bool */ public function getFormatRows() { @@ -302,19 +307,20 @@ class Protection /** * Set FormatRows * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setFormatRows($pValue = false) { $this->formatRows = $pValue; + return $this; } /** * Get InsertColumns * - * @return boolean + * @return bool */ public function getInsertColumns() { @@ -324,19 +330,20 @@ class Protection /** * Set InsertColumns * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setInsertColumns($pValue = false) { $this->insertColumns = $pValue; + return $this; } /** * Get InsertRows * - * @return boolean + * @return bool */ public function getInsertRows() { @@ -346,19 +353,20 @@ class Protection /** * Set InsertRows * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setInsertRows($pValue = false) { $this->insertRows = $pValue; + return $this; } /** * Get InsertHyperlinks * - * @return boolean + * @return bool */ public function getInsertHyperlinks() { @@ -368,19 +376,20 @@ class Protection /** * Set InsertHyperlinks * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setInsertHyperlinks($pValue = false) { $this->insertHyperlinks = $pValue; + return $this; } /** * Get DeleteColumns * - * @return boolean + * @return bool */ public function getDeleteColumns() { @@ -390,19 +399,20 @@ class Protection /** * Set DeleteColumns * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setDeleteColumns($pValue = false) { $this->deleteColumns = $pValue; + return $this; } /** * Get DeleteRows * - * @return boolean + * @return bool */ public function getDeleteRows() { @@ -412,19 +422,20 @@ class Protection /** * Set DeleteRows * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setDeleteRows($pValue = false) { $this->deleteRows = $pValue; + return $this; } /** * Get SelectLockedCells * - * @return boolean + * @return bool */ public function getSelectLockedCells() { @@ -434,19 +445,20 @@ class Protection /** * Set SelectLockedCells * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setSelectLockedCells($pValue = false) { $this->selectLockedCells = $pValue; + return $this; } /** * Get Sort * - * @return boolean + * @return bool */ public function getSort() { @@ -456,19 +468,20 @@ class Protection /** * Set Sort * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setSort($pValue = false) { $this->sort = $pValue; + return $this; } /** * Get AutoFilter * - * @return boolean + * @return bool */ public function getAutoFilter() { @@ -478,19 +491,20 @@ class Protection /** * Set AutoFilter * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setAutoFilter($pValue = false) { $this->autoFilter = $pValue; + return $this; } /** * Get PivotTables * - * @return boolean + * @return bool */ public function getPivotTables() { @@ -500,19 +514,20 @@ class Protection /** * Set PivotTables * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setPivotTables($pValue = false) { $this->pivotTables = $pValue; + return $this; } /** * Get SelectUnlockedCells * - * @return boolean + * @return bool */ public function getSelectUnlockedCells() { @@ -522,12 +537,13 @@ class Protection /** * Set SelectUnlockedCells * - * @param boolean $pValue + * @param bool $pValue * @return Protection */ public function setSelectUnlockedCells($pValue = false) { $this->selectUnlockedCells = $pValue; + return $this; } @@ -545,7 +561,7 @@ class Protection * Set Password * * @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 Protection */ public function setPassword($pValue = '', $pAlreadyHashed = false) @@ -554,6 +570,7 @@ class Protection $pValue = \PhpSpreadsheet\Shared\PasswordHasher::hashPassword($pValue); } $this->password = $pValue; + return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/Row.php b/src/PhpSpreadsheet/Worksheet/Row.php index 7d1fd07a..7385d0b3 100644 --- a/src/PhpSpreadsheet/Worksheet/Row.php +++ b/src/PhpSpreadsheet/Worksheet/Row.php @@ -51,7 +51,7 @@ class Row public function __construct(\PhpSpreadsheet\Worksheet $parent = null, $rowIndex = 1) { // Set parent and row index - $this->parent = $parent; + $this->parent = $parent; $this->rowIndex = $rowIndex; } diff --git a/src/PhpSpreadsheet/Worksheet/RowCellIterator.php b/src/PhpSpreadsheet/Worksheet/RowCellIterator.php index 634557cd..6ca3dc79 100644 --- a/src/PhpSpreadsheet/Worksheet/RowCellIterator.php +++ b/src/PhpSpreadsheet/Worksheet/RowCellIterator.php @@ -53,7 +53,7 @@ class RowCellIterator extends CellIterator implements \Iterator * Create a new column iterator * * @param \PhpSpreadsheet\Worksheet $subject The worksheet to iterate over - * @param integer $rowIndex The row that we want to iterate + * @param int $rowIndex The row that we want to iterate * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ @@ -77,9 +77,9 @@ class RowCellIterator extends CellIterator implements \Iterator /** * (Re)Set the start column and the current column pointer * - * @param integer $startColumn The column address at which to start iterating - * @return RowCellIterator + * @param int $startColumn The column address at which to start iterating * @throws \PhpSpreadsheet\Exception + * @return RowCellIterator */ public function resetStart($startColumn = 'A') { @@ -95,8 +95,8 @@ class RowCellIterator extends CellIterator implements \Iterator * (Re)Set the end column * * @param string $endColumn The column address at which to stop iterating - * @return RowCellIterator * @throws \PhpSpreadsheet\Exception + * @return RowCellIterator */ public function resetEnd($endColumn = null) { @@ -111,8 +111,8 @@ class RowCellIterator extends CellIterator implements \Iterator * Set the column pointer to the selected column * * @param string $column The column address to set the current pointer at - * @return RowCellIterator * @throws \PhpSpreadsheet\Exception + * @return RowCellIterator */ public function seek($column = 'A') { @@ -176,9 +176,9 @@ class RowCellIterator extends CellIterator implements \Iterator { if ($this->position <= $this->startColumn) { throw new \PhpSpreadsheet\Exception( - "Column is already at the beginning of range (" . - \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . " - " . - \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . ")" + 'Column is already at the beginning of range (' . + \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . ' - ' . + \PhpSpreadsheet\Cell::stringFromColumnIndex($this->endColumn) . ')' ); } @@ -192,7 +192,7 @@ class RowCellIterator extends CellIterator implements \Iterator /** * Indicate if more columns exist in the worksheet range of columns that we're iterating * - * @return boolean + * @return bool */ public function valid() { diff --git a/src/PhpSpreadsheet/Worksheet/RowDimension.php b/src/PhpSpreadsheet/Worksheet/RowDimension.php index a8c4cbb7..9782d5d8 100644 --- a/src/PhpSpreadsheet/Worksheet/RowDimension.php +++ b/src/PhpSpreadsheet/Worksheet/RowDimension.php @@ -40,11 +40,11 @@ class RowDimension extends Dimension * * When this is set to a negative value, the row height should be ignored by IWriter * - * @var double + * @var float */ private $height = -1; - /** + /** * ZeroHeight for Row? * * @var bool @@ -84,13 +84,14 @@ class RowDimension extends Dimension public function setRowIndex($pValue) { $this->rowIndex = $pValue; + return $this; } /** * Get Row Height * - * @return double + * @return float */ public function getRowHeight() { @@ -100,12 +101,13 @@ class RowDimension extends Dimension /** * Set Row Height * - * @param double $pValue + * @param float $pValue * @return RowDimension */ public function setRowHeight($pValue = -1) { $this->height = $pValue; + return $this; } @@ -128,6 +130,7 @@ class RowDimension extends Dimension public function setZeroHeight($pValue = false) { $this->zeroHeight = $pValue; + return $this; } } diff --git a/src/PhpSpreadsheet/Worksheet/RowIterator.php b/src/PhpSpreadsheet/Worksheet/RowIterator.php index 3efa5cba..cd88d119 100644 --- a/src/PhpSpreadsheet/Worksheet/RowIterator.php +++ b/src/PhpSpreadsheet/Worksheet/RowIterator.php @@ -49,7 +49,6 @@ class RowIterator implements \Iterator */ private $startRow = 1; - /** * End position * @@ -57,13 +56,12 @@ class RowIterator implements \Iterator */ private $endRow = 1; - /** * Create a new row iterator * * @param \PhpSpreadsheet\Worksheet $subject The worksheet to iterate over - * @param integer $startRow The row number at which to start iterating - * @param integer $endRow Optionally, the row number at which to stop iterating + * @param int $startRow The row number at which to start iterating + * @param int $endRow Optionally, the row number at which to stop iterating */ public function __construct(\PhpSpreadsheet\Worksheet $subject, $startRow = 1, $endRow = null) { @@ -84,9 +82,9 @@ class RowIterator implements \Iterator /** * (Re)Set the start row and the current row pointer * - * @param integer $startRow The row number at which to start iterating - * @return RowIterator + * @param int $startRow The row number at which to start iterating * @throws \PhpSpreadsheet\Exception + * @return RowIterator */ public function resetStart($startRow = 1) { @@ -106,7 +104,7 @@ class RowIterator implements \Iterator /** * (Re)Set the end row * - * @param integer $endRow The row number at which to stop iterating + * @param int $endRow The row number at which to stop iterating * @return RowIterator */ public function resetEnd($endRow = null) @@ -119,9 +117,9 @@ class RowIterator implements \Iterator /** * Set the row pointer to the selected row * - * @param integer $row The row number to set the current pointer at - * @return RowIterator + * @param int $row The row number to set the current pointer at * @throws \PhpSpreadsheet\Exception + * @return RowIterator */ public function seek($row = 1) { @@ -186,7 +184,7 @@ class RowIterator implements \Iterator /** * Indicate if more rows exist in the worksheet range of rows that we're iterating * - * @return boolean + * @return bool */ public function valid() { diff --git a/src/PhpSpreadsheet/Worksheet/SheetView.php b/src/PhpSpreadsheet/Worksheet/SheetView.php index 1e54db03..a367e828 100644 --- a/src/PhpSpreadsheet/Worksheet/SheetView.php +++ b/src/PhpSpreadsheet/Worksheet/SheetView.php @@ -28,17 +28,16 @@ namespace PhpSpreadsheet\Worksheet; */ class SheetView { - /* Sheet View types */ - const SHEETVIEW_NORMAL = 'normal'; - const SHEETVIEW_PAGE_LAYOUT = 'pageLayout'; + const SHEETVIEW_NORMAL = 'normal'; + const SHEETVIEW_PAGE_LAYOUT = 'pageLayout'; const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview'; - private static $sheetViewTypes = array( + private static $sheetViewTypes = [ self::SHEETVIEW_NORMAL, self::SHEETVIEW_PAGE_LAYOUT, self::SHEETVIEW_PAGE_BREAK_PREVIEW, - ); + ]; /** * ZoomScale @@ -100,8 +99,9 @@ class SheetView if (($pValue >= 1) || is_null($pValue)) { $this->zoomScale = $pValue; } else { - throw new \PhpSpreadsheet\Exception("Scale must be greater than or equal to 1."); + throw new \PhpSpreadsheet\Exception('Scale must be greater than or equal to 1.'); } + return $this; } @@ -129,8 +129,9 @@ class SheetView if (($pValue >= 1) || is_null($pValue)) { $this->zoomScaleNormal = $pValue; } else { - throw new \PhpSpreadsheet\Exception("Scale must be greater than or equal to 1."); + throw new \PhpSpreadsheet\Exception('Scale must be greater than or equal to 1.'); } + return $this; } @@ -165,7 +166,7 @@ class SheetView if (in_array($pValue, self::$sheetViewTypes)) { $this->sheetviewType = $pValue; } else { - throw new \PhpSpreadsheet\Exception("Invalid sheetview layout type."); + throw new \PhpSpreadsheet\Exception('Invalid sheetview layout type.'); } return $this; diff --git a/src/PhpSpreadsheet/Writer/BaseWriter.php b/src/PhpSpreadsheet/Writer/BaseWriter.php index 82f524ea..ce1316db 100644 --- a/src/PhpSpreadsheet/Writer/BaseWriter.php +++ b/src/PhpSpreadsheet/Writer/BaseWriter.php @@ -32,7 +32,7 @@ abstract class BaseWriter implements IWriter * Write charts that are defined in the workbook? * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object; * - * @var boolean + * @var bool */ protected $includeCharts = false; @@ -41,14 +41,14 @@ abstract class BaseWriter implements IWriter * Forces PhpSpreadsheet to recalculate all formulae in a workbook when saving, so that the pre-calculated values are * immediately available to MS Excel or other office spreadsheet viewer when opening the file * - * @var boolean + * @var bool */ protected $preCalculateFormulas = true; /** * Use disk caching where possible? * - * @var boolean + * @var bool */ protected $_useDiskCaching = false; @@ -57,14 +57,14 @@ abstract class BaseWriter implements IWriter * * @var string */ - protected $_diskCachingDirectory = './'; + protected $_diskCachingDirectory = './'; /** * Write charts in workbook? * If this is true, then the Writer will write definitions for any charts that exist in the PhpSpreadsheet object. * If false (the default) it will ignore any charts defined in the PhpSpreadsheet object. * - * @return boolean + * @return bool */ public function getIncludeCharts() { @@ -76,12 +76,13 @@ abstract class BaseWriter implements IWriter * Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object. * Set to false (the default) to ignore charts. * - * @param boolean $pValue + * @param bool $pValue * @return IWriter */ public function setIncludeCharts($pValue = false) { $this->includeCharts = (boolean) $pValue; + return $this; } @@ -93,7 +94,7 @@ abstract class BaseWriter implements IWriter * If false, then formulae are not calculated on save. This is faster for saving in PhpSpreadsheet, but slower * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself * - * @return boolean + * @return bool */ public function getPreCalculateFormulas() { @@ -105,19 +106,20 @@ abstract class BaseWriter implements IWriter * Set to true (the default) to advise the Writer to calculate all formulae on save * Set to false to prevent precalculation of formulae on save. * - * @param boolean $pValue Pre-Calculate Formulas? + * @param bool $pValue Pre-Calculate Formulas? * @return IWriter */ public function setPreCalculateFormulas($pValue = true) { $this->preCalculateFormulas = (boolean) $pValue; + return $this; } /** * Get use disk caching where possible? * - * @return boolean + * @return bool */ public function getUseDiskCaching() { @@ -127,7 +129,7 @@ abstract class BaseWriter implements IWriter /** * Set use disk caching where possible? * - * @param boolean $pValue + * @param bool $pValue * @param string $pDirectory Disk caching directory * @throws Exception when directory does not exist * @return IWriter @@ -143,6 +145,7 @@ abstract class BaseWriter implements IWriter throw new Exception("Directory does not exist: $pDirectory"); } } + return $this; } diff --git a/src/PhpSpreadsheet/Writer/CSV.php b/src/PhpSpreadsheet/Writer/CSV.php index be7af10d..c3e4152a 100644 --- a/src/PhpSpreadsheet/Writer/CSV.php +++ b/src/PhpSpreadsheet/Writer/CSV.php @@ -38,33 +38,33 @@ class CSV extends BaseWriter implements IWriter * * @var string */ - private $delimiter = ','; + private $delimiter = ','; /** * Enclosure * * @var string */ - private $enclosure = '"'; + private $enclosure = '"'; /** * Line ending * * @var string */ - private $lineEnding = PHP_EOL; + private $lineEnding = PHP_EOL; /** * Sheet index to write * * @var int */ - private $sheetIndex = 0; + private $sheetIndex = 0; /** * Whether to write a BOM (for UTF8). * - * @var boolean + * @var bool */ private $useBOM = false; @@ -72,14 +72,14 @@ class CSV extends BaseWriter implements IWriter * Whether to write a Separator line as the first line of the file * sep=x * - * @var boolean + * @var bool */ private $includeSeparatorLine = false; /** * Whether to write a fully Excel compatible CSV file. * - * @var boolean + * @var bool */ private $excelCompatibility = false; @@ -119,7 +119,7 @@ class CSV extends BaseWriter implements IWriter $this->setUseBOM(true); // Enforce UTF-8 BOM Header $this->setIncludeSeparatorLine(true); // Set separator line $this->setEnclosure('"'); // Set enclosure to " - $this->setDelimiter(";"); // Set delimiter to a semi-colon + $this->setDelimiter(';'); // Set delimiter to a semi-colon $this->setLineEnding("\r\n"); } if ($this->useBOM) { @@ -138,7 +138,7 @@ class CSV extends BaseWriter implements IWriter // Write rows to file for ($row = 1; $row <= $maxRow; ++$row) { // Convert the row to an array... - $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row, '', $this->preCalculateFormulas); + $cellsArray = $sheet->rangeToArray('A' . $row . ':' . $maxCol . $row, '', $this->preCalculateFormulas); // ... and write to the file $this->writeLine($fileHandle, $cellsArray[0]); } @@ -169,6 +169,7 @@ class CSV extends BaseWriter implements IWriter public function setDelimiter($pValue = ',') { $this->delimiter = $pValue; + return $this; } @@ -194,6 +195,7 @@ class CSV extends BaseWriter implements IWriter $pValue = null; } $this->enclosure = $pValue; + return $this; } @@ -216,13 +218,14 @@ class CSV extends BaseWriter implements IWriter public function setLineEnding($pValue = PHP_EOL) { $this->lineEnding = $pValue; + return $this; } /** * Get whether BOM should be used * - * @return boolean + * @return bool */ public function getUseBOM() { @@ -232,19 +235,20 @@ class CSV extends BaseWriter implements IWriter /** * Set whether BOM should be used * - * @param boolean $pValue Use UTF-8 byte-order mark? Defaults to false + * @param bool $pValue Use UTF-8 byte-order mark? Defaults to false * @return CSV */ public function setUseBOM($pValue = false) { $this->useBOM = $pValue; + return $this; } /** * Get whether a separator line should be included * - * @return boolean + * @return bool */ public function getIncludeSeparatorLine() { @@ -254,19 +258,20 @@ class CSV extends BaseWriter implements IWriter /** * Set whether a separator line should be included as the first line of the file * - * @param boolean $pValue Use separator line? Defaults to false + * @param bool $pValue Use separator line? Defaults to false * @return CSV */ public function setIncludeSeparatorLine($pValue = false) { $this->includeSeparatorLine = $pValue; + return $this; } /** * Get whether the file should be saved with full Excel Compatibility * - * @return boolean + * @return bool */ public function getExcelCompatibility() { @@ -276,13 +281,14 @@ class CSV extends BaseWriter implements IWriter /** * Set whether the file should be saved with full Excel Compatibility * - * @param boolean $pValue Set the file to be written as a fully Excel compatible csv file + * @param bool $pValue Set the file to be written as a fully Excel compatible csv file * Note that this overrides other settings such as useBOM, enclosure and delimiter * @return CSV */ public function setExcelCompatibility($pValue = false) { $this->excelCompatibility = $pValue; + return $this; } @@ -305,6 +311,7 @@ class CSV extends BaseWriter implements IWriter public function setSheetIndex($pValue = 0) { $this->sheetIndex = $pValue; + return $this; } @@ -345,7 +352,7 @@ class CSV extends BaseWriter implements IWriter // Write to file fwrite($pFileHandle, $line); } else { - throw new Exception("Invalid data row passed to CSV writer."); + throw new Exception('Invalid data row passed to CSV writer.'); } } } diff --git a/src/PhpSpreadsheet/Writer/Excel2007.php b/src/PhpSpreadsheet/Writer/Excel2007.php index 677c7f4f..6e178bbd 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007.php +++ b/src/PhpSpreadsheet/Writer/Excel2007.php @@ -31,7 +31,7 @@ class Excel2007 extends BaseWriter implements IWriter /** * Office2003 compatibility * - * @var boolean + * @var bool */ private $office2003compatibility = false; @@ -40,7 +40,7 @@ class Excel2007 extends BaseWriter implements IWriter * * @var Excel2007\WriterPart[] */ - private $writerParts = array(); + private $writerParts = []; /** * Private Spreadsheet @@ -54,7 +54,7 @@ class Excel2007 extends BaseWriter implements IWriter * * @var string[] */ - private $stringTable = array(); + private $stringTable = []; /** * Private unique \PhpSpreadsheet\Style\Conditional HashTable @@ -89,7 +89,7 @@ class Excel2007 extends BaseWriter implements IWriter * * @var \PhpSpreadsheet\HashTable */ - private $bordersHashTable ; + private $bordersHashTable; /** * Private unique \PhpSpreadsheet\Style\NumberFormat HashTable @@ -116,19 +116,19 @@ class Excel2007 extends BaseWriter implements IWriter $this->setPhpSpreadsheet($spreadsheet); $writerPartsArray = [ - 'stringtable' => '\\PhpSpreadsheet\\Writer\\Excel2007\\StringTable', - 'contenttypes' => '\\PhpSpreadsheet\\Writer\\Excel2007\\ContentTypes', - 'docprops' => '\\PhpSpreadsheet\\Writer\\Excel2007\\DocProps', - 'rels' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Rels', - 'theme' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Theme', - 'style' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Style', - 'workbook' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Workbook', - 'worksheet' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Worksheet', - 'drawing' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Drawing', - 'comments' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Comments', - 'chart' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Chart', - 'relsvba' => '\\PhpSpreadsheet\\Writer\\Excel2007\\RelsVBA', - 'relsribbonobjects' => '\\PhpSpreadsheet\\Writer\\Excel2007\\RelsRibbon' + 'stringtable' => '\\PhpSpreadsheet\\Writer\\Excel2007\\StringTable', + 'contenttypes' => '\\PhpSpreadsheet\\Writer\\Excel2007\\ContentTypes', + 'docprops' => '\\PhpSpreadsheet\\Writer\\Excel2007\\DocProps', + 'rels' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Rels', + 'theme' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Theme', + 'style' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Style', + 'workbook' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Workbook', + 'worksheet' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Worksheet', + 'drawing' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Drawing', + 'comments' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Comments', + 'chart' => '\\PhpSpreadsheet\\Writer\\Excel2007\\Chart', + 'relsvba' => '\\PhpSpreadsheet\\Writer\\Excel2007\\RelsVBA', + 'relsribbonobjects' => '\\PhpSpreadsheet\\Writer\\Excel2007\\RelsRibbon', ]; // Initialise writer parts @@ -137,14 +137,14 @@ class Excel2007 extends BaseWriter implements IWriter $this->writerParts[$writer] = new $class($this); } - $hashTablesArray = array( 'stylesConditionalHashTable', 'fillHashTable', 'fontHashTable', + $hashTablesArray = ['stylesConditionalHashTable', 'fillHashTable', 'fontHashTable', 'bordersHashTable', 'numFmtHashTable', 'drawingHashTable', - 'styleHashTable' - ); + 'styleHashTable', + ]; // Set HashTable variables foreach ($hashTablesArray as $tableName) { - $this->$tableName = new \PhpSpreadsheet\HashTable(); + $this->$tableName = new \PhpSpreadsheet\HashTable(); } } @@ -190,7 +190,7 @@ class Excel2007 extends BaseWriter implements IWriter \PhpSpreadsheet\Calculation\Functions::setReturnDateType(\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL); // Create string lookup table - $this->stringTable = array(); + $this->stringTable = []; for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { $this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); } @@ -223,7 +223,7 @@ class Excel2007 extends BaseWriter implements IWriter // Try opening the ZIP file if ($objZip->open($pFilename, $zipOverWrite) !== true) { if ($objZip->open($pFilename, $zipCreate) !== true) { - throw new \PhpSpreadsheet\Writer\Exception("Could not open " . $pFilename . " for writing."); + throw new \PhpSpreadsheet\Writer\Exception('Could not open ' . $pFilename . ' for writing.'); } } @@ -232,10 +232,12 @@ class Excel2007 extends BaseWriter implements IWriter //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) if ($this->spreadSheet->hasMacros()) { - $macrosCode=$this->spreadSheet->getMacrosCode(); - if (!is_null($macrosCode)) {// we have the code ? + $macrosCode = $this->spreadSheet->getMacrosCode(); + if (!is_null($macrosCode)) { + // we have the code ? $objZip->addFromString('xl/vbaProject.bin', $macrosCode);//allways in 'xl', allways named vbaProject.bin - if ($this->spreadSheet->hasMacrosCertificate()) {//signed macros ? + if ($this->spreadSheet->hasMacrosCertificate()) { + //signed macros ? // Yes : add the certificate file and the related rels file $objZip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate()); $objZip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet)); @@ -244,16 +246,16 @@ class Excel2007 extends BaseWriter implements IWriter } //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) if ($this->spreadSheet->hasRibbon()) { - $tmpRibbonTarget=$this->spreadSheet->getRibbonXMLData('target'); + $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target'); $objZip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data')); if ($this->spreadSheet->hasRibbonBinObjects()) { - $tmpRootPath=dirname($tmpRibbonTarget).'/'; - $ribbonBinObjects=$this->spreadSheet->getRibbonBinObjects('data');//the files to write + $tmpRootPath = dirname($tmpRibbonTarget) . '/'; + $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data');//the files to write foreach ($ribbonBinObjects as $aPath => $aContent) { - $objZip->addFromString($tmpRootPath.$aPath, $aContent); + $objZip->addFromString($tmpRootPath . $aPath, $aContent); } //the rels for files - $objZip->addFromString($tmpRootPath.'_rels/'.basename($tmpRibbonTarget).'.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet)); + $objZip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet)); } } @@ -290,7 +292,7 @@ class Excel2007 extends BaseWriter implements IWriter if (count($charts) > 0) { foreach ($charts as $chart) { $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas)); - $chartCount++; + ++$chartCount; } } } @@ -390,22 +392,22 @@ class Excel2007 extends BaseWriter implements IWriter @unlink($pFilename); } } else { - throw new \PhpSpreadsheet\Writer\Exception("PhpSpreadsheet object unassigned."); + throw new \PhpSpreadsheet\Writer\Exception('PhpSpreadsheet object unassigned.'); } } /** * Get PhpSpreadsheet object * - * @return PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return PhpSpreadsheet */ public function getPhpSpreadsheet() { if ($this->spreadSheet !== null) { return $this->spreadSheet; } else { - throw new \PhpSpreadsheet\Writer\Exception("No PhpSpreadsheet object assigned."); + throw new \PhpSpreadsheet\Writer\Exception('No PhpSpreadsheet object assigned.'); } } @@ -419,6 +421,7 @@ class Excel2007 extends BaseWriter implements IWriter public function setPhpSpreadsheet(\PhpSpreadsheet\Spreadsheet $spreadsheet = null) { $this->spreadSheet = $spreadsheet; + return $this; } @@ -505,7 +508,7 @@ class Excel2007 extends BaseWriter implements IWriter /** * Get Office2003 compatibility * - * @return boolean + * @return bool */ public function getOffice2003Compatibility() { @@ -515,12 +518,13 @@ class Excel2007 extends BaseWriter implements IWriter /** * Set Office2003 compatibility * - * @param boolean $pValue Office2003 compatibility? + * @param bool $pValue Office2003 compatibility? * @return Excel2007 */ public function setOffice2003Compatibility($pValue = false) { $this->office2003compatibility = $pValue; + return $this; } } diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Chart.php b/src/PhpSpreadsheet/Writer/Excel2007/Chart.php index af4217eb..add25449 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Chart.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Chart.php @@ -1,4 +1,5 @@ writeAttribute('val', 0); $objWriter->endElement(); $objWriter->startElement('c:lang'); - $objWriter->writeAttribute('val', "en-GB"); + $objWriter->writeAttribute('val', 'en-GB'); $objWriter->endElement(); $objWriter->startElement('c:roundedCorners'); $objWriter->writeAttribute('val', 0); @@ -98,7 +99,7 @@ class Chart extends WriterPart $objWriter->endElement(); $objWriter->startElement('c:dispBlanksAs'); - $objWriter->writeAttribute('val', "gap"); + $objWriter->writeAttribute('val', 'gap'); $objWriter->endElement(); $objWriter->startElement('c:showDLblsOverMax'); @@ -202,7 +203,7 @@ class Chart extends WriterPart $objWriter->endElement(); $objWriter->startElement('a:endParaRPr'); - $objWriter->writeAttribute('lang', "en-US"); + $objWriter->writeAttribute('lang', 'en-US'); $objWriter->endElement(); $objWriter->endElement(); @@ -271,7 +272,7 @@ class Chart extends WriterPart $objWriter->startElement('c:smooth'); $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine()); $objWriter->endElement(); - } elseif (($chartType === DataSeries::TYPE_BARCHART) ||($chartType === DataSeries::TYPE_BARCHART_3D)) { + } elseif (($chartType === DataSeries::TYPE_BARCHART) || ($chartType === DataSeries::TYPE_BARCHART_3D)) { $objWriter->startElement('c:gapWidth'); $objWriter->writeAttribute('val', 150); $objWriter->endElement(); @@ -410,7 +411,7 @@ class Chart extends WriterPart * @param string $groupType Chart type * @param string $id1 * @param string $id2 - * @param boolean $isMultiLevelSeries + * @param bool $isMultiLevelSeries * * @throws \PhpSpreadsheet\Writer\Exception */ @@ -435,7 +436,7 @@ class Chart extends WriterPart $objWriter->endElement(); $objWriter->startElement('c:axPos'); - $objWriter->writeAttribute('val', "b"); + $objWriter->writeAttribute('val', 'b'); $objWriter->endElement(); if (!is_null($xAxisLabel)) { @@ -508,7 +509,7 @@ class Chart extends WriterPart $objWriter->endElement(); $objWriter->startElement('c:lblAlgn'); - $objWriter->writeAttribute('val', "ctr"); + $objWriter->writeAttribute('val', 'ctr'); $objWriter->endElement(); $objWriter->startElement('c:lblOffset'); @@ -532,7 +533,7 @@ class Chart extends WriterPart * @param string $groupType Chart type * @param string $id1 * @param string $id2 - * @param boolean $isMultiLevelSeries + * @param bool $isMultiLevelSeries * * @throws \PhpSpreadsheet\Writer\Exception */ @@ -571,7 +572,7 @@ class Chart extends WriterPart $objWriter->endElement(); $objWriter->startElement('c:axPos'); - $objWriter->writeAttribute('val', "l"); + $objWriter->writeAttribute('val', 'l'); $objWriter->endElement(); $objWriter->startElement('c:majorGridlines'); @@ -602,17 +603,17 @@ class Chart extends WriterPart $objWriter->endElement(); } - if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) { + if (!is_null($majorGridlines->getLineStyleProperty(['arrow', 'head', 'type']))) { $objWriter->startElement('a:headEnd'); - $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type'))); + $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(['arrow', 'head', 'type'])); $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('head', 'w')); $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('head', 'len')); $objWriter->endElement(); } - if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) { + if (!is_null($majorGridlines->getLineStyleProperty(['arrow', 'end', 'type']))) { $objWriter->startElement('a:tailEnd'); - $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type'))); + $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(['arrow', 'end', 'type'])); $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('end', 'w')); $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('end', 'len')); $objWriter->endElement(); @@ -647,23 +648,23 @@ class Chart extends WriterPart if (!is_null($majorGridlines->getShadowProperty('algn'))) { $objWriter->writeAttribute('algn', $majorGridlines->getShadowProperty('algn')); } - if (!is_null($majorGridlines->getShadowProperty(array('size', 'sx')))) { - $objWriter->writeAttribute('sx', $majorGridlines->getShadowProperty(array('size', 'sx'))); + if (!is_null($majorGridlines->getShadowProperty(['size', 'sx']))) { + $objWriter->writeAttribute('sx', $majorGridlines->getShadowProperty(['size', 'sx'])); } - if (!is_null($majorGridlines->getShadowProperty(array('size', 'sy')))) { - $objWriter->writeAttribute('sy', $majorGridlines->getShadowProperty(array('size', 'sy'))); + if (!is_null($majorGridlines->getShadowProperty(['size', 'sy']))) { + $objWriter->writeAttribute('sy', $majorGridlines->getShadowProperty(['size', 'sy'])); } - if (!is_null($majorGridlines->getShadowProperty(array('size', 'kx')))) { - $objWriter->writeAttribute('kx', $majorGridlines->getShadowProperty(array('size', 'kx'))); + if (!is_null($majorGridlines->getShadowProperty(['size', 'kx']))) { + $objWriter->writeAttribute('kx', $majorGridlines->getShadowProperty(['size', 'kx'])); } if (!is_null($majorGridlines->getShadowProperty('rotWithShape'))) { $objWriter->writeAttribute('rotWithShape', $majorGridlines->getShadowProperty('rotWithShape')); } - $objWriter->startElement("a:{$majorGridlines->getShadowProperty(array('color', 'type'))}"); - $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'value'))); + $objWriter->startElement("a:{$majorGridlines->getShadowProperty(['color', 'type'])}"); + $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(['color', 'value'])); $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'alpha'))); + $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(['color', 'alpha'])); $objWriter->endElement(); //end alpha $objWriter->endElement(); //end color:type @@ -709,17 +710,17 @@ class Chart extends WriterPart $objWriter->endElement(); } - if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) { + if (!is_null($minorGridlines->getLineStyleProperty(['arrow', 'head', 'type']))) { $objWriter->startElement('a:headEnd'); - $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type'))); + $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(['arrow', 'head', 'type'])); $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('head', 'w')); $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('head', 'len')); $objWriter->endElement(); } - if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) { + if (!is_null($minorGridlines->getLineStyleProperty(['arrow', 'end', 'type']))) { $objWriter->startElement('a:tailEnd'); - $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type'))); + $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(['arrow', 'end', 'type'])); $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('end', 'w')); $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('end', 'len')); $objWriter->endElement(); @@ -755,22 +756,22 @@ class Chart extends WriterPart if (!is_null($minorGridlines->getShadowProperty('algn'))) { $objWriter->writeAttribute('algn', $minorGridlines->getShadowProperty('algn')); } - if (!is_null($minorGridlines->getShadowProperty(array('size', 'sx')))) { - $objWriter->writeAttribute('sx', $minorGridlines->getShadowProperty(array('size', 'sx'))); + if (!is_null($minorGridlines->getShadowProperty(['size', 'sx']))) { + $objWriter->writeAttribute('sx', $minorGridlines->getShadowProperty(['size', 'sx'])); } - if (!is_null($minorGridlines->getShadowProperty(array('size', 'sy')))) { - $objWriter->writeAttribute('sy', $minorGridlines->getShadowProperty(array('size', 'sy'))); + if (!is_null($minorGridlines->getShadowProperty(['size', 'sy']))) { + $objWriter->writeAttribute('sy', $minorGridlines->getShadowProperty(['size', 'sy'])); } - if (!is_null($minorGridlines->getShadowProperty(array('size', 'kx')))) { - $objWriter->writeAttribute('kx', $minorGridlines->getShadowProperty(array('size', 'kx'))); + if (!is_null($minorGridlines->getShadowProperty(['size', 'kx']))) { + $objWriter->writeAttribute('kx', $minorGridlines->getShadowProperty(['size', 'kx'])); } if (!is_null($minorGridlines->getShadowProperty('rotWithShape'))) { $objWriter->writeAttribute('rotWithShape', $minorGridlines->getShadowProperty('rotWithShape')); } - $objWriter->startElement("a:{$minorGridlines->getShadowProperty(array('color', 'type'))}"); - $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'value'))); + $objWriter->startElement("a:{$minorGridlines->getShadowProperty(['color', 'type'])}"); + $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(['color', 'value'])); $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'alpha'))); + $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(['color', 'alpha'])); $objWriter->endElement(); //end alpha $objWriter->endElement(); //end color:type $objWriter->endElement(); //end shadow @@ -849,7 +850,7 @@ class Chart extends WriterPart if (!is_null($xAxis->getFillProperty('value'))) { $objWriter->startElement('a:solidFill'); - $objWriter->startElement("a:" . $xAxis->getFillProperty('type')); + $objWriter->startElement('a:' . $xAxis->getFillProperty('type')); $objWriter->writeAttribute('val', $xAxis->getFillProperty('value')); $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', $xAxis->getFillProperty('alpha')); @@ -866,7 +867,7 @@ class Chart extends WriterPart if (!is_null($xAxis->getLineProperty('value'))) { $objWriter->startElement('a:solidFill'); - $objWriter->startElement("a:" . $xAxis->getLineProperty('type')); + $objWriter->startElement('a:' . $xAxis->getLineProperty('type')); $objWriter->writeAttribute('val', $xAxis->getLineProperty('value')); $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', $xAxis->getLineProperty('alpha')); @@ -888,17 +889,17 @@ class Chart extends WriterPart $objWriter->endElement(); } - if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'head', 'type')))) { + if (!is_null($xAxis->getLineStyleProperty(['arrow', 'head', 'type']))) { $objWriter->startElement('a:headEnd'); - $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'head', 'type'))); + $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(['arrow', 'head', 'type'])); $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('head')); $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('head')); $objWriter->endElement(); } - if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'end', 'type')))) { + if (!is_null($xAxis->getLineStyleProperty(['arrow', 'end', 'type']))) { $objWriter->startElement('a:tailEnd'); - $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'end', 'type'))); + $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(['arrow', 'end', 'type'])); $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('end')); $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('end')); $objWriter->endElement(); @@ -911,10 +912,10 @@ class Chart extends WriterPart if (!is_null($xAxis->getGlowProperty('size'))) { $objWriter->startElement('a:glow'); $objWriter->writeAttribute('rad', $xAxis->getGlowProperty('size')); - $objWriter->startElement("a:{$xAxis->getGlowProperty(array('color','type'))}"); - $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','value'))); + $objWriter->startElement("a:{$xAxis->getGlowProperty(['color', 'type'])}"); + $objWriter->writeAttribute('val', $xAxis->getGlowProperty(['color', 'value'])); $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','alpha'))); + $objWriter->writeAttribute('val', $xAxis->getGlowProperty(['color', 'alpha'])); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); @@ -935,23 +936,23 @@ class Chart extends WriterPart if (!is_null($xAxis->getShadowProperty('algn'))) { $objWriter->writeAttribute('algn', $xAxis->getShadowProperty('algn')); } - if (!is_null($xAxis->getShadowProperty(array('size','sx')))) { - $objWriter->writeAttribute('sx', $xAxis->getShadowProperty(array('size','sx'))); + if (!is_null($xAxis->getShadowProperty(['size', 'sx']))) { + $objWriter->writeAttribute('sx', $xAxis->getShadowProperty(['size', 'sx'])); } - if (!is_null($xAxis->getShadowProperty(array('size','sy')))) { - $objWriter->writeAttribute('sy', $xAxis->getShadowProperty(array('size','sy'))); + if (!is_null($xAxis->getShadowProperty(['size', 'sy']))) { + $objWriter->writeAttribute('sy', $xAxis->getShadowProperty(['size', 'sy'])); } - if (!is_null($xAxis->getShadowProperty(array('size','kx')))) { - $objWriter->writeAttribute('kx', $xAxis->getShadowProperty(array('size','kx'))); + if (!is_null($xAxis->getShadowProperty(['size', 'kx']))) { + $objWriter->writeAttribute('kx', $xAxis->getShadowProperty(['size', 'kx'])); } if (!is_null($xAxis->getShadowProperty('rotWithShape'))) { $objWriter->writeAttribute('rotWithShape', $xAxis->getShadowProperty('rotWithShape')); } - $objWriter->startElement("a:{$xAxis->getShadowProperty(array('color','type'))}"); - $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','value'))); + $objWriter->startElement("a:{$xAxis->getShadowProperty(['color', 'type'])}"); + $objWriter->writeAttribute('val', $xAxis->getShadowProperty(['color', 'value'])); $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','alpha'))); + $objWriter->writeAttribute('val', $xAxis->getShadowProperty(['color', 'alpha'])); $objWriter->endElement(); $objWriter->endElement(); @@ -983,7 +984,7 @@ class Chart extends WriterPart } $objWriter->startElement('c:crossBetween'); - $objWriter->writeAttribute('val', "midCat"); + $objWriter->writeAttribute('val', 'midCat'); $objWriter->endElement(); if (!is_null($xAxis->getAxisOptionsProperty('major_unit'))) { @@ -1015,17 +1016,17 @@ class Chart extends WriterPart * * @param PlotArea $plotArea * - * @return string|array * @throws \PhpSpreadsheet\Writer\Exception + * @return string|array */ private static function getChartType($plotArea) { $groupCount = $plotArea->getPlotGroupCount(); if ($groupCount == 1) { - $chartType = array($plotArea->getPlotGroupByIndex(0)->getPlotType()); + $chartType = [$plotArea->getPlotGroupByIndex(0)->getPlotType()]; } else { - $chartTypes = array(); + $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType(); } @@ -1044,8 +1045,8 @@ class Chart extends WriterPart * @param DataSeries $plotGroup * @param string $groupType Type of plot for dataseries * @param \PhpSpreadsheet\Shared\XMLWriter $objWriter XML Writer - * @param boolean &$catIsMultiLevelSeries Is category a multi-series category - * @param boolean &$valIsMultiLevelSeries Is value set a multi-series set + * @param bool &$catIsMultiLevelSeries Is category a multi-series category + * @param bool &$valIsMultiLevelSeries Is value set a multi-series set * @param string &$plotGroupingType Type of grouping for multi-series values * @param \PhpSpreadsheet\Worksheet $pSheet * @@ -1518,7 +1519,7 @@ class Chart extends WriterPart $objWriter->endElement(); $objWriter->startElement('c:pageSetup'); - $objWriter->writeAttribute('orientation', "portrait"); + $objWriter->writeAttribute('orientation', 'portrait'); $objWriter->endElement(); $objWriter->endElement(); diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Comments.php b/src/PhpSpreadsheet/Writer/Excel2007/Comments.php index 4be5d18c..2e7b034f 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Comments.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Comments.php @@ -1,4 +1,5 @@ startDocument('1.0', 'UTF-8', 'yes'); // Comments cache - $comments = $pWorksheet->getComments(); + $comments = $pWorksheet->getComments(); // Authors cache - $authors = array(); - $authorId = 0; + $authors = []; + $authorId = 0; foreach ($comments as $comment) { if (!isset($authors[$comment->getAuthor()])) { $authors[$comment->getAuthor()] = $authorId++; @@ -109,8 +110,8 @@ class Comments extends WriterPart * Write VML comments to XML format * * @param \PhpSpreadsheet\Worksheet $pWorksheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeVMLComments(\PhpSpreadsheet\Worksheet $pWorksheet = null) { @@ -126,7 +127,7 @@ class Comments extends WriterPart $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Comments cache - $comments = $pWorksheet->getComments(); + $comments = $pWorksheet->getComments(); // xml $objWriter->startElement('xml'); @@ -140,9 +141,9 @@ class Comments extends WriterPart // o:idmap $objWriter->startElement('o:idmap'); - $objWriter->writeAttribute('v:ext', 'edit'); - $objWriter->writeAttribute('data', '1'); - $objWriter->endElement(); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('data', '1'); + $objWriter->endElement(); $objWriter->endElement(); @@ -155,14 +156,14 @@ class Comments extends WriterPart // v:stroke $objWriter->startElement('v:stroke'); - $objWriter->writeAttribute('joinstyle', 'miter'); - $objWriter->endElement(); + $objWriter->writeAttribute('joinstyle', 'miter'); + $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); - $objWriter->writeAttribute('gradientshapeok', 't'); - $objWriter->writeAttribute('o:connecttype', 'rect'); - $objWriter->endElement(); + $objWriter->writeAttribute('gradientshapeok', 't'); + $objWriter->writeAttribute('o:connecttype', 'rect'); + $objWriter->endElement(); $objWriter->endElement(); @@ -187,11 +188,11 @@ class Comments extends WriterPart */ private function writeVMLComment(\PhpSpreadsheet\Shared\XMLWriter $objWriter = null, $pCellReference = 'A1', \PhpSpreadsheet\Comment $pComment = null) { - // Metadata + // Metadata list($column, $row) = \PhpSpreadsheet\Cell::coordinateFromString($pCellReference); - $column = \PhpSpreadsheet\Cell::columnIndexFromString($column); - $id = 1024 + $column + $row; - $id = substr($id, 0, 4); + $column = \PhpSpreadsheet\Cell::columnIndexFromString($column); + $id = 1024 + $column + $row; + $id = substr($id, 0, 4); // v:shape $objWriter->startElement('v:shape'); @@ -203,35 +204,35 @@ class Comments extends WriterPart // v:fill $objWriter->startElement('v:fill'); - $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB()); - $objWriter->endElement(); + $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->endElement(); // v:shadow $objWriter->startElement('v:shadow'); - $objWriter->writeAttribute('on', 't'); - $objWriter->writeAttribute('color', 'black'); - $objWriter->writeAttribute('obscured', 't'); - $objWriter->endElement(); + $objWriter->writeAttribute('on', 't'); + $objWriter->writeAttribute('color', 'black'); + $objWriter->writeAttribute('obscured', 't'); + $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); - $objWriter->writeAttribute('o:connecttype', 'none'); - $objWriter->endElement(); + $objWriter->writeAttribute('o:connecttype', 'none'); + $objWriter->endElement(); // v:textbox $objWriter->startElement('v:textbox'); - $objWriter->writeAttribute('style', 'mso-direction-alt:auto'); + $objWriter->writeAttribute('style', 'mso-direction-alt:auto'); // div $objWriter->startElement('div'); - $objWriter->writeAttribute('style', 'text-align:left'); - $objWriter->endElement(); + $objWriter->writeAttribute('style', 'text-align:left'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // x:ClientData $objWriter->startElement('x:ClientData'); - $objWriter->writeAttribute('ObjectType', 'Note'); + $objWriter->writeAttribute('ObjectType', 'Note'); // x:MoveWithCells $objWriter->writeElement('x:MoveWithCells', ''); @@ -251,7 +252,7 @@ class Comments extends WriterPart // x:Column $objWriter->writeElement('x:Column', ($column - 1)); - $objWriter->endElement(); + $objWriter->endElement(); $objWriter->endElement(); } diff --git a/src/PhpSpreadsheet/Writer/Excel2007/ContentTypes.php b/src/PhpSpreadsheet/Writer/Excel2007/ContentTypes.php index 32e2e957..08463c1c 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/ContentTypes.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/ContentTypes.php @@ -1,4 +1,5 @@ writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml'); //... and define a new type for the VBA project $this->writeDefaultContentType($objWriter, 'bin', 'application/vnd.ms-office.vbaProject'); - if ($spreadsheet->hasMacrosCertificate()) {// signed macros ? + if ($spreadsheet->hasMacrosCertificate()) { + // signed macros ? // Yes : add needed information $this->writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature'); } - } else {// no macros in workbook, so standard type + } else { + // no macros in workbook, so standard type $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); } @@ -126,11 +129,11 @@ class ContentTypes extends WriterPart } // Add media content-types - $aMediaContentTypes = array(); + $aMediaContentTypes = []; $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count(); for ($i = 0; $i < $mediaCount; ++$i) { - $extension = ''; - $mimeType = ''; + $extension = ''; + $mimeType = ''; if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof \PhpSpreadsheet\Worksheet\Drawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); @@ -152,9 +155,9 @@ class ContentTypes extends WriterPart if ($spreadsheet->hasRibbonBinObjects()) { // Some additional objects in the ribbon ? // we need to write "Extension" but not already write for media content - $tabRibbonTypes=array_diff($spreadsheet->getRibbonBinObjects('types'), array_keys($aMediaContentTypes)); + $tabRibbonTypes = array_diff($spreadsheet->getRibbonBinObjects('types'), array_keys($aMediaContentTypes)); foreach ($tabRibbonTypes as $aRibbonType) { - $mimeType='image/.'.$aRibbonType;//we wrote $mimeType like customUI Editor + $mimeType = 'image/.' . $aRibbonType;//we wrote $mimeType like customUI Editor $this->writeDefaultContentType($objWriter, $aRibbonType, $mimeType); } } @@ -181,13 +184,14 @@ class ContentTypes extends WriterPart * Get image mime type * * @param string $pFile Filename - * @return string Mime Type * @throws \PhpSpreadsheet\Writer\Exception + * @return string Mime Type */ private function getImageMimeType($pFile = '') { if (\PhpSpreadsheet\Shared\File::fileExists($pFile)) { $image = getimagesize($pFile); + return image_type_to_mime_type($image[2]); } else { throw new \PhpSpreadsheet\Writer\Exception("File $pFile does not exist"); @@ -211,7 +215,7 @@ class ContentTypes extends WriterPart $objWriter->writeAttribute('ContentType', $pContentType); $objWriter->endElement(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid parameters passed.'); } } @@ -232,7 +236,7 @@ class ContentTypes extends WriterPart $objWriter->writeAttribute('ContentType', $pContentType); $objWriter->endElement(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid parameters passed.'); } } } diff --git a/src/PhpSpreadsheet/Writer/Excel2007/DocProps.php b/src/PhpSpreadsheet/Writer/Excel2007/DocProps.php index 767ee70c..0a0f46c5 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/DocProps.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/DocProps.php @@ -1,4 +1,5 @@ writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties'); $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); - foreach ($customPropertyList as $key => $customProperty) { $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); $objWriter->startElement('property'); $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}'); - $objWriter->writeAttribute('pid', $key+2); + $objWriter->writeAttribute('pid', $key + 2); $objWriter->writeAttribute('name', $customProperty); switch ($propertyType) { @@ -252,7 +252,6 @@ class DocProps extends WriterPart $objWriter->endElement(); } - $objWriter->endElement(); return $objWriter->getData(); diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Drawing.php b/src/PhpSpreadsheet/Writer/Excel2007/Drawing.php index bab597f0..a082326a 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Drawing.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Drawing.php @@ -1,4 +1,5 @@ 0) { for ($c = 0; $c < $chartCount; ++$c) { - $this->writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i); + $this->writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c + $i); } } } @@ -97,57 +98,57 @@ class Drawing extends WriterPart $objWriter->startElement('xdr:twoCellAnchor'); - $objWriter->startElement('xdr:from'); - $objWriter->writeElement('xdr:col', \PhpSpreadsheet\Cell::columnIndexFromString($tl['colRow'][0]) - 1); - $objWriter->writeElement('xdr:colOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['xOffset'])); - $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1); - $objWriter->writeElement('xdr:rowOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['yOffset'])); - $objWriter->endElement(); - $objWriter->startElement('xdr:to'); - $objWriter->writeElement('xdr:col', \PhpSpreadsheet\Cell::columnIndexFromString($br['colRow'][0]) - 1); - $objWriter->writeElement('xdr:colOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['xOffset'])); - $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1); - $objWriter->writeElement('xdr:rowOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['yOffset'])); - $objWriter->endElement(); + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', \PhpSpreadsheet\Cell::columnIndexFromString($tl['colRow'][0]) - 1); + $objWriter->writeElement('xdr:colOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['xOffset'])); + $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1); + $objWriter->writeElement('xdr:rowOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['yOffset'])); + $objWriter->endElement(); + $objWriter->startElement('xdr:to'); + $objWriter->writeElement('xdr:col', \PhpSpreadsheet\Cell::columnIndexFromString($br['colRow'][0]) - 1); + $objWriter->writeElement('xdr:colOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['xOffset'])); + $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1); + $objWriter->writeElement('xdr:rowOff', \PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['yOffset'])); + $objWriter->endElement(); - $objWriter->startElement('xdr:graphicFrame'); - $objWriter->writeAttribute('macro', ''); - $objWriter->startElement('xdr:nvGraphicFramePr'); - $objWriter->startElement('xdr:cNvPr'); - $objWriter->writeAttribute('name', 'Chart '.$pRelationId); - $objWriter->writeAttribute('id', 1025 * $pRelationId); - $objWriter->endElement(); - $objWriter->startElement('xdr:cNvGraphicFramePr'); - $objWriter->startElement('a:graphicFrameLocks'); - $objWriter->endElement(); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->startElement('xdr:graphicFrame'); + $objWriter->writeAttribute('macro', ''); + $objWriter->startElement('xdr:nvGraphicFramePr'); + $objWriter->startElement('xdr:cNvPr'); + $objWriter->writeAttribute('name', 'Chart ' . $pRelationId); + $objWriter->writeAttribute('id', 1025 * $pRelationId); + $objWriter->endElement(); + $objWriter->startElement('xdr:cNvGraphicFramePr'); + $objWriter->startElement('a:graphicFrameLocks'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->startElement('xdr:xfrm'); - $objWriter->startElement('a:off'); - $objWriter->writeAttribute('x', '0'); - $objWriter->writeAttribute('y', '0'); - $objWriter->endElement(); - $objWriter->startElement('a:ext'); - $objWriter->writeAttribute('cx', '0'); - $objWriter->writeAttribute('cy', '0'); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->startElement('xdr:xfrm'); + $objWriter->startElement('a:off'); + $objWriter->writeAttribute('x', '0'); + $objWriter->writeAttribute('y', '0'); + $objWriter->endElement(); + $objWriter->startElement('a:ext'); + $objWriter->writeAttribute('cx', '0'); + $objWriter->writeAttribute('cy', '0'); + $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->startElement('a:graphic'); - $objWriter->startElement('a:graphicData'); - $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - $objWriter->startElement('c:chart'); - $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $objWriter->writeAttribute('r:id', 'rId'.$pRelationId); - $objWriter->endElement(); - $objWriter->endElement(); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->startElement('a:graphic'); + $objWriter->startElement('a:graphicData'); + $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->startElement('c:chart'); + $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $objWriter->writeAttribute('r:id', 'rId' . $pRelationId); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->startElement('xdr:clientData'); - $objWriter->endElement(); + $objWriter->startElement('xdr:clientData'); + $objWriter->endElement(); $objWriter->endElement(); } @@ -166,8 +167,8 @@ class Drawing extends WriterPart // xdr:oneCellAnchor $objWriter->startElement('xdr:oneCellAnchor'); // Image location - $aCoordinates = \PhpSpreadsheet\Cell::coordinateFromString($pDrawing->getCoordinates()); - $aCoordinates[0] = \PhpSpreadsheet\Cell::columnIndexFromString($aCoordinates[0]); + $aCoordinates = \PhpSpreadsheet\Cell::coordinateFromString($pDrawing->getCoordinates()); + $aCoordinates[0] = \PhpSpreadsheet\Cell::columnIndexFromString($aCoordinates[0]); // xdr:from $objWriter->startElement('xdr:from'); @@ -219,7 +220,7 @@ class Drawing extends WriterPart // a:stretch $objWriter->startElement('a:stretch'); - $objWriter->writeElement('a:fillRect', null); + $objWriter->writeElement('a:fillRect', null); $objWriter->endElement(); $objWriter->endElement(); @@ -366,7 +367,7 @@ class Drawing extends WriterPart $objWriter->endElement(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid parameters passed.'); } } @@ -374,8 +375,8 @@ class Drawing extends WriterPart * Write VML header/footer images to XML format * * @param \PhpSpreadsheet\Worksheet $pWorksheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeVMLHeaderFooterImages(\PhpSpreadsheet\Worksheet $pWorksheet = null) { @@ -559,18 +560,17 @@ class Drawing extends WriterPart $objWriter->endElement(); } - /** * Get an array of all drawings * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return \PhpSpreadsheet\Worksheet\Drawing[] All drawings in PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Worksheet\Drawing[] All drawings in PhpSpreadsheet */ public function allDrawings(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { // Get an array of all drawings - $aDrawings = array(); + $aDrawings = []; // Loop through PhpSpreadsheet $sheetCount = $spreadsheet->getSheetCount(); @@ -580,7 +580,7 @@ class Drawing extends WriterPart while ($iterator->valid()) { $aDrawings[] = $iterator->current(); - $iterator->next(); + $iterator->next(); } } diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Rels.php b/src/PhpSpreadsheet/Writer/Excel2007/Rels.php index d8456dfe..67214d01 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Rels.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Rels.php @@ -1,4 +1,5 @@ getChartCollection(); } else { - $charts = array(); + $charts = []; } if (($pWorksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0)) { @@ -290,9 +291,9 @@ class Rels extends WriterPart * * @param \PhpSpreadsheet\Worksheet $pWorksheet * @param int &$chartRef Chart ID - * @param boolean $includeCharts Flag indicating if we should write charts - * @return string XML Output + * @param bool $includeCharts Flag indicating if we should write charts * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeDrawingRelationships(\PhpSpreadsheet\Worksheet $pWorksheet, &$chartRef, $includeCharts = false) { @@ -354,8 +355,8 @@ class Rels extends WriterPart * Write header/footer drawing relationships to XML format * * @param \PhpSpreadsheet\Worksheet $pWorksheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeHeaderFooterDrawingRelationships(\PhpSpreadsheet\Worksheet $pWorksheet = null) { @@ -415,7 +416,7 @@ class Rels extends WriterPart $objWriter->endElement(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid parameters passed.'); } } } diff --git a/src/PhpSpreadsheet/Writer/Excel2007/RelsRibbon.php b/src/PhpSpreadsheet/Writer/Excel2007/RelsRibbon.php index b66f7548..649ccdc8 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/RelsRibbon.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/RelsRibbon.php @@ -1,4 +1,5 @@ getDataType() == \PhpSpreadsheet\Cell\DataType::TYPE_STRING || $cell->getDataType() == \PhpSpreadsheet\Cell\DataType::TYPE_STRING2 || $cell->getDataType() == \PhpSpreadsheet\Cell\DataType::TYPE_NULL)) { - $aStringTable[] = $cellValue; - $aFlippedStringTable[$cellValue] = true; + $aStringTable[] = $cellValue; + $aFlippedStringTable[$cellValue] = true; } elseif ($cellValue instanceof \PhpSpreadsheet\RichText && ($cellValue !== null) && !isset($aFlippedStringTable[$cellValue->getHashCode()])) { - $aStringTable[] = $cellValue; - $aFlippedStringTable[$cellValue->getHashCode()] = true; + $aStringTable[] = $cellValue; + $aFlippedStringTable[$cellValue->getHashCode()] = true; } } @@ -79,8 +79,8 @@ class StringTable extends WriterPart * Write string table to XML format * * @param string[] $pStringTable - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeStringTable($pStringTable = null) { @@ -105,7 +105,7 @@ class StringTable extends WriterPart foreach ($pStringTable as $textElement) { $objWriter->startElement('si'); - if (! $textElement instanceof \PhpSpreadsheet\RichText) { + if (!$textElement instanceof \PhpSpreadsheet\RichText) { $textToWrite = \PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($textElement); $objWriter->startElement('t'); if ($textToWrite !== trim($textToWrite)) { @@ -124,7 +124,7 @@ class StringTable extends WriterPart return $objWriter->getData(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid string table array passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid string table array passed.'); } } @@ -146,31 +146,31 @@ class StringTable extends WriterPart $elements = $pRichText->getRichTextElements(); foreach ($elements as $element) { // r - $objWriter->startElement($prefix.'r'); + $objWriter->startElement($prefix . 'r'); // rPr if ($element instanceof \PhpSpreadsheet\RichText\Run) { // rPr - $objWriter->startElement($prefix.'rPr'); + $objWriter->startElement($prefix . 'rPr'); // rFont - $objWriter->startElement($prefix.'rFont'); + $objWriter->startElement($prefix . 'rFont'); $objWriter->writeAttribute('val', $element->getFont()->getName()); $objWriter->endElement(); // Bold - $objWriter->startElement($prefix.'b'); + $objWriter->startElement($prefix . 'b'); $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false')); $objWriter->endElement(); // Italic - $objWriter->startElement($prefix.'i'); + $objWriter->startElement($prefix . 'i'); $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false')); $objWriter->endElement(); // Superscript / subscript if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) { - $objWriter->startElement($prefix.'vertAlign'); + $objWriter->startElement($prefix . 'vertAlign'); if ($element->getFont()->getSuperScript()) { $objWriter->writeAttribute('val', 'superscript'); } elseif ($element->getFont()->getSubScript()) { @@ -180,22 +180,22 @@ class StringTable extends WriterPart } // Strikethrough - $objWriter->startElement($prefix.'strike'); + $objWriter->startElement($prefix . 'strike'); $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false')); $objWriter->endElement(); // Color - $objWriter->startElement($prefix.'color'); + $objWriter->startElement($prefix . 'color'); $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB()); $objWriter->endElement(); // Size - $objWriter->startElement($prefix.'sz'); + $objWriter->startElement($prefix . 'sz'); $objWriter->writeAttribute('val', $element->getFont()->getSize()); $objWriter->endElement(); // Underline - $objWriter->startElement($prefix.'u'); + $objWriter->startElement($prefix . 'u'); $objWriter->writeAttribute('val', $element->getFont()->getUnderline()); $objWriter->endElement(); @@ -203,7 +203,7 @@ class StringTable extends WriterPart } // t - $objWriter->startElement($prefix.'t'); + $objWriter->startElement($prefix . 't'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeRawData(\PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($element->getText())); $objWriter->endElement(); @@ -236,10 +236,10 @@ class StringTable extends WriterPart $elements = $pRichText->getRichTextElements(); foreach ($elements as $element) { // r - $objWriter->startElement($prefix.'r'); + $objWriter->startElement($prefix . 'r'); // rPr - $objWriter->startElement($prefix.'rPr'); + $objWriter->startElement($prefix . 'rPr'); // Bold $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0)); @@ -260,8 +260,8 @@ class StringTable extends WriterPart $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike')); // rFont - $objWriter->startElement($prefix.'latin'); - $objWriter->writeAttribute('typeface', $element->getFont()->getName()); + $objWriter->startElement($prefix . 'latin'); + $objWriter->writeAttribute('typeface', $element->getFont()->getName()); $objWriter->endElement(); // Superscript / subscript @@ -278,7 +278,7 @@ class StringTable extends WriterPart $objWriter->endElement(); // t - $objWriter->startElement($prefix.'t'); + $objWriter->startElement($prefix . 't'); // $objWriter->writeAttribute('xml:space', 'preserve'); // Excel2010 accepts, Excel2007 complains $objWriter->writeRawData(\PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($element->getText())); $objWriter->endElement(); @@ -293,14 +293,14 @@ class StringTable extends WriterPart * @param array $stringTable Stringtable * @return array */ - public function flipStringTable($stringTable = array()) + public function flipStringTable($stringTable = []) { // Return value - $returnValue = array(); + $returnValue = []; // Loop through stringtable and add flipped items to $returnValue foreach ($stringTable as $key => $value) { - if (! $value instanceof \PhpSpreadsheet\RichText) { + if (!$value instanceof \PhpSpreadsheet\RichText) { $returnValue[$value] = $key; } elseif ($value instanceof \PhpSpreadsheet\RichText) { $returnValue[$value->getHashCode()] = $key; diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Style.php b/src/PhpSpreadsheet/Writer/Excel2007/Style.php index 180a4b79..868138fc 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Style.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Style.php @@ -1,4 +1,5 @@ startElement('xf'); $objWriter->writeAttribute('xfId', 0); - $objWriter->writeAttribute('fontId', (int)$this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode())); + $objWriter->writeAttribute('fontId', (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode())); if ($pStyle->getQuotePrefix()) { $objWriter->writeAttribute('quotePrefix', 1); } if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) { - $objWriter->writeAttribute('numFmtId', (int)($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164)); + $objWriter->writeAttribute('numFmtId', (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164)); } else { - $objWriter->writeAttribute('numFmtId', (int)$pStyle->getNumberFormat()->getBuiltInFormatCode()); + $objWriter->writeAttribute('numFmtId', (int) $pStyle->getNumberFormat()->getBuiltInFormatCode()); } - $objWriter->writeAttribute('fillId', (int)$this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode())); - $objWriter->writeAttribute('borderId', (int)$this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode())); + $objWriter->writeAttribute('fillId', (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode())); + $objWriter->writeAttribute('borderId', (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode())); // Apply styles? $objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0'); @@ -563,8 +564,8 @@ class Style extends WriterPart * Get an array of all styles * * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return \PhpSpreadsheet\Style[] All styles in PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Style[] All styles in PhpSpreadsheet */ public function allStyles(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { @@ -575,13 +576,13 @@ class Style extends WriterPart * Get an array of all conditional styles * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return \PhpSpreadsheet\Style\Conditional[] All conditional styles in PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Style\Conditional[] All conditional styles in PhpSpreadsheet */ public function allConditionalStyles(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { // Get an array of all styles - $aStyles = array(); + $aStyles = []; $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { @@ -599,13 +600,13 @@ class Style extends WriterPart * Get an array of all fills * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return \PhpSpreadsheet\Style\Fill[] All fills in PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Style\Fill[] All fills in PhpSpreadsheet */ public function allFills(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { // Get an array of unique fills - $aFills = array(); + $aFills = []; // Two first fills are predefined $fill0 = new \PhpSpreadsheet\Style\Fill(); @@ -631,13 +632,13 @@ class Style extends WriterPart * Get an array of all fonts * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return \PhpSpreadsheet\Style\Font[] All fonts in PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Style\Font[] All fonts in PhpSpreadsheet */ public function allFonts(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { // Get an array of unique fonts - $aFonts = array(); + $aFonts = []; $aStyles = $this->allStyles($spreadsheet); /** @var \PhpSpreadsheet\Style $style */ @@ -654,13 +655,13 @@ class Style extends WriterPart * Get an array of all borders * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return \PhpSpreadsheet\Style\Borders[] All borders in PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Style\Borders[] All borders in PhpSpreadsheet */ public function allBorders(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { // Get an array of unique borders - $aBorders = array(); + $aBorders = []; $aStyles = $this->allStyles($spreadsheet); /** @var \PhpSpreadsheet\Style $style */ @@ -677,13 +678,13 @@ class Style extends WriterPart * Get an array of all number formats * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return \PhpSpreadsheet\Style\NumberFormat[] All number formats in PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Style\NumberFormat[] All number formats in PhpSpreadsheet */ public function allNumberFormats(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { // Get an array of unique number formats - $aNumFmts = array(); + $aNumFmts = []; $aStyles = $this->allStyles($spreadsheet); /** @var \PhpSpreadsheet\Style $style */ diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Theme.php b/src/PhpSpreadsheet/Writer/Excel2007/Theme.php index 20a3a872..b72a05b9 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Theme.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Theme.php @@ -27,7 +27,6 @@ namespace PhpSpreadsheet\Writer\Excel2007; * @version ##VERSION##, ##DATE## */ - /** * @category PhpSpreadsheet * @copyright Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) @@ -37,9 +36,8 @@ class Theme extends WriterPart /** * Map of Major fonts to write * @static array of string - * */ - private static $majorFonts = array( + private static $majorFonts = [ 'Jpan' => 'MS Pゴシック', 'Hang' => '맑은 고딕', 'Hans' => '宋体', @@ -70,14 +68,13 @@ class Theme extends WriterPart 'Viet' => 'Times New Roman', 'Uigh' => 'Microsoft Uighur', 'Geor' => 'Sylfaen', - ); + ]; /** * Map of Minor fonts to write * @static array of string - * */ - private static $minorFonts = array( + private static $minorFonts = [ 'Jpan' => 'MS Pゴシック', 'Hang' => '맑은 고딕', 'Hans' => '宋体', @@ -108,32 +105,31 @@ class Theme extends WriterPart 'Viet' => 'Arial', 'Uigh' => 'Microsoft Uighur', 'Geor' => 'Sylfaen', - ); + ]; /** * Map of core colours * @static array of string - * */ - private static $colourScheme = array( - 'dk2' => '1F497D', - 'lt2' => 'EEECE1', - 'accent1' => '4F81BD', - 'accent2' => 'C0504D', - 'accent3' => '9BBB59', - 'accent4' => '8064A2', - 'accent5' => '4BACC6', - 'accent6' => 'F79646', - 'hlink' => '0000FF', - 'folHlink' => '800080', - ); + private static $colourScheme = [ + 'dk2' => '1F497D', + 'lt2' => 'EEECE1', + 'accent1' => '4F81BD', + 'accent2' => 'C0504D', + 'accent3' => '9BBB59', + 'accent4' => '8064A2', + 'accent5' => '4BACC6', + 'accent6' => 'F79646', + 'hlink' => '0000FF', + 'folHlink' => '800080', + ]; /** * Write theme to XML format * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeTheme(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { @@ -158,54 +154,54 @@ class Theme extends WriterPart // a:clrScheme $objWriter->startElement('a:clrScheme'); - $objWriter->writeAttribute('name', 'Office'); + $objWriter->writeAttribute('name', 'Office'); // a:dk1 $objWriter->startElement('a:dk1'); // a:sysClr $objWriter->startElement('a:sysClr'); - $objWriter->writeAttribute('val', 'windowText'); - $objWriter->writeAttribute('lastClr', '000000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'windowText'); + $objWriter->writeAttribute('lastClr', '000000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:lt1 $objWriter->startElement('a:lt1'); // a:sysClr $objWriter->startElement('a:sysClr'); - $objWriter->writeAttribute('val', 'window'); - $objWriter->writeAttribute('lastClr', 'FFFFFF'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'window'); + $objWriter->writeAttribute('lastClr', 'FFFFFF'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:dk2 $this->writeColourScheme($objWriter); - $objWriter->endElement(); + $objWriter->endElement(); // a:fontScheme $objWriter->startElement('a:fontScheme'); - $objWriter->writeAttribute('name', 'Office'); + $objWriter->writeAttribute('name', 'Office'); // a:majorFont $objWriter->startElement('a:majorFont'); - $this->writeFonts($objWriter, 'Cambria', self::$majorFonts); - $objWriter->endElement(); + $this->writeFonts($objWriter, 'Cambria', self::$majorFonts); + $objWriter->endElement(); // a:minorFont $objWriter->startElement('a:minorFont'); - $this->writeFonts($objWriter, 'Calibri', self::$minorFonts); - $objWriter->endElement(); + $this->writeFonts($objWriter, 'Calibri', self::$minorFonts); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:fmtScheme $objWriter->startElement('a:fmtScheme'); - $objWriter->writeAttribute('name', 'Office'); + $objWriter->writeAttribute('name', 'Office'); // a:fillStyleLst $objWriter->startElement('a:fillStyleLst'); @@ -215,268 +211,266 @@ class Theme extends WriterPart // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); - $objWriter->writeAttribute('rotWithShape', '1'); + $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '0'); + $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); - $objWriter->writeAttribute('val', '50000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '50000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '300000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '35000'); + $objWriter->writeAttribute('pos', '35000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); - $objWriter->writeAttribute('val', '37000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '37000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '300000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '100000'); + $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); - $objWriter->writeAttribute('val', '15000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '15000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '350000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:lin $objWriter->startElement('a:lin'); - $objWriter->writeAttribute('ang', '16200000'); - $objWriter->writeAttribute('scaled', '1'); - $objWriter->endElement(); + $objWriter->writeAttribute('ang', '16200000'); + $objWriter->writeAttribute('scaled', '1'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); - $objWriter->writeAttribute('rotWithShape', '1'); + $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '0'); + $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); - $objWriter->writeAttribute('val', '51000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '51000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '130000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '130000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '80000'); + $objWriter->writeAttribute('pos', '80000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); - $objWriter->writeAttribute('val', '93000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '93000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '130000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '130000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '100000'); + $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); - $objWriter->writeAttribute('val', '94000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '94000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '135000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '135000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:lin $objWriter->startElement('a:lin'); - $objWriter->writeAttribute('ang', '16200000'); - $objWriter->writeAttribute('scaled', '0'); - $objWriter->endElement(); + $objWriter->writeAttribute('ang', '16200000'); + $objWriter->writeAttribute('scaled', '0'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:lnStyleLst $objWriter->startElement('a:lnStyleLst'); // a:ln $objWriter->startElement('a:ln'); - $objWriter->writeAttribute('w', '9525'); - $objWriter->writeAttribute('cap', 'flat'); - $objWriter->writeAttribute('cmpd', 'sng'); - $objWriter->writeAttribute('algn', 'ctr'); + $objWriter->writeAttribute('w', '9525'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); - $objWriter->writeAttribute('val', '95000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '95000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '105000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '105000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); - $objWriter->writeAttribute('val', 'solid'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:ln $objWriter->startElement('a:ln'); - $objWriter->writeAttribute('w', '25400'); - $objWriter->writeAttribute('cap', 'flat'); - $objWriter->writeAttribute('cmpd', 'sng'); - $objWriter->writeAttribute('algn', 'ctr'); + $objWriter->writeAttribute('w', '25400'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); - $objWriter->writeAttribute('val', 'solid'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:ln $objWriter->startElement('a:ln'); - $objWriter->writeAttribute('w', '38100'); - $objWriter->writeAttribute('cap', 'flat'); - $objWriter->writeAttribute('cmpd', 'sng'); - $objWriter->writeAttribute('algn', 'ctr'); + $objWriter->writeAttribute('w', '38100'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); - $objWriter->writeAttribute('val', 'solid'); - $objWriter->endElement(); - - $objWriter->endElement(); - - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); // a:effectStyleLst $objWriter->startElement('a:effectStyleLst'); @@ -489,27 +483,27 @@ class Theme extends WriterPart // a:outerShdw $objWriter->startElement('a:outerShdw'); - $objWriter->writeAttribute('blurRad', '40000'); - $objWriter->writeAttribute('dist', '20000'); - $objWriter->writeAttribute('dir', '5400000'); - $objWriter->writeAttribute('rotWithShape', '0'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '20000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', '000000'); + $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', '38000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '38000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:effectStyle $objWriter->startElement('a:effectStyle'); @@ -519,27 +513,27 @@ class Theme extends WriterPart // a:outerShdw $objWriter->startElement('a:outerShdw'); - $objWriter->writeAttribute('blurRad', '40000'); - $objWriter->writeAttribute('dist', '23000'); - $objWriter->writeAttribute('dir', '5400000'); - $objWriter->writeAttribute('rotWithShape', '0'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '23000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', '000000'); + $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', '35000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '35000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:effectStyle $objWriter->startElement('a:effectStyle'); @@ -549,72 +543,72 @@ class Theme extends WriterPart // a:outerShdw $objWriter->startElement('a:outerShdw'); - $objWriter->writeAttribute('blurRad', '40000'); - $objWriter->writeAttribute('dist', '23000'); - $objWriter->writeAttribute('dir', '5400000'); - $objWriter->writeAttribute('rotWithShape', '0'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '23000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', '000000'); + $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', '35000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '35000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:scene3d $objWriter->startElement('a:scene3d'); // a:camera $objWriter->startElement('a:camera'); - $objWriter->writeAttribute('prst', 'orthographicFront'); + $objWriter->writeAttribute('prst', 'orthographicFront'); // a:rot $objWriter->startElement('a:rot'); - $objWriter->writeAttribute('lat', '0'); - $objWriter->writeAttribute('lon', '0'); - $objWriter->writeAttribute('rev', '0'); - $objWriter->endElement(); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '0'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:lightRig $objWriter->startElement('a:lightRig'); - $objWriter->writeAttribute('rig', 'threePt'); - $objWriter->writeAttribute('dir', 't'); + $objWriter->writeAttribute('rig', 'threePt'); + $objWriter->writeAttribute('dir', 't'); // a:rot $objWriter->startElement('a:rot'); - $objWriter->writeAttribute('lat', '0'); - $objWriter->writeAttribute('lon', '0'); - $objWriter->writeAttribute('rev', '1200000'); - $objWriter->endElement(); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '1200000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:sp3d $objWriter->startElement('a:sp3d'); // a:bevelT $objWriter->startElement('a:bevelT'); - $objWriter->writeAttribute('w', '63500'); - $objWriter->writeAttribute('h', '25400'); - $objWriter->endElement(); + $objWriter->writeAttribute('w', '63500'); + $objWriter->writeAttribute('h', '25400'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:bgFillStyleLst $objWriter->startElement('a:bgFillStyleLst'); @@ -624,181 +618,181 @@ class Theme extends WriterPart // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); - $objWriter->writeAttribute('rotWithShape', '1'); + $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '0'); + $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); - $objWriter->writeAttribute('val', '40000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '40000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '350000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '40000'); + $objWriter->writeAttribute('pos', '40000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); - $objWriter->writeAttribute('val', '45000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '45000'); + $objWriter->endElement(); // a:shade $objWriter->startElement('a:shade'); - $objWriter->writeAttribute('val', '99000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '99000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '350000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '100000'); + $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); - $objWriter->writeAttribute('val', '20000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '20000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '255000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '255000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:path $objWriter->startElement('a:path'); - $objWriter->writeAttribute('path', 'circle'); + $objWriter->writeAttribute('path', 'circle'); // a:fillToRect $objWriter->startElement('a:fillToRect'); - $objWriter->writeAttribute('l', '50000'); - $objWriter->writeAttribute('t', '-80000'); - $objWriter->writeAttribute('r', '50000'); - $objWriter->writeAttribute('b', '180000'); - $objWriter->endElement(); + $objWriter->writeAttribute('l', '50000'); + $objWriter->writeAttribute('t', '-80000'); + $objWriter->writeAttribute('r', '50000'); + $objWriter->writeAttribute('b', '180000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); - $objWriter->writeAttribute('rotWithShape', '1'); + $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '0'); + $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); - $objWriter->writeAttribute('val', '80000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '80000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '300000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); - $objWriter->writeAttribute('pos', '100000'); + $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); - $objWriter->writeAttribute('val', 'phClr'); + $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); - $objWriter->writeAttribute('val', '30000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '30000'); + $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); - $objWriter->writeAttribute('val', '200000'); - $objWriter->endElement(); + $objWriter->writeAttribute('val', '200000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:path $objWriter->startElement('a:path'); - $objWriter->writeAttribute('path', 'circle'); + $objWriter->writeAttribute('path', 'circle'); // a:fillToRect $objWriter->startElement('a:fillToRect'); - $objWriter->writeAttribute('l', '50000'); - $objWriter->writeAttribute('t', '50000'); - $objWriter->writeAttribute('r', '50000'); - $objWriter->writeAttribute('b', '50000'); - $objWriter->endElement(); + $objWriter->writeAttribute('l', '50000'); + $objWriter->writeAttribute('t', '50000'); + $objWriter->writeAttribute('r', '50000'); + $objWriter->writeAttribute('b', '50000'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // a:objectDefaults $objWriter->writeElement('a:objectDefaults', null); @@ -818,8 +812,8 @@ class Theme extends WriterPart * @param \PhpSpreadsheet\Shared\XMLWriter $objWriter * @param string $latinFont * @param array of string $fontSet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ private function writeFonts($objWriter, $latinFont, $fontSet) { @@ -840,8 +834,8 @@ class Theme extends WriterPart foreach ($fontSet as $fontScript => $typeface) { $objWriter->startElement('a:font'); - $objWriter->writeAttribute('script', $fontScript); - $objWriter->writeAttribute('typeface', $typeface); + $objWriter->writeAttribute('script', $fontScript); + $objWriter->writeAttribute('typeface', $typeface); $objWriter->endElement(); } } @@ -850,17 +844,17 @@ class Theme extends WriterPart * Write colour scheme to XML format * * @param \PhpSpreadsheet\Shared\XMLWriter $objWriter - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ private function writeColourScheme($objWriter) { foreach (self::$colourScheme as $colourName => $colourValue) { - $objWriter->startElement('a:'.$colourName); + $objWriter->startElement('a:' . $colourName); - $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', $colourValue); - $objWriter->endElement(); + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', $colourValue); + $objWriter->endElement(); $objWriter->endElement(); } diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Workbook.php b/src/PhpSpreadsheet/Writer/Excel2007/Workbook.php index c5969131..f05238de 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Workbook.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Workbook.php @@ -1,4 +1,5 @@ writeAttribute('r:id', 'rId' . $pRelId); $objWriter->endElement(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid parameters passed.'); } } @@ -316,7 +317,7 @@ class Workbook extends WriterPart // Create absolute coordinate and write as raw text $range = \PhpSpreadsheet\Cell::splitRange($pNamedRange->getRange()); - for ($i = 0; $i < count($range); $i++) { + for ($i = 0; $i < count($range); ++$i) { $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . \PhpSpreadsheet\Cell::absoluteReference($range[$i][0]); if (isset($range[$i][1])) { $range[$i][1] = \PhpSpreadsheet\Cell::absoluteReference($range[$i][1]); @@ -430,7 +431,7 @@ class Workbook extends WriterPart // Print area $printArea = \PhpSpreadsheet\Cell::splitRange($pSheet->getPageSetup()->getPrintArea()); - $chunks = array(); + $chunks = []; foreach ($printArea as $printAreaRect) { $printAreaRect[0] = \PhpSpreadsheet\Cell::absoluteReference($printAreaRect[0]); $printAreaRect[1] = \PhpSpreadsheet\Cell::absoluteReference($printAreaRect[1]); diff --git a/src/PhpSpreadsheet/Writer/Excel2007/Worksheet.php b/src/PhpSpreadsheet/Writer/Excel2007/Worksheet.php index 6e8ae8ef..62f276d9 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/Worksheet.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/Worksheet.php @@ -1,4 +1,5 @@ getData(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid \\PhpSpreadsheet\\Worksheet object passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid \\PhpSpreadsheet\\Worksheet object passed.'); } } @@ -146,8 +146,9 @@ class Worksheet extends WriterPart // sheetPr $objWriter->startElement('sheetPr'); //$objWriter->writeAttribute('codeName', $pSheet->getTitle()); - if ($pSheet->getParent()->hasMacros()) {//if the workbook have macros, we need to have codeName for the sheet - if ($pSheet->hasCodeName()==false) { + if ($pSheet->getParent()->hasMacros()) { + //if the workbook have macros, we need to have codeName for the sheet + if ($pSheet->hasCodeName() == false) { $pSheet->setCodeName($pSheet->getTitle()); } $objWriter->writeAttribute('codeName', $pSheet->getCodeName()); @@ -329,8 +330,8 @@ class Worksheet extends WriterPart } // Set Zero Height row - if ((string)$pSheet->getDefaultRowDimension()->getZeroHeight() == '1' || - strtolower((string)$pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true') { + if ((string) $pSheet->getDefaultRowDimension()->getZeroHeight() == '1' || + strtolower((string) $pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true') { $objWriter->writeAttribute('zeroHeight', '1'); } @@ -346,7 +347,7 @@ class Worksheet extends WriterPart $outlineLevelRow = $dimension->getOutlineLevel(); } } - $objWriter->writeAttribute('outlineLevelRow', (int)$outlineLevelRow); + $objWriter->writeAttribute('outlineLevelRow', (int) $outlineLevelRow); // Outline level - column $outlineLevelCol = 0; @@ -355,7 +356,7 @@ class Worksheet extends WriterPart $outlineLevelCol = $dimension->getOutlineLevel(); } } - $objWriter->writeAttribute('outlineLevelCol', (int)$outlineLevelCol); + $objWriter->writeAttribute('outlineLevelCol', (int) $outlineLevelCol); $objWriter->endElement(); } @@ -903,8 +904,8 @@ class Worksheet extends WriterPart private function writeBreaks(\PhpSpreadsheet\Shared\XMLWriter $objWriter = null, \PhpSpreadsheet\Worksheet $pSheet = null) { // Get row and column breaks - $aRowBreaks = array(); - $aColumnBreaks = array(); + $aRowBreaks = []; + $aColumnBreaks = []; foreach ($pSheet->getBreaks() as $cell => $breakType) { if ($breakType == \PhpSpreadsheet\Worksheet::BREAK_ROW) { $aRowBreaks[] = $cell; @@ -974,7 +975,7 @@ class Worksheet extends WriterPart $highestRow = $pSheet->getHighestRow(); // Loop through cells - $cellsByRow = array(); + $cellsByRow = []; foreach ($pSheet->getCellCollection() as $cellID) { $cellAddress = \PhpSpreadsheet\Cell::coordinateFromString($cellID); $cellsByRow[$cellAddress[1]][] = $cellID; @@ -1036,7 +1037,7 @@ class Worksheet extends WriterPart $objWriter->endElement(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid parameters passed.'); } } @@ -1091,7 +1092,7 @@ class Worksheet extends WriterPart // Write data depending on its type switch (strtolower($mappedType)) { case 'inlinestr': // Inline string - if (! $cellValue instanceof \PhpSpreadsheet\RichText) { + if (!$cellValue instanceof \PhpSpreadsheet\RichText) { $objWriter->writeElement('t', \PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue))); } elseif ($cellValue instanceof \PhpSpreadsheet\RichText) { $objWriter->startElement('is'); @@ -1101,7 +1102,7 @@ class Worksheet extends WriterPart break; case 's': // String - if (! $cellValue instanceof \PhpSpreadsheet\RichText) { + if (!$cellValue instanceof \PhpSpreadsheet\RichText) { if (isset($pFlippedStringTable[$cellValue])) { $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]); } @@ -1125,7 +1126,7 @@ class Worksheet extends WriterPart } if ($this->getParentWriter()->getOffice2003Compatibility() === false) { if ($this->getParentWriter()->getPreCalculateFormulas()) { -// $calculatedValue = $pCell->getCalculatedValue(); + // $calculatedValue = $pCell->getCalculatedValue(); if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') { $objWriter->writeElement('v', \PhpSpreadsheet\Shared\StringHelper::formatNumber($calculatedValue)); } else { @@ -1157,7 +1158,7 @@ class Worksheet extends WriterPart $objWriter->endElement(); } else { - throw new \PhpSpreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \PhpSpreadsheet\Writer\Exception('Invalid parameters passed.'); } } @@ -1166,7 +1167,7 @@ class Worksheet extends WriterPart * * @param \PhpSpreadsheet\Shared\XMLWriter $objWriter XML Writer * @param \PhpSpreadsheet\Worksheet $pSheet Worksheet - * @param boolean $includeCharts Flag indicating if we should include drawing details for charts + * @param bool $includeCharts Flag indicating if we should include drawing details for charts * @throws \PhpSpreadsheet\Writer\Exception */ private function writeDrawings(\PhpSpreadsheet\Shared\XMLWriter $objWriter = null, \PhpSpreadsheet\Worksheet $pSheet = null, $includeCharts = false) diff --git a/src/PhpSpreadsheet/Writer/Excel2007/WriterPart.php b/src/PhpSpreadsheet/Writer/Excel2007/WriterPart.php index 99a7ab7e..735ca7cb 100644 --- a/src/PhpSpreadsheet/Writer/Excel2007/WriterPart.php +++ b/src/PhpSpreadsheet/Writer/Excel2007/WriterPart.php @@ -49,15 +49,15 @@ abstract class WriterPart /** * Get parent IWriter object * - * @return \PhpSpreadsheet\Writer\IWriter * @throws \PhpSpreadsheet\Writer\Exception + * @return \PhpSpreadsheet\Writer\IWriter */ public function getParentWriter() { if (!is_null($this->parentWriter)) { return $this->parentWriter; } else { - throw new \PhpSpreadsheet\Writer\Exception("No parent \\PhpSpreadsheet\\Writer\\IWriter assigned."); + throw new \PhpSpreadsheet\Writer\Exception('No parent \\PhpSpreadsheet\\Writer\\IWriter assigned.'); } } diff --git a/src/PhpSpreadsheet/Writer/Excel5.php b/src/PhpSpreadsheet/Writer/Excel5.php index 8a2f23bc..132cc530 100644 --- a/src/PhpSpreadsheet/Writer/Excel5.php +++ b/src/PhpSpreadsheet/Writer/Excel5.php @@ -54,7 +54,7 @@ class Excel5 extends BaseWriter implements IWriter * * @var array */ - private $strTable = array(); + private $strTable = []; /** * Color cache. Mapping between RGB value and color index. @@ -100,7 +100,7 @@ class Excel5 extends BaseWriter implements IWriter { $this->spreadsheet = $spreadsheet; - $this->parser = new Excel5\Parser(); + $this->parser = new Excel5\Parser(); } /** @@ -121,7 +121,7 @@ class Excel5 extends BaseWriter implements IWriter \PhpSpreadsheet\Calculation\Functions::setReturnDateType(\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL); // initialize colors array - $this->colors = array(); + $this->colors = []; // Initialise workbook writer $this->writerWorkbook = new Excel5\Workbook($this->spreadsheet, $this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser); @@ -171,7 +171,7 @@ class Excel5 extends BaseWriter implements IWriter // Write the worksheet streams before the global workbook stream, // because the byte sizes of these are needed in the global workbook stream - $worksheetSizes = array(); + $worksheetSizes = []; for ($i = 0; $i < $countSheets; ++$i) { $this->writerWorksheets[$i]->close(); $worksheetSizes[] = $this->writerWorksheets[$i]->_datasize; @@ -200,7 +200,7 @@ class Excel5 extends BaseWriter implements IWriter } // define OLE Parts - $arrRootData = array($OLE); + $arrRootData = [$OLE]; // initialize OLE Properties file if (isset($OLE_SummaryInformation)) { $arrRootData[] = $OLE_SummaryInformation; @@ -233,7 +233,6 @@ class Excel5 extends BaseWriter implements IWriter /** * Build the Worksheet Escher objects - * */ private function buildWorksheetEschers() { @@ -338,9 +337,9 @@ class Excel5 extends BaseWriter implements IWriter ++$countShapes[$sheetIndex]; // create an Drawing Object for the dropdown - $oDrawing = new \PhpSpreadsheet\Worksheet\BaseDrawing(); + $oDrawing = new \PhpSpreadsheet\Worksheet\BaseDrawing(); // get the coordinates of drawing - $cDrawing = \PhpSpreadsheet\Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1]; + $cDrawing = \PhpSpreadsheet\Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1]; $oDrawing->setCoordinates($cDrawing); $oDrawing->setWorksheet($sheet); @@ -381,7 +380,7 @@ class Excel5 extends BaseWriter implements IWriter $spContainer->setEndOffsetY(0); $spgrContainer->addChild($spContainer); - $iInc++; + ++$iInc; } } @@ -559,57 +558,57 @@ class Excel5 extends BaseWriter implements IWriter $data .= pack('V', 0x30); // SECTION - $dataSection = array(); + $dataSection = []; $dataSection_NumProps = 0; $dataSection_Summary = ''; $dataSection_Content = ''; // GKPIDDSI_CODEPAGE: CodePage - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer - 'data' => array('data' => 1252)); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x01], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer + 'data' => ['data' => 1252], ]; + ++$dataSection_NumProps; // GKPIDDSI_CATEGORY : Category if ($this->spreadsheet->getProperties()->getCategory()) { $dataProp = $this->spreadsheet->getProperties()->getCategory(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x1E), - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x02], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x1E], + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; } // GKPIDDSI_VERSION :Version of the application that wrote the property storage - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x17), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x03), - 'data' => array('pack' => 'V', 'data' => 0x000C0000)); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x17], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x03], + 'data' => ['pack' => 'V', 'data' => 0x000C0000], ]; + ++$dataSection_NumProps; // GKPIDDSI_SCALE : FALSE - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0B), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x0B), - 'data' => array('data' => false)); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x0B], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x0B], + 'data' => ['data' => false], ]; + ++$dataSection_NumProps; // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x10), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x0B), - 'data' => array('data' => false)); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x10], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x0B], + 'data' => ['data' => false], ]; + ++$dataSection_NumProps; // GKPIDDSI_SHAREDOC : FALSE - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x0B), - 'data' => array('data' => false)); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x13], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x0B], + 'data' => ['data' => false], ]; + ++$dataSection_NumProps; // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x16), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x0B), - 'data' => array('data' => false)); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x16], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x0B], + 'data' => ['data' => false], ]; + ++$dataSection_NumProps; // GKPIDDSI_DOCSPARTS // MS-OSHARED p75 (2.3.3.2.2.1) @@ -620,21 +619,21 @@ class Excel5 extends BaseWriter implements IWriter // array of UnalignedLpstr // cch $dataProp .= pack('v', 0x000A); - $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); // value - $dataProp .= 'Worksheet'.chr(0); + $dataProp .= 'Worksheet' . chr(0); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x101E), - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x0D], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x101E], + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; // GKPIDDSI_HEADINGPAIR // VtVecHeadingPairValue // cElements $dataProp = pack('v', 0x0002); - $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); // Array of vtHeadingPair // vtUnalignedString - headingString // stringType @@ -644,7 +643,7 @@ class Excel5 extends BaseWriter implements IWriter // UnalignedLpstr // cch $dataProp .= pack('v', 0x0013); - $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); // value $dataProp .= 'Feuilles de calcul'; // vtUnalignedString - headingParts @@ -654,15 +653,15 @@ class Excel5 extends BaseWriter implements IWriter $dataProp .= pack('v', 0x0000); // value $dataProp .= pack('v', 0x0100); - $dataProp .= pack('v', 0x0000); - $dataProp .= pack('v', 0x0000); - $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x100C), - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x0C], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x100C], + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; // 4 Section Length // 4 Property count @@ -696,7 +695,7 @@ class Excel5 extends BaseWriter implements IWriter $dataProp['data']['data'] .= chr(0); $dataProp['data']['length'] += 1; // Complete the string with null string for being a %4 - $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4)); + $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); $dataSection_Content .= pack('V', $dataProp['data']['length']); @@ -755,97 +754,96 @@ class Excel5 extends BaseWriter implements IWriter $data .= pack('V', 0x30); // SECTION - $dataSection = array(); + $dataSection = []; $dataSection_NumProps = 0; $dataSection_Summary = ''; $dataSection_Content = ''; // CodePage : CP-1252 - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer - 'data' => array('data' => 1252)); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x01], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer + 'data' => ['data' => 1252], ]; + ++$dataSection_NumProps; // Title if ($this->spreadsheet->getProperties()->getTitle()) { $dataProp = $this->spreadsheet->getProperties()->getTitle(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x02], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; } // Subject if ($this->spreadsheet->getProperties()->getSubject()) { $dataProp = $this->spreadsheet->getProperties()->getSubject(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x03), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x03], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; } // Author (Creator) if ($this->spreadsheet->getProperties()->getCreator()) { $dataProp = $this->spreadsheet->getProperties()->getCreator(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x04), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x04], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; } // Keywords if ($this->spreadsheet->getProperties()->getKeywords()) { $dataProp = $this->spreadsheet->getProperties()->getKeywords(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x05), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x05], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; } // Comments (Description) if ($this->spreadsheet->getProperties()->getDescription()) { $dataProp = $this->spreadsheet->getProperties()->getDescription(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x06), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x06], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; } // Last Saved By (LastModifiedBy) if ($this->spreadsheet->getProperties()->getLastModifiedBy()) { $dataProp = $this->spreadsheet->getProperties()->getLastModifiedBy(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x08), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length - 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x08], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; + ++$dataSection_NumProps; } // Created Date/Time if ($this->spreadsheet->getProperties()->getCreated()) { $dataProp = $this->spreadsheet->getProperties()->getCreated(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) - 'data' => array('data' => \PhpSpreadsheet\Shared\OLE::localDateToOLE($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x0C], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x40], // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + 'data' => ['data' => \PhpSpreadsheet\Shared\OLE::localDateToOLE($dataProp)], ]; + ++$dataSection_NumProps; } // Modified Date/Time if ($this->spreadsheet->getProperties()->getModified()) { $dataProp = $this->spreadsheet->getProperties()->getModified(); - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) - 'data' => array('data' => \PhpSpreadsheet\Shared\OLE::localDateToOLE($dataProp))); - $dataSection_NumProps++; + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x0D], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x40], // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + 'data' => ['data' => \PhpSpreadsheet\Shared\OLE::localDateToOLE($dataProp)], ]; + ++$dataSection_NumProps; } // Security - $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13), - 'offset' => array('pack' => 'V'), - 'type' => array('pack' => 'V', 'data' => 0x03), // 4 byte signed integer - 'data' => array('data' => 0x00)); - $dataSection_NumProps++; - + $dataSection[] = ['summary' => ['pack' => 'V', 'data' => 0x13], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => 0x03], // 4 byte signed integer + 'data' => ['data' => 0x00], ]; + ++$dataSection_NumProps; // 4 Section Length // 4 Property count @@ -872,7 +870,7 @@ class Excel5 extends BaseWriter implements IWriter $dataProp['data']['data'] .= chr(0); $dataProp['data']['length'] += 1; // Complete the string with null string for being a %4 - $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4)); + $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); $dataSection_Content .= pack('V', $dataProp['data']['length']); diff --git a/src/PhpSpreadsheet/Writer/Excel5/BIFFwriter.php b/src/PhpSpreadsheet/Writer/Excel5/BIFFwriter.php index ab919973..a5230aa2 100644 --- a/src/PhpSpreadsheet/Writer/Excel5/BIFFwriter.php +++ b/src/PhpSpreadsheet/Writer/Excel5/BIFFwriter.php @@ -64,7 +64,7 @@ class BIFFwriter { /** * The byte order of this architecture. 0 => little endian, 1 => big endian - * @var integer + * @var int */ private static $byteOrder; @@ -76,24 +76,24 @@ class BIFFwriter /** * The size of the data in bytes. Should be the same as strlen($this->_data) - * @var integer + * @var int */ public $_datasize; /** * The maximum length for a BIFF record (excluding record header and length field). See addContinue() - * @var integer + * @var int * @see addContinue() */ - private $limit = 8224; + private $limit = 8224; /** * Constructor */ public function __construct() { - $this->_data = ''; - $this->_datasize = 0; + $this->_data = ''; + $this->_datasize = 0; // $this->limit = 8224; } @@ -107,15 +107,15 @@ class BIFFwriter { if (!isset(self::$byteOrder)) { // Check if "pack" gives the required IEEE 64bit float - $teststr = pack("d", 1.2345); - $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F); + $teststr = pack('d', 1.2345); + $number = pack('C8', 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F); if ($number == $teststr) { $byte_order = 0; // Little Endian } elseif ($number == strrev($teststr)) { $byte_order = 1; // Big Endian } else { // Give up. I'll fix this in a later version. - throw new \PhpSpreadsheet\Writer\Exception("Required floating point format not supported on this platform."); + throw new \PhpSpreadsheet\Writer\Exception('Required floating point format not supported on this platform.'); } self::$byteOrder = $byte_order; } @@ -127,14 +127,13 @@ class BIFFwriter * General storage function * * @param string $data binary data to append - * @access private */ protected function append($data) { if (strlen($data) - 4 > $this->limit) { $data = $this->addContinue($data); } - $this->_data .= $data; + $this->_data .= $data; $this->_datasize += strlen($data); } @@ -158,52 +157,48 @@ class BIFFwriter * Writes Excel BOF record to indicate the beginning of a stream or * sub-stream in the BIFF file. * - * @param integer $type Type of BIFF file to write: 0x0005 Workbook, + * @param int $type Type of BIFF file to write: 0x0005 Workbook, * 0x0010 Worksheet. - * @access private */ protected function storeBof($type) { - $record = 0x0809; // Record identifier (BIFF5-BIFF8) - $length = 0x0010; + $record = 0x0809; // Record identifier (BIFF5-BIFF8) + $length = 0x0010; // by inspection of real files, MS Office Excel 2007 writes the following - $unknown = pack("VV", 0x000100D1, 0x00000406); + $unknown = pack('VV', 0x000100D1, 0x00000406); - $build = 0x0DBB; // Excel 97 - $year = 0x07CC; // Excel 97 + $build = 0x0DBB; // Excel 97 + $year = 0x07CC; // Excel 97 $version = 0x0600; // BIFF8 - $header = pack("vv", $record, $length); - $data = pack("vvvv", $version, $type, $build, $year); + $header = pack('vv', $record, $length); + $data = pack('vvvv', $version, $type, $build, $year); $this->append($header . $data . $unknown); } /** * Writes Excel EOF record to indicate the end of a BIFF stream. - * - * @access private */ protected function storeEof() { - $record = 0x000A; // Record identifier - $length = 0x0000; // Number of bytes to follow + $record = 0x000A; // Record identifier + $length = 0x0000; // Number of bytes to follow - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); $this->append($header); } /** * Writes Excel EOF record to indicate the end of a BIFF stream. - * - * @access private */ public function writeEof() { - $record = 0x000A; // Record identifier - $length = 0x0000; // Number of bytes to follow - $header = pack("vv", $record, $length); + $record = 0x000A; // Record identifier + $length = 0x0000; // Number of bytes to follow + $header = pack('vv', $record, $length); + return $this->writeData($header); } @@ -217,18 +212,17 @@ class BIFFwriter * * @param string $data The original binary data to be written * @return string A very convenient string of continue blocks - * @access private */ private function addContinue($data) { - $limit = $this->limit; + $limit = $this->limit; $record = 0x003C; // Record identifier // The first 2080/8224 bytes remain intact. However, we have to change // the length field of the record. - $tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit); + $tmp = substr($data, 0, 2) . pack('v', $limit) . substr($data, 4, $limit); - $header = pack("vv", $record, $limit); // Headers for continue records + $header = pack('vv', $record, $limit); // Headers for continue records // Retrieve chunks of 2080/8224 bytes +4 for the header. $data_length = strlen($data); @@ -238,9 +232,9 @@ class BIFFwriter } // Retrieve the last chunk of data - $header = pack("vv", $record, strlen($data) - $i); - $tmp .= $header; - $tmp .= substr($data, $i, strlen($data) - $i); + $header = pack('vv', $record, strlen($data) - $i); + $tmp .= $header; + $tmp .= substr($data, $i, strlen($data) - $i); return $tmp; } diff --git a/src/PhpSpreadsheet/Writer/Excel5/Escher.php b/src/PhpSpreadsheet/Writer/Excel5/Escher.php index b2b821f1..7ee4d930 100644 --- a/src/PhpSpreadsheet/Writer/Excel5/Escher.php +++ b/src/PhpSpreadsheet/Writer/Excel5/Escher.php @@ -26,8 +26,6 @@ namespace PhpSpreadsheet\Writer\Excel5; * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ - - class Escher { /** @@ -53,7 +51,7 @@ class Escher * @var array */ private $spTypes; - + /** * Constructor * @@ -75,10 +73,10 @@ class Escher switch (get_class($this->object)) { case '\\PhpSpreadsheet\\Shared\\Escher': if ($dggContainer = $this->object->getDggContainer()) { - $writer = new Escher($dggContainer); + $writer = new self($dggContainer); $this->data = $writer->close(); } elseif ($dgContainer = $this->object->getDgContainer()) { - $writer = new Escher($dgContainer); + $writer = new self($dgContainer); $this->data = $writer->close(); $this->spOffsets = $writer->getSpOffsets(); $this->spTypes = $writer->getSpTypes(); @@ -91,11 +89,11 @@ class Escher $innerData = ''; // write the dgg - $recVer = 0x0; - $recInstance = 0x0000; - $recType = 0xF006; + $recVer = 0x0; + $recInstance = 0x0000; + $recType = 0xF006; - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; // dgg data @@ -120,17 +118,17 @@ class Escher // write the bstoreContainer if ($bstoreContainer = $this->object->getBstoreContainer()) { - $writer = new Escher($bstoreContainer); + $writer = new self($bstoreContainer); $innerData .= $writer->close(); } // write the record - $recVer = 0xF; - $recInstance = 0x0000; - $recType = 0xF000; - $length = strlen($innerData); + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF000; + $length = strlen($innerData); - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -146,18 +144,18 @@ class Escher // treat the inner data if ($BSECollection = $this->object->getBSECollection()) { foreach ($BSECollection as $BSE) { - $writer = new Escher($BSE); + $writer = new self($BSE); $innerData .= $writer->close(); } } // write the record - $recVer = 0xF; - $recInstance = count($this->object->getBSECollection()); - $recType = 0xF001; - $length = strlen($innerData); + $recVer = 0xF; + $recInstance = count($this->object->getBSECollection()); + $recType = 0xF001; + $length = strlen($innerData); - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -172,7 +170,7 @@ class Escher // here we treat the inner data if ($blip = $this->object->getBlip()) { - $writer = new Escher($blip); + $writer = new self($blip); $innerData .= $writer->close(); } @@ -199,13 +197,13 @@ class Escher $data .= $innerData; // write the record - $recVer = 0x2; - $recInstance = $this->object->getBlipType(); - $recType = 0xF007; - $length = strlen($data); + $recVer = 0x2; + $recInstance = $this->object->getBlipType(); + $recType = 0xF007; + $length = strlen($data); - $recVerInstance = $recVer; - $recVerInstance |= $recInstance << 4; + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -230,13 +228,13 @@ class Escher $innerData .= $this->object->getData(); - $recVer = 0x0; - $recInstance = 0x46A; - $recType = 0xF01D; - $length = strlen($innerData); + $recVer = 0x0; + $recInstance = 0x46A; + $recType = 0xF01D; + $length = strlen($innerData); - $recVerInstance = $recVer; - $recVerInstance |= $recInstance << 4; + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -257,13 +255,13 @@ class Escher $innerData .= $this->object->getData(); - $recVer = 0x0; - $recInstance = 0x6E0; - $recType = 0xF01E; - $length = strlen($innerData); + $recVer = 0x0; + $recInstance = 0x6E0; + $recType = 0xF01E; + $length = strlen($innerData); - $recVerInstance = $recVer; - $recVerInstance |= $recInstance << 4; + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -280,12 +278,12 @@ class Escher $innerData = ''; // write the dg - $recVer = 0x0; - $recInstance = $this->object->getDgId(); - $recType = 0xF008; - $length = 8; + $recVer = 0x0; + $recInstance = $this->object->getDgId(); + $recType = 0xF008; + $length = 8; - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -297,15 +295,15 @@ class Escher // write the spgrContainer if ($spgrContainer = $this->object->getSpgrContainer()) { - $writer = new Escher($spgrContainer); + $writer = new self($spgrContainer); $innerData .= $writer->close(); // get the shape offsets relative to the spgrContainer record $spOffsets = $writer->getSpOffsets(); - $spTypes = $writer->getSpTypes(); - + $spTypes = $writer->getSpTypes(); + // save the shape offsets relative to dgContainer - foreach ($spOffsets as & $spOffset) { + foreach ($spOffsets as &$spOffset) { $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes) } @@ -314,12 +312,12 @@ class Escher } // write the record - $recVer = 0xF; - $recInstance = 0x0000; - $recType = 0xF002; - $length = strlen($innerData); + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF002; + $length = strlen($innerData); - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -334,29 +332,29 @@ class Escher // initialize spape offsets $totalSize = 8; - $spOffsets = array(); - $spTypes = array(); + $spOffsets = []; + $spTypes = []; // treat the inner data foreach ($this->object->getChildren() as $spContainer) { - $writer = new Escher($spContainer); + $writer = new self($spContainer); $spData = $writer->close(); $innerData .= $spData; // save the shape offsets (where new shape records begin) $totalSize += strlen($spData); $spOffsets[] = $totalSize; - + $spTypes = array_merge($spTypes, $writer->getSpTypes()); } // write the record - $recVer = 0xF; - $recInstance = 0x0000; - $recType = 0xF003; - $length = strlen($innerData); + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF003; + $length = strlen($innerData); - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -373,12 +371,12 @@ class Escher // write group shape record, if necessary? if ($this->object->getSpgr()) { - $recVer = 0x1; - $recInstance = 0x0000; - $recType = 0xF009; - $length = 0x00000010; + $recVer = 0x1; + $recInstance = 0x0000; + $recType = 0xF009; + $length = 0x00000010; - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -388,32 +386,31 @@ class Escher $this->spTypes[] = ($this->object->getSpType()); // write the shape record - $recVer = 0x2; - $recInstance = $this->object->getSpType(); // shape type - $recType = 0xF00A; - $length = 0x00000008; + $recVer = 0x2; + $recInstance = $this->object->getSpType(); // shape type + $recType = 0xF00A; + $length = 0x00000008; - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . pack('VV', $this->object->getSpId(), $this->object->getSpgr() ? 0x0005 : 0x0A00); - // the options if ($this->object->getOPTCollection()) { $optData = ''; - $recVer = 0x3; - $recInstance = count($this->object->getOPTCollection()); - $recType = 0xF00B; + $recVer = 0x3; + $recInstance = count($this->object->getOPTCollection()); + $recType = 0xF00B; foreach ($this->object->getOPTCollection() as $property => $value) { $optData .= pack('vV', $property, $value); } - $length = strlen($optData); + $length = strlen($optData); - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -424,9 +421,9 @@ class Escher if ($this->object->getStartCoordinates()) { $clientAnchorData = ''; - $recVer = 0x0; - $recInstance = 0x0; - $recType = 0xF010; + $recVer = 0x0; + $recInstance = 0x0; + $recType = 0xF010; // start coordinates list($column, $row) = \PhpSpreadsheet\Cell::coordinateFromString($this->object->getStartCoordinates()); @@ -451,10 +448,10 @@ class Escher $endOffsetY = $this->object->getEndOffsetY(); $clientAnchorData = pack('vvvvvvvvv', $this->object->getSpFlag(), $c1, $startOffsetX, $r1, $startOffsetY, $c2, $endOffsetX, $r2, $endOffsetY); - - $length = strlen($clientAnchorData); - $recVerInstance = $recVer; + $length = strlen($clientAnchorData); + + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -465,13 +462,13 @@ class Escher if (!$this->object->getSpgr()) { $clientDataData = ''; - $recVer = 0x0; - $recInstance = 0x0; - $recType = 0xF011; + $recVer = 0x0; + $recInstance = 0x0; + $recType = 0xF011; $length = strlen($clientDataData); - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); @@ -479,12 +476,12 @@ class Escher } // write the record - $recVer = 0xF; - $recInstance = 0x0000; - $recType = 0xF004; - $length = strlen($data); + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF004; + $length = strlen($data); - $recVerInstance = $recVer; + $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); diff --git a/src/PhpSpreadsheet/Writer/Excel5/Font.php b/src/PhpSpreadsheet/Writer/Excel5/Font.php index 35ced929..17c4542f 100644 --- a/src/PhpSpreadsheet/Writer/Excel5/Font.php +++ b/src/PhpSpreadsheet/Writer/Excel5/Font.php @@ -101,7 +101,7 @@ class Font } $data = pack( - "vvvvvCCCC", + 'vvvvvCCCC', // Fontsize (in twips) $this->font->getSize() * 20, $grbit, @@ -119,15 +119,15 @@ class Font $data .= \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeShort($this->font->getName()); $length = strlen($data); - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); - return($header . $data); + return $header . $data; } /** * Map to BIFF5-BIFF8 codes for bold * - * @param boolean $bold + * @param bool $bold * @return int */ private static function mapBold($bold) @@ -135,21 +135,21 @@ class Font if ($bold) { return 0x2BC; // 700 = Bold font weight } + return 0x190; // 400 = Normal font weight } /** * Map of BIFF2-BIFF8 codes for underline styles * @static array of int - * */ - private static $mapUnderline = array( - \PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00, - \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE => 0x01, - \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE => 0x02, - \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING => 0x21, - \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING => 0x22, - ); + private static $mapUnderline = [ + \PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00, + \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE => 0x01, + \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE => 0x02, + \PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING => 0x21, + \PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING => 0x22, + ]; /** * Map underline @@ -162,6 +162,7 @@ class Font if (isset(self::$mapUnderline[$underline])) { return self::$mapUnderline[$underline]; } + return 0x00; } } diff --git a/src/PhpSpreadsheet/Writer/Excel5/Parser.php b/src/PhpSpreadsheet/Writer/Excel5/Parser.php index 1abb6203..e89da216 100644 --- a/src/PhpSpreadsheet/Writer/Excel5/Parser.php +++ b/src/PhpSpreadsheet/Writer/Excel5/Parser.php @@ -68,7 +68,7 @@ class Parser /** * The index of the character we are currently looking at - * @var integer + * @var int */ public $currentCharacter; @@ -110,125 +110,122 @@ class Parser /** * The class constructor - * */ public function __construct() { - $this->currentCharacter = 0; + $this->currentCharacter = 0; $this->currentToken = ''; // The token we are working on. - $this->formula = ''; // The formula to parse. - $this->lookAhead = ''; // The character ahead of the current char. - $this->parseTree = ''; // The parse tree to be generated. + $this->formula = ''; // The formula to parse. + $this->lookAhead = ''; // The character ahead of the current char. + $this->parseTree = ''; // The parse tree to be generated. $this->initializeHashes(); // Initialize the hashes: ptg's and function's ptg's - $this->externalSheets = array(); - $this->references = array(); + $this->externalSheets = []; + $this->references = []; } /** * Initialize the ptg and function hashes. - * - * @access private */ private function initializeHashes() { // The Excel ptg indices - $this->ptg = array( - 'ptgExp' => 0x01, - 'ptgTbl' => 0x02, - 'ptgAdd' => 0x03, - 'ptgSub' => 0x04, - 'ptgMul' => 0x05, - 'ptgDiv' => 0x06, - 'ptgPower' => 0x07, - 'ptgConcat' => 0x08, - 'ptgLT' => 0x09, - 'ptgLE' => 0x0A, - 'ptgEQ' => 0x0B, - 'ptgGE' => 0x0C, - 'ptgGT' => 0x0D, - 'ptgNE' => 0x0E, - 'ptgIsect' => 0x0F, - 'ptgUnion' => 0x10, - 'ptgRange' => 0x11, - 'ptgUplus' => 0x12, - 'ptgUminus' => 0x13, - 'ptgPercent' => 0x14, - 'ptgParen' => 0x15, - 'ptgMissArg' => 0x16, - 'ptgStr' => 0x17, - 'ptgAttr' => 0x19, - 'ptgSheet' => 0x1A, - 'ptgEndSheet' => 0x1B, - 'ptgErr' => 0x1C, - 'ptgBool' => 0x1D, - 'ptgInt' => 0x1E, - 'ptgNum' => 0x1F, - 'ptgArray' => 0x20, - 'ptgFunc' => 0x21, - 'ptgFuncVar' => 0x22, - 'ptgName' => 0x23, - 'ptgRef' => 0x24, - 'ptgArea' => 0x25, - 'ptgMemArea' => 0x26, - 'ptgMemErr' => 0x27, - 'ptgMemNoMem' => 0x28, - 'ptgMemFunc' => 0x29, - 'ptgRefErr' => 0x2A, - 'ptgAreaErr' => 0x2B, - 'ptgRefN' => 0x2C, - 'ptgAreaN' => 0x2D, - 'ptgMemAreaN' => 0x2E, + $this->ptg = [ + 'ptgExp' => 0x01, + 'ptgTbl' => 0x02, + 'ptgAdd' => 0x03, + 'ptgSub' => 0x04, + 'ptgMul' => 0x05, + 'ptgDiv' => 0x06, + 'ptgPower' => 0x07, + 'ptgConcat' => 0x08, + 'ptgLT' => 0x09, + 'ptgLE' => 0x0A, + 'ptgEQ' => 0x0B, + 'ptgGE' => 0x0C, + 'ptgGT' => 0x0D, + 'ptgNE' => 0x0E, + 'ptgIsect' => 0x0F, + 'ptgUnion' => 0x10, + 'ptgRange' => 0x11, + 'ptgUplus' => 0x12, + 'ptgUminus' => 0x13, + 'ptgPercent' => 0x14, + 'ptgParen' => 0x15, + 'ptgMissArg' => 0x16, + 'ptgStr' => 0x17, + 'ptgAttr' => 0x19, + 'ptgSheet' => 0x1A, + 'ptgEndSheet' => 0x1B, + 'ptgErr' => 0x1C, + 'ptgBool' => 0x1D, + 'ptgInt' => 0x1E, + 'ptgNum' => 0x1F, + 'ptgArray' => 0x20, + 'ptgFunc' => 0x21, + 'ptgFuncVar' => 0x22, + 'ptgName' => 0x23, + 'ptgRef' => 0x24, + 'ptgArea' => 0x25, + 'ptgMemArea' => 0x26, + 'ptgMemErr' => 0x27, + 'ptgMemNoMem' => 0x28, + 'ptgMemFunc' => 0x29, + 'ptgRefErr' => 0x2A, + 'ptgAreaErr' => 0x2B, + 'ptgRefN' => 0x2C, + 'ptgAreaN' => 0x2D, + 'ptgMemAreaN' => 0x2E, 'ptgMemNoMemN' => 0x2F, - 'ptgNameX' => 0x39, - 'ptgRef3d' => 0x3A, - 'ptgArea3d' => 0x3B, - 'ptgRefErr3d' => 0x3C, + 'ptgNameX' => 0x39, + 'ptgRef3d' => 0x3A, + 'ptgArea3d' => 0x3B, + 'ptgRefErr3d' => 0x3C, 'ptgAreaErr3d' => 0x3D, - 'ptgArrayV' => 0x40, - 'ptgFuncV' => 0x41, - 'ptgFuncVarV' => 0x42, - 'ptgNameV' => 0x43, - 'ptgRefV' => 0x44, - 'ptgAreaV' => 0x45, - 'ptgMemAreaV' => 0x46, - 'ptgMemErrV' => 0x47, + 'ptgArrayV' => 0x40, + 'ptgFuncV' => 0x41, + 'ptgFuncVarV' => 0x42, + 'ptgNameV' => 0x43, + 'ptgRefV' => 0x44, + 'ptgAreaV' => 0x45, + 'ptgMemAreaV' => 0x46, + 'ptgMemErrV' => 0x47, 'ptgMemNoMemV' => 0x48, - 'ptgMemFuncV' => 0x49, - 'ptgRefErrV' => 0x4A, - 'ptgAreaErrV' => 0x4B, - 'ptgRefNV' => 0x4C, - 'ptgAreaNV' => 0x4D, + 'ptgMemFuncV' => 0x49, + 'ptgRefErrV' => 0x4A, + 'ptgAreaErrV' => 0x4B, + 'ptgRefNV' => 0x4C, + 'ptgAreaNV' => 0x4D, 'ptgMemAreaNV' => 0x4E, 'ptgMemNoMemN' => 0x4F, - 'ptgFuncCEV' => 0x58, - 'ptgNameXV' => 0x59, - 'ptgRef3dV' => 0x5A, - 'ptgArea3dV' => 0x5B, + 'ptgFuncCEV' => 0x58, + 'ptgNameXV' => 0x59, + 'ptgRef3dV' => 0x5A, + 'ptgArea3dV' => 0x5B, 'ptgRefErr3dV' => 0x5C, 'ptgAreaErr3d' => 0x5D, - 'ptgArrayA' => 0x60, - 'ptgFuncA' => 0x61, - 'ptgFuncVarA' => 0x62, - 'ptgNameA' => 0x63, - 'ptgRefA' => 0x64, - 'ptgAreaA' => 0x65, - 'ptgMemAreaA' => 0x66, - 'ptgMemErrA' => 0x67, + 'ptgArrayA' => 0x60, + 'ptgFuncA' => 0x61, + 'ptgFuncVarA' => 0x62, + 'ptgNameA' => 0x63, + 'ptgRefA' => 0x64, + 'ptgAreaA' => 0x65, + 'ptgMemAreaA' => 0x66, + 'ptgMemErrA' => 0x67, 'ptgMemNoMemA' => 0x68, - 'ptgMemFuncA' => 0x69, - 'ptgRefErrA' => 0x6A, - 'ptgAreaErrA' => 0x6B, - 'ptgRefNA' => 0x6C, - 'ptgAreaNA' => 0x6D, + 'ptgMemFuncA' => 0x69, + 'ptgRefErrA' => 0x6A, + 'ptgAreaErrA' => 0x6B, + 'ptgRefNA' => 0x6C, + 'ptgAreaNA' => 0x6D, 'ptgMemAreaNA' => 0x6E, 'ptgMemNoMemN' => 0x6F, - 'ptgFuncCEA' => 0x78, - 'ptgNameXA' => 0x79, - 'ptgRef3dA' => 0x7A, - 'ptgArea3dA' => 0x7B, + 'ptgFuncCEA' => 0x78, + 'ptgNameXA' => 0x79, + 'ptgRef3dA' => 0x7A, + 'ptgArea3dA' => 0x7B, 'ptgRefErr3dA' => 0x7C, - 'ptgAreaErr3d' => 0x7D - ); + 'ptgAreaErr3d' => 0x7D, + ]; // Thanks to Michael Meeks and Gnumeric for the initial arg values. // @@ -243,271 +240,270 @@ class Parser // class: The reference, value or array class of the function args. // vol: The function is volatile. // - $this->functions = array( + $this->functions = [ // function ptg args class vol - 'COUNT' => array( 0, -1, 0, 0 ), - 'IF' => array( 1, -1, 1, 0 ), - 'ISNA' => array( 2, 1, 1, 0 ), - 'ISERROR' => array( 3, 1, 1, 0 ), - 'SUM' => array( 4, -1, 0, 0 ), - 'AVERAGE' => array( 5, -1, 0, 0 ), - 'MIN' => array( 6, -1, 0, 0 ), - 'MAX' => array( 7, -1, 0, 0 ), - 'ROW' => array( 8, -1, 0, 0 ), - 'COLUMN' => array( 9, -1, 0, 0 ), - 'NA' => array( 10, 0, 0, 0 ), - 'NPV' => array( 11, -1, 1, 0 ), - 'STDEV' => array( 12, -1, 0, 0 ), - 'DOLLAR' => array( 13, -1, 1, 0 ), - 'FIXED' => array( 14, -1, 1, 0 ), - 'SIN' => array( 15, 1, 1, 0 ), - 'COS' => array( 16, 1, 1, 0 ), - 'TAN' => array( 17, 1, 1, 0 ), - 'ATAN' => array( 18, 1, 1, 0 ), - 'PI' => array( 19, 0, 1, 0 ), - 'SQRT' => array( 20, 1, 1, 0 ), - 'EXP' => array( 21, 1, 1, 0 ), - 'LN' => array( 22, 1, 1, 0 ), - 'LOG10' => array( 23, 1, 1, 0 ), - 'ABS' => array( 24, 1, 1, 0 ), - 'INT' => array( 25, 1, 1, 0 ), - 'SIGN' => array( 26, 1, 1, 0 ), - 'ROUND' => array( 27, 2, 1, 0 ), - 'LOOKUP' => array( 28, -1, 0, 0 ), - 'INDEX' => array( 29, -1, 0, 1 ), - 'REPT' => array( 30, 2, 1, 0 ), - 'MID' => array( 31, 3, 1, 0 ), - 'LEN' => array( 32, 1, 1, 0 ), - 'VALUE' => array( 33, 1, 1, 0 ), - 'TRUE' => array( 34, 0, 1, 0 ), - 'FALSE' => array( 35, 0, 1, 0 ), - 'AND' => array( 36, -1, 0, 0 ), - 'OR' => array( 37, -1, 0, 0 ), - 'NOT' => array( 38, 1, 1, 0 ), - 'MOD' => array( 39, 2, 1, 0 ), - 'DCOUNT' => array( 40, 3, 0, 0 ), - 'DSUM' => array( 41, 3, 0, 0 ), - 'DAVERAGE' => array( 42, 3, 0, 0 ), - 'DMIN' => array( 43, 3, 0, 0 ), - 'DMAX' => array( 44, 3, 0, 0 ), - 'DSTDEV' => array( 45, 3, 0, 0 ), - 'VAR' => array( 46, -1, 0, 0 ), - 'DVAR' => array( 47, 3, 0, 0 ), - 'TEXT' => array( 48, 2, 1, 0 ), - 'LINEST' => array( 49, -1, 0, 0 ), - 'TREND' => array( 50, -1, 0, 0 ), - 'LOGEST' => array( 51, -1, 0, 0 ), - 'GROWTH' => array( 52, -1, 0, 0 ), - 'PV' => array( 56, -1, 1, 0 ), - 'FV' => array( 57, -1, 1, 0 ), - 'NPER' => array( 58, -1, 1, 0 ), - 'PMT' => array( 59, -1, 1, 0 ), - 'RATE' => array( 60, -1, 1, 0 ), - 'MIRR' => array( 61, 3, 0, 0 ), - 'IRR' => array( 62, -1, 0, 0 ), - 'RAND' => array( 63, 0, 1, 1 ), - 'MATCH' => array( 64, -1, 0, 0 ), - 'DATE' => array( 65, 3, 1, 0 ), - 'TIME' => array( 66, 3, 1, 0 ), - 'DAY' => array( 67, 1, 1, 0 ), - 'MONTH' => array( 68, 1, 1, 0 ), - 'YEAR' => array( 69, 1, 1, 0 ), - 'WEEKDAY' => array( 70, -1, 1, 0 ), - 'HOUR' => array( 71, 1, 1, 0 ), - 'MINUTE' => array( 72, 1, 1, 0 ), - 'SECOND' => array( 73, 1, 1, 0 ), - 'NOW' => array( 74, 0, 1, 1 ), - 'AREAS' => array( 75, 1, 0, 1 ), - 'ROWS' => array( 76, 1, 0, 1 ), - 'COLUMNS' => array( 77, 1, 0, 1 ), - 'OFFSET' => array( 78, -1, 0, 1 ), - 'SEARCH' => array( 82, -1, 1, 0 ), - 'TRANSPOSE' => array( 83, 1, 1, 0 ), - 'TYPE' => array( 86, 1, 1, 0 ), - 'ATAN2' => array( 97, 2, 1, 0 ), - 'ASIN' => array( 98, 1, 1, 0 ), - 'ACOS' => array( 99, 1, 1, 0 ), - 'CHOOSE' => array( 100, -1, 1, 0 ), - 'HLOOKUP' => array( 101, -1, 0, 0 ), - 'VLOOKUP' => array( 102, -1, 0, 0 ), - 'ISREF' => array( 105, 1, 0, 0 ), - 'LOG' => array( 109, -1, 1, 0 ), - 'CHAR' => array( 111, 1, 1, 0 ), - 'LOWER' => array( 112, 1, 1, 0 ), - 'UPPER' => array( 113, 1, 1, 0 ), - 'PROPER' => array( 114, 1, 1, 0 ), - 'LEFT' => array( 115, -1, 1, 0 ), - 'RIGHT' => array( 116, -1, 1, 0 ), - 'EXACT' => array( 117, 2, 1, 0 ), - 'TRIM' => array( 118, 1, 1, 0 ), - 'REPLACE' => array( 119, 4, 1, 0 ), - 'SUBSTITUTE' => array( 120, -1, 1, 0 ), - 'CODE' => array( 121, 1, 1, 0 ), - 'FIND' => array( 124, -1, 1, 0 ), - 'CELL' => array( 125, -1, 0, 1 ), - 'ISERR' => array( 126, 1, 1, 0 ), - 'ISTEXT' => array( 127, 1, 1, 0 ), - 'ISNUMBER' => array( 128, 1, 1, 0 ), - 'ISBLANK' => array( 129, 1, 1, 0 ), - 'T' => array( 130, 1, 0, 0 ), - 'N' => array( 131, 1, 0, 0 ), - 'DATEVALUE' => array( 140, 1, 1, 0 ), - 'TIMEVALUE' => array( 141, 1, 1, 0 ), - 'SLN' => array( 142, 3, 1, 0 ), - 'SYD' => array( 143, 4, 1, 0 ), - 'DDB' => array( 144, -1, 1, 0 ), - 'INDIRECT' => array( 148, -1, 1, 1 ), - 'CALL' => array( 150, -1, 1, 0 ), - 'CLEAN' => array( 162, 1, 1, 0 ), - 'MDETERM' => array( 163, 1, 2, 0 ), - 'MINVERSE' => array( 164, 1, 2, 0 ), - 'MMULT' => array( 165, 2, 2, 0 ), - 'IPMT' => array( 167, -1, 1, 0 ), - 'PPMT' => array( 168, -1, 1, 0 ), - 'COUNTA' => array( 169, -1, 0, 0 ), - 'PRODUCT' => array( 183, -1, 0, 0 ), - 'FACT' => array( 184, 1, 1, 0 ), - 'DPRODUCT' => array( 189, 3, 0, 0 ), - 'ISNONTEXT' => array( 190, 1, 1, 0 ), - 'STDEVP' => array( 193, -1, 0, 0 ), - 'VARP' => array( 194, -1, 0, 0 ), - 'DSTDEVP' => array( 195, 3, 0, 0 ), - 'DVARP' => array( 196, 3, 0, 0 ), - 'TRUNC' => array( 197, -1, 1, 0 ), - 'ISLOGICAL' => array( 198, 1, 1, 0 ), - 'DCOUNTA' => array( 199, 3, 0, 0 ), - 'USDOLLAR' => array( 204, -1, 1, 0 ), - 'FINDB' => array( 205, -1, 1, 0 ), - 'SEARCHB' => array( 206, -1, 1, 0 ), - 'REPLACEB' => array( 207, 4, 1, 0 ), - 'LEFTB' => array( 208, -1, 1, 0 ), - 'RIGHTB' => array( 209, -1, 1, 0 ), - 'MIDB' => array( 210, 3, 1, 0 ), - 'LENB' => array( 211, 1, 1, 0 ), - 'ROUNDUP' => array( 212, 2, 1, 0 ), - 'ROUNDDOWN' => array( 213, 2, 1, 0 ), - 'ASC' => array( 214, 1, 1, 0 ), - 'DBCS' => array( 215, 1, 1, 0 ), - 'RANK' => array( 216, -1, 0, 0 ), - 'ADDRESS' => array( 219, -1, 1, 0 ), - 'DAYS360' => array( 220, -1, 1, 0 ), - 'TODAY' => array( 221, 0, 1, 1 ), - 'VDB' => array( 222, -1, 1, 0 ), - 'MEDIAN' => array( 227, -1, 0, 0 ), - 'SUMPRODUCT' => array( 228, -1, 2, 0 ), - 'SINH' => array( 229, 1, 1, 0 ), - 'COSH' => array( 230, 1, 1, 0 ), - 'TANH' => array( 231, 1, 1, 0 ), - 'ASINH' => array( 232, 1, 1, 0 ), - 'ACOSH' => array( 233, 1, 1, 0 ), - 'ATANH' => array( 234, 1, 1, 0 ), - 'DGET' => array( 235, 3, 0, 0 ), - 'INFO' => array( 244, 1, 1, 1 ), - 'DB' => array( 247, -1, 1, 0 ), - 'FREQUENCY' => array( 252, 2, 0, 0 ), - 'ERROR.TYPE' => array( 261, 1, 1, 0 ), - 'REGISTER.ID' => array( 267, -1, 1, 0 ), - 'AVEDEV' => array( 269, -1, 0, 0 ), - 'BETADIST' => array( 270, -1, 1, 0 ), - 'GAMMALN' => array( 271, 1, 1, 0 ), - 'BETAINV' => array( 272, -1, 1, 0 ), - 'BINOMDIST' => array( 273, 4, 1, 0 ), - 'CHIDIST' => array( 274, 2, 1, 0 ), - 'CHIINV' => array( 275, 2, 1, 0 ), - 'COMBIN' => array( 276, 2, 1, 0 ), - 'CONFIDENCE' => array( 277, 3, 1, 0 ), - 'CRITBINOM' => array( 278, 3, 1, 0 ), - 'EVEN' => array( 279, 1, 1, 0 ), - 'EXPONDIST' => array( 280, 3, 1, 0 ), - 'FDIST' => array( 281, 3, 1, 0 ), - 'FINV' => array( 282, 3, 1, 0 ), - 'FISHER' => array( 283, 1, 1, 0 ), - 'FISHERINV' => array( 284, 1, 1, 0 ), - 'FLOOR' => array( 285, 2, 1, 0 ), - 'GAMMADIST' => array( 286, 4, 1, 0 ), - 'GAMMAINV' => array( 287, 3, 1, 0 ), - 'CEILING' => array( 288, 2, 1, 0 ), - 'HYPGEOMDIST' => array( 289, 4, 1, 0 ), - 'LOGNORMDIST' => array( 290, 3, 1, 0 ), - 'LOGINV' => array( 291, 3, 1, 0 ), - 'NEGBINOMDIST' => array( 292, 3, 1, 0 ), - 'NORMDIST' => array( 293, 4, 1, 0 ), - 'NORMSDIST' => array( 294, 1, 1, 0 ), - 'NORMINV' => array( 295, 3, 1, 0 ), - 'NORMSINV' => array( 296, 1, 1, 0 ), - 'STANDARDIZE' => array( 297, 3, 1, 0 ), - 'ODD' => array( 298, 1, 1, 0 ), - 'PERMUT' => array( 299, 2, 1, 0 ), - 'POISSON' => array( 300, 3, 1, 0 ), - 'TDIST' => array( 301, 3, 1, 0 ), - 'WEIBULL' => array( 302, 4, 1, 0 ), - 'SUMXMY2' => array( 303, 2, 2, 0 ), - 'SUMX2MY2' => array( 304, 2, 2, 0 ), - 'SUMX2PY2' => array( 305, 2, 2, 0 ), - 'CHITEST' => array( 306, 2, 2, 0 ), - 'CORREL' => array( 307, 2, 2, 0 ), - 'COVAR' => array( 308, 2, 2, 0 ), - 'FORECAST' => array( 309, 3, 2, 0 ), - 'FTEST' => array( 310, 2, 2, 0 ), - 'INTERCEPT' => array( 311, 2, 2, 0 ), - 'PEARSON' => array( 312, 2, 2, 0 ), - 'RSQ' => array( 313, 2, 2, 0 ), - 'STEYX' => array( 314, 2, 2, 0 ), - 'SLOPE' => array( 315, 2, 2, 0 ), - 'TTEST' => array( 316, 4, 2, 0 ), - 'PROB' => array( 317, -1, 2, 0 ), - 'DEVSQ' => array( 318, -1, 0, 0 ), - 'GEOMEAN' => array( 319, -1, 0, 0 ), - 'HARMEAN' => array( 320, -1, 0, 0 ), - 'SUMSQ' => array( 321, -1, 0, 0 ), - 'KURT' => array( 322, -1, 0, 0 ), - 'SKEW' => array( 323, -1, 0, 0 ), - 'ZTEST' => array( 324, -1, 0, 0 ), - 'LARGE' => array( 325, 2, 0, 0 ), - 'SMALL' => array( 326, 2, 0, 0 ), - 'QUARTILE' => array( 327, 2, 0, 0 ), - 'PERCENTILE' => array( 328, 2, 0, 0 ), - 'PERCENTRANK' => array( 329, -1, 0, 0 ), - 'MODE' => array( 330, -1, 2, 0 ), - 'TRIMMEAN' => array( 331, 2, 0, 0 ), - 'TINV' => array( 332, 2, 1, 0 ), - 'CONCATENATE' => array( 336, -1, 1, 0 ), - 'POWER' => array( 337, 2, 1, 0 ), - 'RADIANS' => array( 342, 1, 1, 0 ), - 'DEGREES' => array( 343, 1, 1, 0 ), - 'SUBTOTAL' => array( 344, -1, 0, 0 ), - 'SUMIF' => array( 345, -1, 0, 0 ), - 'COUNTIF' => array( 346, 2, 0, 0 ), - 'COUNTBLANK' => array( 347, 1, 0, 0 ), - 'ISPMT' => array( 350, 4, 1, 0 ), - 'DATEDIF' => array( 351, 3, 1, 0 ), - 'DATESTRING' => array( 352, 1, 1, 0 ), - 'NUMBERSTRING' => array( 353, 2, 1, 0 ), - 'ROMAN' => array( 354, -1, 1, 0 ), - 'GETPIVOTDATA' => array( 358, -1, 0, 0 ), - 'HYPERLINK' => array( 359, -1, 1, 0 ), - 'PHONETIC' => array( 360, 1, 0, 0 ), - 'AVERAGEA' => array( 361, -1, 0, 0 ), - 'MAXA' => array( 362, -1, 0, 0 ), - 'MINA' => array( 363, -1, 0, 0 ), - 'STDEVPA' => array( 364, -1, 0, 0 ), - 'VARPA' => array( 365, -1, 0, 0 ), - 'STDEVA' => array( 366, -1, 0, 0 ), - 'VARA' => array( 367, -1, 0, 0 ), - 'BAHTTEXT' => array( 368, 1, 0, 0 ), - ); + 'COUNT' => [0, -1, 0, 0], + 'IF' => [1, -1, 1, 0], + 'ISNA' => [2, 1, 1, 0], + 'ISERROR' => [3, 1, 1, 0], + 'SUM' => [4, -1, 0, 0], + 'AVERAGE' => [5, -1, 0, 0], + 'MIN' => [6, -1, 0, 0], + 'MAX' => [7, -1, 0, 0], + 'ROW' => [8, -1, 0, 0], + 'COLUMN' => [9, -1, 0, 0], + 'NA' => [10, 0, 0, 0], + 'NPV' => [11, -1, 1, 0], + 'STDEV' => [12, -1, 0, 0], + 'DOLLAR' => [13, -1, 1, 0], + 'FIXED' => [14, -1, 1, 0], + 'SIN' => [15, 1, 1, 0], + 'COS' => [16, 1, 1, 0], + 'TAN' => [17, 1, 1, 0], + 'ATAN' => [18, 1, 1, 0], + 'PI' => [19, 0, 1, 0], + 'SQRT' => [20, 1, 1, 0], + 'EXP' => [21, 1, 1, 0], + 'LN' => [22, 1, 1, 0], + 'LOG10' => [23, 1, 1, 0], + 'ABS' => [24, 1, 1, 0], + 'INT' => [25, 1, 1, 0], + 'SIGN' => [26, 1, 1, 0], + 'ROUND' => [27, 2, 1, 0], + 'LOOKUP' => [28, -1, 0, 0], + 'INDEX' => [29, -1, 0, 1], + 'REPT' => [30, 2, 1, 0], + 'MID' => [31, 3, 1, 0], + 'LEN' => [32, 1, 1, 0], + 'VALUE' => [33, 1, 1, 0], + 'TRUE' => [34, 0, 1, 0], + 'FALSE' => [35, 0, 1, 0], + 'AND' => [36, -1, 0, 0], + 'OR' => [37, -1, 0, 0], + 'NOT' => [38, 1, 1, 0], + 'MOD' => [39, 2, 1, 0], + 'DCOUNT' => [40, 3, 0, 0], + 'DSUM' => [41, 3, 0, 0], + 'DAVERAGE' => [42, 3, 0, 0], + 'DMIN' => [43, 3, 0, 0], + 'DMAX' => [44, 3, 0, 0], + 'DSTDEV' => [45, 3, 0, 0], + 'VAR' => [46, -1, 0, 0], + 'DVAR' => [47, 3, 0, 0], + 'TEXT' => [48, 2, 1, 0], + 'LINEST' => [49, -1, 0, 0], + 'TREND' => [50, -1, 0, 0], + 'LOGEST' => [51, -1, 0, 0], + 'GROWTH' => [52, -1, 0, 0], + 'PV' => [56, -1, 1, 0], + 'FV' => [57, -1, 1, 0], + 'NPER' => [58, -1, 1, 0], + 'PMT' => [59, -1, 1, 0], + 'RATE' => [60, -1, 1, 0], + 'MIRR' => [61, 3, 0, 0], + 'IRR' => [62, -1, 0, 0], + 'RAND' => [63, 0, 1, 1], + 'MATCH' => [64, -1, 0, 0], + 'DATE' => [65, 3, 1, 0], + 'TIME' => [66, 3, 1, 0], + 'DAY' => [67, 1, 1, 0], + 'MONTH' => [68, 1, 1, 0], + 'YEAR' => [69, 1, 1, 0], + 'WEEKDAY' => [70, -1, 1, 0], + 'HOUR' => [71, 1, 1, 0], + 'MINUTE' => [72, 1, 1, 0], + 'SECOND' => [73, 1, 1, 0], + 'NOW' => [74, 0, 1, 1], + 'AREAS' => [75, 1, 0, 1], + 'ROWS' => [76, 1, 0, 1], + 'COLUMNS' => [77, 1, 0, 1], + 'OFFSET' => [78, -1, 0, 1], + 'SEARCH' => [82, -1, 1, 0], + 'TRANSPOSE' => [83, 1, 1, 0], + 'TYPE' => [86, 1, 1, 0], + 'ATAN2' => [97, 2, 1, 0], + 'ASIN' => [98, 1, 1, 0], + 'ACOS' => [99, 1, 1, 0], + 'CHOOSE' => [100, -1, 1, 0], + 'HLOOKUP' => [101, -1, 0, 0], + 'VLOOKUP' => [102, -1, 0, 0], + 'ISREF' => [105, 1, 0, 0], + 'LOG' => [109, -1, 1, 0], + 'CHAR' => [111, 1, 1, 0], + 'LOWER' => [112, 1, 1, 0], + 'UPPER' => [113, 1, 1, 0], + 'PROPER' => [114, 1, 1, 0], + 'LEFT' => [115, -1, 1, 0], + 'RIGHT' => [116, -1, 1, 0], + 'EXACT' => [117, 2, 1, 0], + 'TRIM' => [118, 1, 1, 0], + 'REPLACE' => [119, 4, 1, 0], + 'SUBSTITUTE' => [120, -1, 1, 0], + 'CODE' => [121, 1, 1, 0], + 'FIND' => [124, -1, 1, 0], + 'CELL' => [125, -1, 0, 1], + 'ISERR' => [126, 1, 1, 0], + 'ISTEXT' => [127, 1, 1, 0], + 'ISNUMBER' => [128, 1, 1, 0], + 'ISBLANK' => [129, 1, 1, 0], + 'T' => [130, 1, 0, 0], + 'N' => [131, 1, 0, 0], + 'DATEVALUE' => [140, 1, 1, 0], + 'TIMEVALUE' => [141, 1, 1, 0], + 'SLN' => [142, 3, 1, 0], + 'SYD' => [143, 4, 1, 0], + 'DDB' => [144, -1, 1, 0], + 'INDIRECT' => [148, -1, 1, 1], + 'CALL' => [150, -1, 1, 0], + 'CLEAN' => [162, 1, 1, 0], + 'MDETERM' => [163, 1, 2, 0], + 'MINVERSE' => [164, 1, 2, 0], + 'MMULT' => [165, 2, 2, 0], + 'IPMT' => [167, -1, 1, 0], + 'PPMT' => [168, -1, 1, 0], + 'COUNTA' => [169, -1, 0, 0], + 'PRODUCT' => [183, -1, 0, 0], + 'FACT' => [184, 1, 1, 0], + 'DPRODUCT' => [189, 3, 0, 0], + 'ISNONTEXT' => [190, 1, 1, 0], + 'STDEVP' => [193, -1, 0, 0], + 'VARP' => [194, -1, 0, 0], + 'DSTDEVP' => [195, 3, 0, 0], + 'DVARP' => [196, 3, 0, 0], + 'TRUNC' => [197, -1, 1, 0], + 'ISLOGICAL' => [198, 1, 1, 0], + 'DCOUNTA' => [199, 3, 0, 0], + 'USDOLLAR' => [204, -1, 1, 0], + 'FINDB' => [205, -1, 1, 0], + 'SEARCHB' => [206, -1, 1, 0], + 'REPLACEB' => [207, 4, 1, 0], + 'LEFTB' => [208, -1, 1, 0], + 'RIGHTB' => [209, -1, 1, 0], + 'MIDB' => [210, 3, 1, 0], + 'LENB' => [211, 1, 1, 0], + 'ROUNDUP' => [212, 2, 1, 0], + 'ROUNDDOWN' => [213, 2, 1, 0], + 'ASC' => [214, 1, 1, 0], + 'DBCS' => [215, 1, 1, 0], + 'RANK' => [216, -1, 0, 0], + 'ADDRESS' => [219, -1, 1, 0], + 'DAYS360' => [220, -1, 1, 0], + 'TODAY' => [221, 0, 1, 1], + 'VDB' => [222, -1, 1, 0], + 'MEDIAN' => [227, -1, 0, 0], + 'SUMPRODUCT' => [228, -1, 2, 0], + 'SINH' => [229, 1, 1, 0], + 'COSH' => [230, 1, 1, 0], + 'TANH' => [231, 1, 1, 0], + 'ASINH' => [232, 1, 1, 0], + 'ACOSH' => [233, 1, 1, 0], + 'ATANH' => [234, 1, 1, 0], + 'DGET' => [235, 3, 0, 0], + 'INFO' => [244, 1, 1, 1], + 'DB' => [247, -1, 1, 0], + 'FREQUENCY' => [252, 2, 0, 0], + 'ERROR.TYPE' => [261, 1, 1, 0], + 'REGISTER.ID' => [267, -1, 1, 0], + 'AVEDEV' => [269, -1, 0, 0], + 'BETADIST' => [270, -1, 1, 0], + 'GAMMALN' => [271, 1, 1, 0], + 'BETAINV' => [272, -1, 1, 0], + 'BINOMDIST' => [273, 4, 1, 0], + 'CHIDIST' => [274, 2, 1, 0], + 'CHIINV' => [275, 2, 1, 0], + 'COMBIN' => [276, 2, 1, 0], + 'CONFIDENCE' => [277, 3, 1, 0], + 'CRITBINOM' => [278, 3, 1, 0], + 'EVEN' => [279, 1, 1, 0], + 'EXPONDIST' => [280, 3, 1, 0], + 'FDIST' => [281, 3, 1, 0], + 'FINV' => [282, 3, 1, 0], + 'FISHER' => [283, 1, 1, 0], + 'FISHERINV' => [284, 1, 1, 0], + 'FLOOR' => [285, 2, 1, 0], + 'GAMMADIST' => [286, 4, 1, 0], + 'GAMMAINV' => [287, 3, 1, 0], + 'CEILING' => [288, 2, 1, 0], + 'HYPGEOMDIST' => [289, 4, 1, 0], + 'LOGNORMDIST' => [290, 3, 1, 0], + 'LOGINV' => [291, 3, 1, 0], + 'NEGBINOMDIST' => [292, 3, 1, 0], + 'NORMDIST' => [293, 4, 1, 0], + 'NORMSDIST' => [294, 1, 1, 0], + 'NORMINV' => [295, 3, 1, 0], + 'NORMSINV' => [296, 1, 1, 0], + 'STANDARDIZE' => [297, 3, 1, 0], + 'ODD' => [298, 1, 1, 0], + 'PERMUT' => [299, 2, 1, 0], + 'POISSON' => [300, 3, 1, 0], + 'TDIST' => [301, 3, 1, 0], + 'WEIBULL' => [302, 4, 1, 0], + 'SUMXMY2' => [303, 2, 2, 0], + 'SUMX2MY2' => [304, 2, 2, 0], + 'SUMX2PY2' => [305, 2, 2, 0], + 'CHITEST' => [306, 2, 2, 0], + 'CORREL' => [307, 2, 2, 0], + 'COVAR' => [308, 2, 2, 0], + 'FORECAST' => [309, 3, 2, 0], + 'FTEST' => [310, 2, 2, 0], + 'INTERCEPT' => [311, 2, 2, 0], + 'PEARSON' => [312, 2, 2, 0], + 'RSQ' => [313, 2, 2, 0], + 'STEYX' => [314, 2, 2, 0], + 'SLOPE' => [315, 2, 2, 0], + 'TTEST' => [316, 4, 2, 0], + 'PROB' => [317, -1, 2, 0], + 'DEVSQ' => [318, -1, 0, 0], + 'GEOMEAN' => [319, -1, 0, 0], + 'HARMEAN' => [320, -1, 0, 0], + 'SUMSQ' => [321, -1, 0, 0], + 'KURT' => [322, -1, 0, 0], + 'SKEW' => [323, -1, 0, 0], + 'ZTEST' => [324, -1, 0, 0], + 'LARGE' => [325, 2, 0, 0], + 'SMALL' => [326, 2, 0, 0], + 'QUARTILE' => [327, 2, 0, 0], + 'PERCENTILE' => [328, 2, 0, 0], + 'PERCENTRANK' => [329, -1, 0, 0], + 'MODE' => [330, -1, 2, 0], + 'TRIMMEAN' => [331, 2, 0, 0], + 'TINV' => [332, 2, 1, 0], + 'CONCATENATE' => [336, -1, 1, 0], + 'POWER' => [337, 2, 1, 0], + 'RADIANS' => [342, 1, 1, 0], + 'DEGREES' => [343, 1, 1, 0], + 'SUBTOTAL' => [344, -1, 0, 0], + 'SUMIF' => [345, -1, 0, 0], + 'COUNTIF' => [346, 2, 0, 0], + 'COUNTBLANK' => [347, 1, 0, 0], + 'ISPMT' => [350, 4, 1, 0], + 'DATEDIF' => [351, 3, 1, 0], + 'DATESTRING' => [352, 1, 1, 0], + 'NUMBERSTRING' => [353, 2, 1, 0], + 'ROMAN' => [354, -1, 1, 0], + 'GETPIVOTDATA' => [358, -1, 0, 0], + 'HYPERLINK' => [359, -1, 1, 0], + 'PHONETIC' => [360, 1, 0, 0], + 'AVERAGEA' => [361, -1, 0, 0], + 'MAXA' => [362, -1, 0, 0], + 'MINA' => [363, -1, 0, 0], + 'STDEVPA' => [364, -1, 0, 0], + 'VARPA' => [365, -1, 0, 0], + 'STDEVA' => [366, -1, 0, 0], + 'VARA' => [367, -1, 0, 0], + 'BAHTTEXT' => [368, 1, 0, 0], + ]; } /** * Convert a token to the proper ptg value. * - * @access private * @param mixed $token The token to convert. * @return mixed the converted token on success */ private function convert($token) { - if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) { + if (preg_match('/"([^"]|""){0,255}"/', $token)) { return $this->convertString($token); } elseif (is_numeric($token)) { return $this->convertNumber($token); @@ -515,7 +511,7 @@ class Parser } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) { return $this->convertRef2d($token); // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1 - } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u", $token)) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u", $token)) { return $this->convertRef3d($token); // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1 } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u", $token)) { @@ -524,14 +520,14 @@ class Parser } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) { return $this->convertRange2d($token); // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 - } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u", $token)) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u", $token)) { return $this->convertRange3d($token); // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u", $token)) { return $this->convertRange3d($token); // operators (including parentheses) } elseif (isset($this->ptg[$token])) { - return pack("C", $this->ptg[$token]); + return pack('C', $this->ptg[$token]); // match error codes } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') { return $this->convertError($token); @@ -552,26 +548,25 @@ class Parser /** * Convert a number token to ptgInt or ptgNum * - * @access private * @param mixed $num an integer or double for conversion to its ptg value */ private function convertNumber($num) { // Integer in the range 0..2**16-1 if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) { - return pack("Cv", $this->ptg['ptgInt'], $num); + return pack('Cv', $this->ptg['ptgInt'], $num); } else { // A float if (BIFFwriter::getByteOrder()) { // if it's Big Endian $num = strrev($num); } - return pack("Cd", $this->ptg['ptgNum'], $num); + + return pack('Cd', $this->ptg['ptgNum'], $num); } } /** * Convert a string token to ptgStr * - * @access private * @param string $string A string for conversion to its ptg value. * @return mixed the converted token on success */ @@ -580,7 +575,7 @@ class Parser // chop away beggining and ending quotes $string = substr($string, 1, strlen($string) - 2); if (strlen($string) > 255) { - throw new \PhpSpreadsheet\Writer\Exception("String is too long"); + throw new \PhpSpreadsheet\Writer\Exception('String is too long'); } return pack('C', $this->ptg['ptgStr']) . \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeShort($string); @@ -590,30 +585,28 @@ class Parser * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of * args that it takes. * - * @access private * @param string $token The name of the function for convertion to ptg value. - * @param integer $num_args The number of arguments the function receives. + * @param int $num_args The number of arguments the function receives. * @return string The packed ptg for the function */ private function convertFunction($token, $num_args) { - $args = $this->functions[$token][1]; + $args = $this->functions[$token][1]; // $volatile = $this->functions[$token][3]; // Fixed number of args eg. TIME($i, $j, $k). if ($args >= 0) { - return pack("Cv", $this->ptg['ptgFuncV'], $this->functions[$token][0]); + return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]); } // Variable number of args eg. SUM($i, $j, $k, ..). if ($args == -1) { - return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); + return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); } } /** * Convert an Excel range such as A1:D4 to a ptgRefV. * - * @access private * @param string $range An Excel range in the A1:A2 * @param int $class */ @@ -626,7 +619,7 @@ class Parser list($cell1, $cell2) = explode(':', $range); } else { // TODO: use real error codes - throw new \PhpSpreadsheet\Writer\Exception("Unknown range separator"); + throw new \PhpSpreadsheet\Writer\Exception('Unknown range separator'); } // Convert the cell references @@ -635,29 +628,29 @@ class Parser // The ptg value depends on the class of the ptg. if ($class == 0) { - $ptgArea = pack("C", $this->ptg['ptgArea']); + $ptgArea = pack('C', $this->ptg['ptgArea']); } elseif ($class == 1) { - $ptgArea = pack("C", $this->ptg['ptgAreaV']); + $ptgArea = pack('C', $this->ptg['ptgAreaV']); } elseif ($class == 2) { - $ptgArea = pack("C", $this->ptg['ptgAreaA']); + $ptgArea = pack('C', $this->ptg['ptgAreaA']); } else { // TODO: use real error codes throw new \PhpSpreadsheet\Writer\Exception("Unknown class $class"); } - return $ptgArea . $row1 . $row2 . $col1. $col2; + + return $ptgArea . $row1 . $row2 . $col1 . $col2; } /** * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to * a ptgArea3d. * - * @access private * @param string $token An Excel range in the Sheet1!A1:A2 format. * @return mixed The packed ptgArea3d token on success. */ private function convertRange3d($token) { -// $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B) + // $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B) // Split the ref at the ! symbol list($ext_ref, $range) = explode('!', $token); @@ -673,12 +666,12 @@ class Parser list($row1, $col1) = $this->cellToPackedRowcol($cell1); list($row2, $col2) = $this->cellToPackedRowcol($cell2); } else { // It's a rows range (like 26:27) - list($row1, $col1, $row2, $col2) = $this->rangeToPackedRange($cell1.':'.$cell2); + list($row1, $col1, $row2, $col2) = $this->rangeToPackedRange($cell1 . ':' . $cell2); } // The ptg value depends on the class of the ptg. // if ($class == 0) { - $ptgArea = pack("C", $this->ptg['ptgArea3d']); + $ptgArea = pack('C', $this->ptg['ptgArea3d']); // } elseif ($class == 1) { // $ptgArea = pack("C", $this->ptg['ptgArea3dV']); // } elseif ($class == 2) { @@ -687,19 +680,18 @@ class Parser // throw new \PhpSpreadsheet\Writer\Exception("Unknown class $class"); // } - return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2; + return $ptgArea . $ext_ref . $row1 . $row2 . $col1 . $col2; } /** * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV. * - * @access private * @param string $cell An Excel cell reference * @return string The cell in packed() format with the corresponding ptg */ private function convertRef2d($cell) { -// $class = 2; // as far as I know, this is magick. + // $class = 2; // as far as I know, this is magick. // Convert the cell reference $cell_array = $this->cellToPackedRowcol($cell); @@ -711,25 +703,24 @@ class Parser // } elseif ($class == 1) { // $ptgRef = pack("C", $this->ptg['ptgRefV']); // } elseif ($class == 2) { - $ptgRef = pack("C", $this->ptg['ptgRefA']); + $ptgRef = pack('C', $this->ptg['ptgRefA']); // } else { // // TODO: use real error codes // throw new \PhpSpreadsheet\Writer\Exception("Unknown class $class"); // } - return $ptgRef.$row.$col; + return $ptgRef . $row . $col; } /** * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a * ptgRef3d. * - * @access private * @param string $cell An Excel cell reference * @return mixed The packed ptgRef3d token on success. */ private function convertRef3d($cell) { -// $class = 2; // as far as I know, this is magick. + // $class = 2; // as far as I know, this is magick. // Split the ref at the ! symbol list($ext_ref, $cell) = explode('!', $cell); @@ -746,18 +737,17 @@ class Parser // } elseif ($class == 1) { // $ptgRef = pack("C", $this->ptg['ptgRef3dV']); // } elseif ($class == 2) { - $ptgRef = pack("C", $this->ptg['ptgRef3dA']); + $ptgRef = pack('C', $this->ptg['ptgRef3dA']); // } else { // throw new \PhpSpreadsheet\Writer\Exception("Unknown class $class"); // } - return $ptgRef . $ext_ref. $row . $col; + return $ptgRef . $ext_ref . $row . $col; } /** * Convert an error code to a ptgErr * - * @access private * @param string $errorCode The error code for conversion to its ptg value * @return string The error code ptgErr */ @@ -765,28 +755,28 @@ class Parser { switch ($errorCode) { case '#NULL!': - return pack("C", 0x00); + return pack('C', 0x00); case '#DIV/0!': - return pack("C", 0x07); + return pack('C', 0x07); case '#VALUE!': - return pack("C", 0x0F); + return pack('C', 0x0F); case '#REF!': - return pack("C", 0x17); + return pack('C', 0x17); case '#NAME?': - return pack("C", 0x1D); + return pack('C', 0x1D); case '#NUM!': - return pack("C", 0x24); + return pack('C', 0x24); case '#N/A': - return pack("C", 0x2A); + return pack('C', 0x2A); } - return pack("C", 0xFF); + + return pack('C', 0xFF); } /** * Convert the sheet name part of an external reference, for example "Sheet1" or * "Sheet1:Sheet2", to a packed structure. * - * @access private * @param string $ext_ref The name of the external reference * @return string The reference index in packed() format */ @@ -796,7 +786,7 @@ class Parser $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. // Check if there is a sheet range eg., Sheet1:Sheet2. - if (preg_match("/:/", $ext_ref)) { + if (preg_match('/:/', $ext_ref)) { list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); $sheet1 = $this->getSheetIndex($sheet_name1); @@ -810,7 +800,7 @@ class Parser // Reverse max and min sheet numbers if necessary if ($sheet1 > $sheet2) { - list($sheet1, $sheet2) = array($sheet2, $sheet1); + list($sheet1, $sheet2) = [$sheet2, $sheet1]; } } else { // Single sheet name only. $sheet1 = $this->getSheetIndex($ext_ref); @@ -831,7 +821,6 @@ class Parser * (or range). If it doesn't exist yet add it to the workbook's references * array. It assumes all sheet names given must exist. * - * @access private * @param string $ext_ref The name of the external reference * @return mixed The reference index in packed() format on success */ @@ -842,7 +831,7 @@ class Parser $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with ' // Check if there is a sheet range eg., Sheet1:Sheet2. - if (preg_match("/:/", $ext_ref)) { + if (preg_match('/:/', $ext_ref)) { list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); $sheet1 = $this->getSheetIndex($sheet_name1); @@ -856,7 +845,7 @@ class Parser // Reverse max and min sheet numbers if necessary if ($sheet1 > $sheet2) { - list($sheet1, $sheet2) = array($sheet2, $sheet1); + list($sheet1, $sheet2) = [$sheet2, $sheet1]; } } else { // Single sheet name only. $sheet1 = $this->getSheetIndex($ext_ref); @@ -891,9 +880,8 @@ class Parser * sheet names is updated by the addworksheet() method of the * \PhpSpreadsheet\Writer\Excel5\Workbook class. * - * @access private * @param string $sheet_name Sheet name - * @return integer The sheet index, -1 if the sheet was not found + * @return int The sheet index, -1 if the sheet was not found */ private function getSheetIndex($sheet_name) { @@ -909,10 +897,9 @@ class Parser * called by the addWorksheet() method of the * \PhpSpreadsheet\Writer\Excel5\Workbook class. * - * @access public * @see \PhpSpreadsheet\Writer\Excel5\Workbook::addWorksheet() * @param string $name The name of the worksheet being added - * @param integer $index The index of the worksheet being added + * @param int $index The index of the worksheet being added */ public function setExtSheet($name, $index) { @@ -922,7 +909,6 @@ class Parser /** * pack() row and column into the required 3 or 4 byte format. * - * @access private * @param string $cell The Excel cell reference to be packed * @return array Array containing the row and column in packed() format */ @@ -944,14 +930,13 @@ class Parser $row = pack('v', $row); - return array($row, $col); + return [$row, $col]; } /** * pack() row range into the required 3 or 4 byte format. * Just using maximum col/rows, which is probably not the correct solution * - * @access private * @param string $range The Excel range to be packed * @return array Array containing (row1,col1,row2,col2) in packed() format */ @@ -960,9 +945,9 @@ class Parser preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match); // return absolute rows if there is a $ in the ref $row1_rel = empty($match[1]) ? 1 : 0; - $row1 = $match[2]; + $row1 = $match[2]; $row2_rel = empty($match[3]) ? 1 : 0; - $row2 = $match[4]; + $row2 = $match[4]; // Convert 1-index to zero-index --$row1; --$row2; @@ -984,7 +969,7 @@ class Parser $row1 = pack('v', $row1); $row2 = pack('v', $row2); - return array($row1, $col1, $row2, $col2); + return [$row1, $col1, $row2, $col2]; } /** @@ -992,7 +977,6 @@ class Parser * indexed row and column number. Also returns two (0,1) values to indicate * whether the row or column are relative references. * - * @access private * @param string $cell The Excel cell reference in A1 format. * @return array */ @@ -1003,11 +987,11 @@ class Parser $col_rel = empty($match[1]) ? 1 : 0; $col_ref = $match[2]; $row_rel = empty($match[3]) ? 1 : 0; - $row = $match[4]; + $row = $match[4]; // Convert base26 column string to a number. $expn = strlen($col_ref) - 1; - $col = 0; + $col = 0; $col_ref_length = strlen($col_ref); for ($i = 0; $i < $col_ref_length; ++$i) { $col += (ord($col_ref{$i}) - 64) * pow(26, $expn); @@ -1018,13 +1002,11 @@ class Parser --$row; --$col; - return array($row, $col, $row_rel, $col_rel); + return [$row, $col, $row_rel, $col_rel]; } /** * Advance to the next valid token. - * - * @access private */ private function advance() { @@ -1032,12 +1014,12 @@ class Parser $formula_length = strlen($this->formula); // eat up white spaces if ($i < $formula_length) { - while ($this->formula{$i} == " ") { + while ($this->formula{$i} == ' ') { ++$i; } if ($i < ($formula_length - 1)) { - $this->lookAhead = $this->formula{$i+1}; + $this->lookAhead = $this->formula{$i + 1}; } $token = ''; } @@ -1046,7 +1028,7 @@ class Parser $token .= $this->formula{$i}; if ($i < ($formula_length - 1)) { - $this->lookAhead = $this->formula{$i+1}; + $this->lookAhead = $this->formula{$i + 1}; } else { $this->lookAhead = ''; } @@ -1057,11 +1039,12 @@ class Parser //} $this->currentCharacter = $i + 1; $this->currentToken = $token; + return 1; } if ($i < ($formula_length - 2)) { - $this->lookAhead = $this->formula{$i+2}; + $this->lookAhead = $this->formula{$i + 2}; } else { // if we run out of characters lookAhead becomes empty $this->lookAhead = ''; } @@ -1073,72 +1056,73 @@ class Parser /** * Checks if it's a valid token. * - * @access private * @param mixed $token The token to check. * @return mixed The checked token or false on failure */ private function match($token) { switch ($token) { - case "+": - case "-": - case "*": - case "/": - case "(": - case ")": - case ",": - case ";": - case ">=": - case "<=": - case "=": - case "<>": - case "^": - case "&": - case "%": + case '+': + case '-': + case '*': + case '/': + case '(': + case ')': + case ',': + case ';': + case '>=': + case '<=': + case '=': + case '<>': + case '^': + case '&': + case '%': return $token; break; - case ">": + case '>': if ($this->lookAhead == '=') { // it's a GE token break; } + return $token; break; - case "<": + case '<': // it's a LE or a NE token if (($this->lookAhead == '=') or ($this->lookAhead == '>')) { break; } + return $token; break; default: // if it's a reference A1 or $A$1 or $A1 or A$1 - if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/', $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.') and ($this->lookAhead != '!')) { + if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/', $token) and !preg_match('/[0-9]/', $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.') and ($this->lookAhead != '!')) { return $token; - } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match('/[0-9]/', $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) { // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) return $token; - } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) { + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match('/[0-9]/', $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) { // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) return $token; - } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) && !preg_match("/[0-9]/", $this->lookAhead)) { + } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) && !preg_match('/[0-9]/', $this->lookAhead)) { // if it's a range A1:A2 or $A$1:$A$2 return $token; - } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead)) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match('/[0-9]/', $this->lookAhead)) { // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 return $token; - } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead)) { + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match('/[0-9]/', $this->lookAhead)) { // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 return $token; - } elseif (is_numeric($token) and (!is_numeric($token.$this->lookAhead) or ($this->lookAhead == '')) and ($this->lookAhead != '!') and ($this->lookAhead != ':')) { + } elseif (is_numeric($token) and (!is_numeric($token . $this->lookAhead) or ($this->lookAhead == '')) and ($this->lookAhead != '!') and ($this->lookAhead != ':')) { // If it's a number (check that it's not a sheet name or range) return $token; - } elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token) and $this->lookAhead != '"' and (substr_count($token, '"')%2 == 0)) { + } elseif (preg_match('/"([^"]|""){0,255}"/', $token) and $this->lookAhead != '"' and (substr_count($token, '"') % 2 == 0)) { // If it's a string (of maximum 255 characters) return $token; } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') { // If it's an error code return $token; - } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $token) and ($this->lookAhead == "(")) { + } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $token) and ($this->lookAhead == '(')) { // if it's a function call return $token; } elseif (substr($token, -1) == ')') { @@ -1146,6 +1130,7 @@ class Parser // precise nature yet to be determined return $token; } + return ''; } } @@ -1153,7 +1138,6 @@ class Parser /** * The parsing method. It parses a formula. * - * @access public * @param string $formula The formula to parse, without the initial equal * sign (=). * @return mixed true on success @@ -1161,10 +1145,12 @@ class Parser public function parse($formula) { $this->currentCharacter = 0; - $this->formula = $formula; - $this->lookAhead = isset($formula{1}) ? $formula{1} : ''; + $this->formula = $formula; + $this->lookAhead = isset($formula{1}) ? $formula{1} + : ''; $this->advance(); - $this->parseTree = $this->condition(); + $this->parseTree = $this->condition(); + return true; } @@ -1172,41 +1158,41 @@ class Parser * It parses a condition. It assumes the following rule: * Cond -> Expr [(">" | "<") Expr] * - * @access private * @return mixed The parsed ptg'd tree on success */ private function condition() { $result = $this->expression(); - if ($this->currentToken == "<") { + if ($this->currentToken == '<') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgLT', $result, $result2); - } elseif ($this->currentToken == ">") { + } elseif ($this->currentToken == '>') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgGT', $result, $result2); - } elseif ($this->currentToken == "<=") { + } elseif ($this->currentToken == '<=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgLE', $result, $result2); - } elseif ($this->currentToken == ">=") { + } elseif ($this->currentToken == '>=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgGE', $result, $result2); - } elseif ($this->currentToken == "=") { + } elseif ($this->currentToken == '=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgEQ', $result, $result2); - } elseif ($this->currentToken == "<>") { + } elseif ($this->currentToken == '<>') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgNE', $result, $result2); - } elseif ($this->currentToken == "&") { + } elseif ($this->currentToken == '&') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgConcat', $result, $result2); } + return $result; } @@ -1218,13 +1204,12 @@ class Parser * -> "+" Term : Positive value * -> Error code * - * @access private * @return mixed The parsed ptg'd tree on success */ private function expression() { // If it's a string return a string node - if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->currentToken)) { + if (preg_match('/"([^"]|""){0,255}"/', $this->currentToken)) { $tmp = str_replace('""', '"', $this->currentToken); if (($tmp == '"') || ($tmp == '')) { // Trap for "" that has been used for an empty string @@ -1232,37 +1217,41 @@ class Parser } $result = $this->createTree($tmp, '', ''); $this->advance(); + return $result; // If it's an error code } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->currentToken) or $this->currentToken == '#N/A') { $result = $this->createTree($this->currentToken, 'ptgErr', ''); $this->advance(); + return $result; // If it's a negative value - } elseif ($this->currentToken == "-") { + } elseif ($this->currentToken == '-') { // catch "-" Term $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgUminus', $result2, ''); + return $result; // If it's a positive value - } elseif ($this->currentToken == "+") { + } elseif ($this->currentToken == '+') { // catch "+" Term $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgUplus', $result2, ''); + return $result; } $result = $this->term(); - while (($this->currentToken == "+") or - ($this->currentToken == "-") or - ($this->currentToken == "^")) { - /**/ - if ($this->currentToken == "+") { + while (($this->currentToken == '+') or + ($this->currentToken == '-') or + ($this->currentToken == '^')) { + /**/ + if ($this->currentToken == '+') { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgAdd', $result, $result2); - } elseif ($this->currentToken == "-") { + } elseif ($this->currentToken == '-') { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgSub', $result, $result2); @@ -1272,6 +1261,7 @@ class Parser $result = $this->createTree('ptgPower', $result, $result2); } } + return $result; } @@ -1279,13 +1269,13 @@ class Parser * This function just introduces a ptgParen element in the tree, so that Excel * doesn't get confused when working with a parenthesized formula afterwards. * - * @access private * @see fact() * @return array The parsed ptg'd tree */ private function parenthesizedExpression() { $result = $this->createTree('ptgParen', $this->expression(), ''); + return $result; } @@ -1293,16 +1283,15 @@ class Parser * It parses a term. It assumes the following rule: * Term -> Fact [("*" | "/") Fact] * - * @access private * @return mixed The parsed ptg'd tree on success */ private function term() { $result = $this->fact(); - while (($this->currentToken == "*") or - ($this->currentToken == "/")) { - /**/ - if ($this->currentToken == "*") { + while (($this->currentToken == '*') or + ($this->currentToken == '/')) { + /**/ + if ($this->currentToken == '*') { $this->advance(); $result2 = $this->fact(); $result = $this->createTree('ptgMul', $result, $result2); @@ -1312,6 +1301,7 @@ class Parser $result = $this->createTree('ptgDiv', $result, $result2); } } + return $result; } @@ -1323,15 +1313,14 @@ class Parser * | Number * | Function * - * @access private * @return mixed The parsed ptg'd tree on success */ private function fact() { - if ($this->currentToken == "(") { + if ($this->currentToken == '(') { $this->advance(); // eat the "(" $result = $this->parenthesizedExpression(); - if ($this->currentToken != ")") { + if ($this->currentToken != ')') { throw new \PhpSpreadsheet\Writer\Exception("')' token expected."); } $this->advance(); // eat the ")" @@ -1341,16 +1330,19 @@ class Parser if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/', $this->currentToken)) { $result = $this->createTree($this->currentToken, '', ''); $this->advance(); + return $result; - } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->currentToken)) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->currentToken)) { // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) $result = $this->createTree($this->currentToken, '', ''); $this->advance(); + return $result; } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->currentToken)) { // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) $result = $this->createTree($this->currentToken, '', ''); $this->advance(); + return $result; } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->currentToken) or preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->currentToken)) { @@ -1358,13 +1350,15 @@ class Parser // must be an error? $result = $this->createTree($this->currentToken, '', ''); $this->advance(); + return $result; - } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->currentToken)) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->currentToken)) { // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2) // must be an error? //$result = $this->currentToken; $result = $this->createTree($this->currentToken, '', ''); $this->advance(); + return $result; } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->currentToken)) { // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2) @@ -1372,6 +1366,7 @@ class Parser //$result = $this->currentToken; $result = $this->createTree($this->currentToken, '', ''); $this->advance(); + return $result; } elseif (is_numeric($this->currentToken)) { // If it's a number or a percent @@ -1382,33 +1377,34 @@ class Parser $result = $this->createTree($this->currentToken, '', ''); } $this->advance(); + return $result; } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $this->currentToken)) { // if it's a function call $result = $this->func(); + return $result; } - throw new \PhpSpreadsheet\Writer\Exception("Syntax error: ".$this->currentToken.", lookahead: ".$this->lookAhead.", current char: ".$this->currentCharacter); + throw new \PhpSpreadsheet\Writer\Exception('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter); } /** * It parses a function call. It assumes the following rule: * Func -> ( Expr [,Expr]* ) * - * @access private * @return mixed The parsed ptg'd tree on success */ private function func() { $num_args = 0; // number of arguments received $function = strtoupper($this->currentToken); - $result = ''; // initialize result + $result = ''; // initialize result $this->advance(); $this->advance(); // eat the "(" while ($this->currentToken != ')') { - /**/ + /**/ if ($num_args > 0) { - if ($this->currentToken == "," || $this->currentToken == ";") { + if ($this->currentToken == ',' || $this->currentToken == ';') { $this->advance(); // eat the "," or ";" } else { throw new \PhpSpreadsheet\Writer\Exception("Syntax error: comma expected in function $function, arg #{$num_args}"); @@ -1439,7 +1435,6 @@ class Parser * Creates a tree. In fact an array which may have one or two arrays (sub-trees) * as elements. * - * @access private * @param mixed $value The value of this node. * @param mixed $left The left array (sub-tree) or a final node. * @param mixed $right The right array (sub-tree) or a final node. @@ -1447,7 +1442,7 @@ class Parser */ private function createTree($value, $left, $right) { - return array('value' => $value, 'left' => $left, 'right' => $right); + return ['value' => $value, 'left' => $left, 'right' => $right]; } /** @@ -1473,13 +1468,12 @@ class Parser * * In fact all operands, functions, references, etc... are written as ptg's * - * @access public * @param array $tree The optional tree to convert. * @return string The tree in reverse polish notation */ - public function toReversePolish($tree = array()) + public function toReversePolish($tree = []) { - $polish = ""; // the string we are going to return + $polish = ''; // the string we are going to return if (empty($tree)) { // If it's the first call use parseTree $tree = $this->parseTree; } @@ -1511,11 +1505,12 @@ class Parser $left_tree = ''; } // add it's left subtree and return. - return $left_tree.$this->convertFunction($tree['value'], $tree['right']); + return $left_tree . $this->convertFunction($tree['value'], $tree['right']); } else { $converted_tree = $this->convert($tree['value']); } $polish .= $converted_tree; + return $polish; } } diff --git a/src/PhpSpreadsheet/Writer/Excel5/Workbook.php b/src/PhpSpreadsheet/Writer/Excel5/Workbook.php index 5a3184ef..5e7b2631 100644 --- a/src/PhpSpreadsheet/Writer/Excel5/Workbook.php +++ b/src/PhpSpreadsheet/Writer/Excel5/Workbook.php @@ -72,7 +72,7 @@ class Workbook extends BIFFwriter /** * The BIFF file size for the workbook. - * @var integer + * @var int * @see calcSheetOffsets() */ private $biffSize; @@ -81,7 +81,7 @@ class Workbook extends BIFFwriter * XF Writers * @var \PhpSpreadsheet\Writer\Excel5\Xf[] */ - private $xfWriters = array(); + private $xfWriters = []; /** * Array containing the colour palette @@ -91,13 +91,13 @@ class Workbook extends BIFFwriter /** * The codepage indicates the text encoding used for strings - * @var integer + * @var int */ private $codepage; /** * The country code used for localization - * @var integer + * @var int */ private $countryCode; @@ -112,42 +112,42 @@ class Workbook extends BIFFwriter * * @var \PhpSpreadsheet\Writer\Excel5\Font[] */ - private $fontWriters = array(); + private $fontWriters = []; /** * Added fonts. Maps from font's hash => index in workbook * * @var array */ - private $addedFonts = array(); + private $addedFonts = []; /** * Shared number formats * * @var array */ - private $numberFormats = array(); + private $numberFormats = []; /** * Added number formats. Maps from numberFormat's hash => index in workbook * * @var array */ - private $addedNumberFormats = array(); + private $addedNumberFormats = []; /** * Sizes of the binary worksheet streams * * @var array */ - private $worksheetSizes = array(); + private $worksheetSizes = []; /** * Offsets of the binary worksheet streams relative to the start of the global workbook stream * * @var array */ - private $worksheetOffsets = array(); + private $worksheetOffsets = []; /** * Total number of shared strings in workbook @@ -182,7 +182,6 @@ class Workbook extends BIFFwriter */ private $escher; - /** * Class constructor * @@ -198,15 +197,15 @@ class Workbook extends BIFFwriter // It needs to call its parent's constructor explicitly parent::__construct(); - $this->parser = $parser; - $this->biffSize = 0; - $this->palette = array(); + $this->parser = $parser; + $this->biffSize = 0; + $this->palette = []; $this->countryCode = -1; - $this->stringTotal = &$str_total; - $this->stringUnique = &$str_unique; - $this->stringTable = &$str_table; - $this->colors = &$colors; + $this->stringTotal = &$str_total; + $this->stringUnique = &$str_unique; + $this->stringTable = &$str_table; + $this->colors = &$colors; $this->setPaletteXl97(); $this->spreadsheet = $spreadsheet; @@ -237,7 +236,7 @@ class Workbook extends BIFFwriter * Add a new XF writer * * @param \PhpSpreadsheet\Style - * @param boolean Is it a style XF? + * @param bool Is it a style XF? * @return int Index to XF record */ public function addXfWriter($style, $isStyleXf = false) @@ -281,6 +280,7 @@ class Workbook extends BIFFwriter $this->xfWriters[] = $xfWriter; $xfIndex = count($this->xfWriters) - 1; + return $xfIndex; } @@ -305,6 +305,7 @@ class Workbook extends BIFFwriter $this->addedFonts[$fontHashCode] = $fontIndex; } + return $fontIndex; } @@ -321,12 +322,12 @@ class Workbook extends BIFFwriter // then we add a custom color altering the palette $colorIndex = 8 + count($this->colors); $this->palette[$colorIndex] = - array( + [ hexdec(substr($rgb, 0, 2)), hexdec(substr($rgb, 2, 2)), hexdec(substr($rgb, 4)), - 0 - ); + 0, + ]; $this->colors[$rgb] = $colorIndex; } else { // no room for more custom colors, just map to black @@ -342,69 +343,67 @@ class Workbook extends BIFFwriter /** * Sets the colour palette to the Excel 97+ default. - * - * @access private */ private function setPaletteXl97() { - $this->palette = array( - 0x08 => array(0x00, 0x00, 0x00, 0x00), - 0x09 => array(0xff, 0xff, 0xff, 0x00), - 0x0A => array(0xff, 0x00, 0x00, 0x00), - 0x0B => array(0x00, 0xff, 0x00, 0x00), - 0x0C => array(0x00, 0x00, 0xff, 0x00), - 0x0D => array(0xff, 0xff, 0x00, 0x00), - 0x0E => array(0xff, 0x00, 0xff, 0x00), - 0x0F => array(0x00, 0xff, 0xff, 0x00), - 0x10 => array(0x80, 0x00, 0x00, 0x00), - 0x11 => array(0x00, 0x80, 0x00, 0x00), - 0x12 => array(0x00, 0x00, 0x80, 0x00), - 0x13 => array(0x80, 0x80, 0x00, 0x00), - 0x14 => array(0x80, 0x00, 0x80, 0x00), - 0x15 => array(0x00, 0x80, 0x80, 0x00), - 0x16 => array(0xc0, 0xc0, 0xc0, 0x00), - 0x17 => array(0x80, 0x80, 0x80, 0x00), - 0x18 => array(0x99, 0x99, 0xff, 0x00), - 0x19 => array(0x99, 0x33, 0x66, 0x00), - 0x1A => array(0xff, 0xff, 0xcc, 0x00), - 0x1B => array(0xcc, 0xff, 0xff, 0x00), - 0x1C => array(0x66, 0x00, 0x66, 0x00), - 0x1D => array(0xff, 0x80, 0x80, 0x00), - 0x1E => array(0x00, 0x66, 0xcc, 0x00), - 0x1F => array(0xcc, 0xcc, 0xff, 0x00), - 0x20 => array(0x00, 0x00, 0x80, 0x00), - 0x21 => array(0xff, 0x00, 0xff, 0x00), - 0x22 => array(0xff, 0xff, 0x00, 0x00), - 0x23 => array(0x00, 0xff, 0xff, 0x00), - 0x24 => array(0x80, 0x00, 0x80, 0x00), - 0x25 => array(0x80, 0x00, 0x00, 0x00), - 0x26 => array(0x00, 0x80, 0x80, 0x00), - 0x27 => array(0x00, 0x00, 0xff, 0x00), - 0x28 => array(0x00, 0xcc, 0xff, 0x00), - 0x29 => array(0xcc, 0xff, 0xff, 0x00), - 0x2A => array(0xcc, 0xff, 0xcc, 0x00), - 0x2B => array(0xff, 0xff, 0x99, 0x00), - 0x2C => array(0x99, 0xcc, 0xff, 0x00), - 0x2D => array(0xff, 0x99, 0xcc, 0x00), - 0x2E => array(0xcc, 0x99, 0xff, 0x00), - 0x2F => array(0xff, 0xcc, 0x99, 0x00), - 0x30 => array(0x33, 0x66, 0xff, 0x00), - 0x31 => array(0x33, 0xcc, 0xcc, 0x00), - 0x32 => array(0x99, 0xcc, 0x00, 0x00), - 0x33 => array(0xff, 0xcc, 0x00, 0x00), - 0x34 => array(0xff, 0x99, 0x00, 0x00), - 0x35 => array(0xff, 0x66, 0x00, 0x00), - 0x36 => array(0x66, 0x66, 0x99, 0x00), - 0x37 => array(0x96, 0x96, 0x96, 0x00), - 0x38 => array(0x00, 0x33, 0x66, 0x00), - 0x39 => array(0x33, 0x99, 0x66, 0x00), - 0x3A => array(0x00, 0x33, 0x00, 0x00), - 0x3B => array(0x33, 0x33, 0x00, 0x00), - 0x3C => array(0x99, 0x33, 0x00, 0x00), - 0x3D => array(0x99, 0x33, 0x66, 0x00), - 0x3E => array(0x33, 0x33, 0x99, 0x00), - 0x3F => array(0x33, 0x33, 0x33, 0x00), - ); + $this->palette = [ + 0x08 => [0x00, 0x00, 0x00, 0x00], + 0x09 => [0xff, 0xff, 0xff, 0x00], + 0x0A => [0xff, 0x00, 0x00, 0x00], + 0x0B => [0x00, 0xff, 0x00, 0x00], + 0x0C => [0x00, 0x00, 0xff, 0x00], + 0x0D => [0xff, 0xff, 0x00, 0x00], + 0x0E => [0xff, 0x00, 0xff, 0x00], + 0x0F => [0x00, 0xff, 0xff, 0x00], + 0x10 => [0x80, 0x00, 0x00, 0x00], + 0x11 => [0x00, 0x80, 0x00, 0x00], + 0x12 => [0x00, 0x00, 0x80, 0x00], + 0x13 => [0x80, 0x80, 0x00, 0x00], + 0x14 => [0x80, 0x00, 0x80, 0x00], + 0x15 => [0x00, 0x80, 0x80, 0x00], + 0x16 => [0xc0, 0xc0, 0xc0, 0x00], + 0x17 => [0x80, 0x80, 0x80, 0x00], + 0x18 => [0x99, 0x99, 0xff, 0x00], + 0x19 => [0x99, 0x33, 0x66, 0x00], + 0x1A => [0xff, 0xff, 0xcc, 0x00], + 0x1B => [0xcc, 0xff, 0xff, 0x00], + 0x1C => [0x66, 0x00, 0x66, 0x00], + 0x1D => [0xff, 0x80, 0x80, 0x00], + 0x1E => [0x00, 0x66, 0xcc, 0x00], + 0x1F => [0xcc, 0xcc, 0xff, 0x00], + 0x20 => [0x00, 0x00, 0x80, 0x00], + 0x21 => [0xff, 0x00, 0xff, 0x00], + 0x22 => [0xff, 0xff, 0x00, 0x00], + 0x23 => [0x00, 0xff, 0xff, 0x00], + 0x24 => [0x80, 0x00, 0x80, 0x00], + 0x25 => [0x80, 0x00, 0x00, 0x00], + 0x26 => [0x00, 0x80, 0x80, 0x00], + 0x27 => [0x00, 0x00, 0xff, 0x00], + 0x28 => [0x00, 0xcc, 0xff, 0x00], + 0x29 => [0xcc, 0xff, 0xff, 0x00], + 0x2A => [0xcc, 0xff, 0xcc, 0x00], + 0x2B => [0xff, 0xff, 0x99, 0x00], + 0x2C => [0x99, 0xcc, 0xff, 0x00], + 0x2D => [0xff, 0x99, 0xcc, 0x00], + 0x2E => [0xcc, 0x99, 0xff, 0x00], + 0x2F => [0xff, 0xcc, 0x99, 0x00], + 0x30 => [0x33, 0x66, 0xff, 0x00], + 0x31 => [0x33, 0xcc, 0xcc, 0x00], + 0x32 => [0x99, 0xcc, 0x00, 0x00], + 0x33 => [0xff, 0xcc, 0x00, 0x00], + 0x34 => [0xff, 0x99, 0x00, 0x00], + 0x35 => [0xff, 0x66, 0x00, 0x00], + 0x36 => [0x66, 0x66, 0x99, 0x00], + 0x37 => [0x96, 0x96, 0x96, 0x00], + 0x38 => [0x00, 0x33, 0x66, 0x00], + 0x39 => [0x33, 0x99, 0x66, 0x00], + 0x3A => [0x00, 0x33, 0x00, 0x00], + 0x3B => [0x33, 0x33, 0x00, 0x00], + 0x3C => [0x99, 0x33, 0x00, 0x00], + 0x3D => [0x99, 0x33, 0x66, 0x00], + 0x3E => [0x33, 0x33, 0x99, 0x00], + 0x3F => [0x33, 0x33, 0x33, 0x00], + ]; } /** @@ -465,15 +464,13 @@ class Workbook extends BIFFwriter /** * Calculate offsets for Worksheet BOF records. - * - * @access private */ private function calcSheetOffsets() { $boundsheet_length = 10; // fixed length for a BOUNDSHEET record // size of Workbook globals part 1 + 3 - $offset = $this->_datasize; + $offset = $this->_datasize; // add size of Workbook globals part 2, the length of the SHEET records $total_worksheets = count($this->spreadsheet->getAllSheets()); @@ -650,7 +647,7 @@ class Workbook extends BIFFwriter foreach ($namedRanges as $namedRange) { // Create absolute coordinate $range = \PhpSpreadsheet\Cell::splitRange($namedRange->getRange()); - for ($i = 0; $i < count($range); $i++) { + for ($i = 0; $i < count($range); ++$i) { $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . \PhpSpreadsheet\Cell::absoluteCoordinate($range[$i][0]); if (isset($range[$i][1])) { $range[$i][1] = \PhpSpreadsheet\Cell::absoluteCoordinate($range[$i][1]); @@ -791,7 +788,7 @@ class Workbook extends BIFFwriter * @param string $name The name in UTF-8 * @param string $formulaData The binary formula data * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global - * @param boolean $isBuiltIn Built-in name? + * @param bool $isBuiltIn Built-in name? * @return string Complete binary record data */ private function writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false) @@ -826,7 +823,7 @@ class Workbook extends BIFFwriter * @param string $name * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global * @param integer[][] $rangeBounds range boundaries - * @param boolean $isHidden + * @param bool $isHidden * @return string Complete binary record data * */ private function writeShortNameBiff8($name, $sheetIndex, $rangeBounds, $isHidden = false) @@ -836,7 +833,7 @@ class Workbook extends BIFFwriter // option flags $options = ($isHidden ? 0x21 : 0x00); - $extra = pack( + $extra = pack( 'Cvvvvv', 0x3B, $sheetIndex - 1, @@ -866,10 +863,10 @@ class Workbook extends BIFFwriter { $record = 0x0042; // Record identifier $length = 0x0002; // Number of bytes to follow - $cv = $this->codepage; // The code page + $cv = $this->codepage; // The code page $header = pack('vv', $record, $length); - $data = pack('v', $cv); + $data = pack('v', $cv); $this->append($header . $data); } @@ -882,8 +879,8 @@ class Workbook extends BIFFwriter $record = 0x003D; // Record identifier $length = 0x0012; // Number of bytes to follow - $xWn = 0x0000; // Horizontal position of window - $yWn = 0x0000; // Vertical position of window + $xWn = 0x0000; // Horizontal position of window + $yWn = 0x0000; // Vertical position of window $dxWn = 0x25BC; // Width of window $dyWn = 0x1572; // Height of window @@ -896,10 +893,10 @@ class Workbook extends BIFFwriter // not supported by PhpSpreadsheet, set to 0 $itabFirst = 0; // 1st displayed worksheet - $itabCur = $this->spreadsheet->getActiveSheetIndex(); // Active worksheet + $itabCur = $this->spreadsheet->getActiveSheetIndex(); // Active worksheet - $header = pack("vv", $record, $length); - $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio); + $header = pack('vv', $record, $length); + $data = pack('vvvvvvvvv', $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio); $this->append($header . $data); } @@ -907,12 +904,12 @@ class Workbook extends BIFFwriter * Writes Excel BIFF BOUNDSHEET record. * * @param \PhpSpreadsheet\Worksheet $sheet Worksheet name - * @param integer $offset Location of worksheet BOF + * @param int $offset Location of worksheet BOF */ private function writeBoundSheet($sheet, $offset) { $sheetname = $sheet->getTitle(); - $record = 0x0085; // Record identifier + $record = 0x0085; // Record identifier // sheet state switch ($sheet->getSheetState()) { @@ -935,11 +932,11 @@ class Workbook extends BIFFwriter $grbit = 0x0000; // Visibility and sheet type - $data = pack("VCC", $offset, $ss, $st); + $data = pack('VCC', $offset, $ss, $st); $data .= \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeShort($sheetname); $length = strlen($data); - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); $this->append($header . $data); } @@ -948,18 +945,18 @@ class Workbook extends BIFFwriter */ private function writeSupbookInternal() { - $record = 0x01AE; // Record identifier - $length = 0x0004; // Bytes to follow + $record = 0x01AE; // Record identifier + $length = 0x0004; // Bytes to follow + + $header = pack('vv', $record, $length); + $data = pack('vv', $this->spreadsheet->getSheetCount(), 0x0401); - $header = pack("vv", $record, $length); - $data = pack("vv", $this->spreadsheet->getSheetCount(), 0x0401); return $this->writeData($header . $data); } /** * Writes the Excel BIFF EXTERNSHEET record. These references are used by * formulas. - * */ private function writeExternalsheetBiff8() { @@ -968,11 +965,12 @@ class Workbook extends BIFFwriter $length = 2 + 6 * $totalReferences; // Number of bytes to follow $supbook_index = 0; // FIXME: only using internal SUPBOOK record - $header = pack("vv", $record, $length); - $data = pack('v', $totalReferences); + $header = pack('vv', $record, $length); + $data = pack('v', $totalReferences); for ($i = 0; $i < $totalReferences; ++$i) { $data .= $this->parser->references[$i]; } + return $this->writeData($header . $data); } @@ -984,12 +982,12 @@ class Workbook extends BIFFwriter $record = 0x0293; // Record identifier $length = 0x0004; // Bytes to follow - $ixfe = 0x8000; // Index to cell style XF + $ixfe = 0x8000; // Index to cell style XF $BuiltIn = 0x00; // Built-in style - $iLevel = 0xff; // Outline style level + $iLevel = 0xff; // Outline style level - $header = pack("vv", $record, $length); - $data = pack("vCC", $ixfe, $BuiltIn, $iLevel); + $header = pack('vv', $record, $length); + $data = pack('vCC', $ixfe, $BuiltIn, $iLevel); $this->append($header . $data); } @@ -997,7 +995,7 @@ class Workbook extends BIFFwriter * Writes Excel FORMAT record for non "built-in" numerical formats. * * @param string $format Custom format string - * @param integer $ifmt Format index code + * @param int $ifmt Format index code */ private function writeNumberFormat($format, $ifmt) { @@ -1006,9 +1004,8 @@ class Workbook extends BIFFwriter $numberFormatString = \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeLong($format); $length = 2 + strlen($numberFormatString); // Number of bytes to follow - - $header = pack("vv", $record, $length); - $data = pack("v", $ifmt) . $numberFormatString; + $header = pack('vv', $record, $length); + $data = pack('v', $ifmt) . $numberFormatString; $this->append($header . $data); } @@ -1020,12 +1017,12 @@ class Workbook extends BIFFwriter $record = 0x0022; // Record identifier $length = 0x0002; // Bytes to follow - $f1904 = (\PhpSpreadsheet\Shared\Date::getExcelCalendar() == \PhpSpreadsheet\Shared\Date::CALENDAR_MAC_1904) + $f1904 = (\PhpSpreadsheet\Shared\Date::getExcelCalendar() == \PhpSpreadsheet\Shared\Date::CALENDAR_MAC_1904) ? 1 : 0; // Flag for 1904 date system - $header = pack("vv", $record, $length); - $data = pack("v", $f1904); + $header = pack('vv', $record, $length); + $data = pack('v', $f1904); $this->append($header . $data); } @@ -1039,15 +1036,15 @@ class Workbook extends BIFFwriter * * A similar method is used in Worksheet.php for a slightly different purpose. * - * @param integer $cxals Number of external references + * @param int $cxals Number of external references */ private function writeExternalCount($cxals) { $record = 0x0016; // Record identifier $length = 0x0002; // Number of bytes to follow - $header = pack("vv", $record, $length); - $data = pack("v", $cxals); + $header = pack('vv', $record, $length); + $data = pack('v', $cxals); $this->append($header . $data); } @@ -1065,11 +1062,11 @@ class Workbook extends BIFFwriter $record = 0x0017; // Record identifier $length = 0x02 + strlen($sheetname); // Number of bytes to follow - $cch = strlen($sheetname); // Length of sheet name - $rgch = 0x03; // Filename encoding + $cch = strlen($sheetname); // Length of sheet name + $rgch = 0x03; // Filename encoding - $header = pack("vv", $record, $length); - $data = pack("CC", $cch, $rgch); + $header = pack('vv', $record, $length); + $data = pack('CC', $cch, $rgch); $this->append($header . $data . $sheetname); } @@ -1077,29 +1074,29 @@ class Workbook extends BIFFwriter * Store the NAME record in the short format that is used for storing the print * area, repeat rows only and repeat columns only. * - * @param integer $index Sheet index - * @param integer $type Built-in name type - * @param integer $rowmin Start row - * @param integer $rowmax End row - * @param integer $colmin Start colum - * @param integer $colmax End column + * @param int $index Sheet index + * @param int $type Built-in name type + * @param int $rowmin Start row + * @param int $rowmax End row + * @param int $colmin Start colum + * @param int $colmax End column */ private function writeNameShort($index, $type, $rowmin, $rowmax, $colmin, $colmax) { $record = 0x0018; // Record identifier $length = 0x0024; // Number of bytes to follow - $grbit = 0x0020; // Option flags - $chKey = 0x00; // Keyboard shortcut - $cch = 0x01; // Length of text name - $cce = 0x0015; // Length of text definition - $ixals = $index + 1; // Sheet index - $itab = $ixals; // Equal to ixals - $cchCustMenu = 0x00; // Length of cust menu text + $grbit = 0x0020; // Option flags + $chKey = 0x00; // Keyboard shortcut + $cch = 0x01; // Length of text name + $cce = 0x0015; // Length of text definition + $ixals = $index + 1; // Sheet index + $itab = $ixals; // Equal to ixals + $cchCustMenu = 0x00; // Length of cust menu text $cchDescription = 0x00; // Length of description text - $cchHelptopic = 0x00; // Length of help topic text - $cchStatustext = 0x00; // Length of status bar text - $rgch = $type; // Built-in name type + $cchHelptopic = 0x00; // Length of help topic text + $cchStatustext = 0x00; // Length of status bar text + $rgch = $type; // Built-in name type $unknown03 = 0x3b; $unknown04 = 0xffff - $index; @@ -1108,30 +1105,30 @@ class Workbook extends BIFFwriter $unknown07 = 0x1087; $unknown08 = 0x8005; - $header = pack("vv", $record, $length); - $data = pack("v", $grbit); - $data .= pack("C", $chKey); - $data .= pack("C", $cch); - $data .= pack("v", $cce); - $data .= pack("v", $ixals); - $data .= pack("v", $itab); - $data .= pack("C", $cchCustMenu); - $data .= pack("C", $cchDescription); - $data .= pack("C", $cchHelptopic); - $data .= pack("C", $cchStatustext); - $data .= pack("C", $rgch); - $data .= pack("C", $unknown03); - $data .= pack("v", $unknown04); - $data .= pack("v", $unknown05); - $data .= pack("v", $unknown06); - $data .= pack("v", $unknown07); - $data .= pack("v", $unknown08); - $data .= pack("v", $index); - $data .= pack("v", $index); - $data .= pack("v", $rowmin); - $data .= pack("v", $rowmax); - $data .= pack("C", $colmin); - $data .= pack("C", $colmax); + $header = pack('vv', $record, $length); + $data = pack('v', $grbit); + $data .= pack('C', $chKey); + $data .= pack('C', $cch); + $data .= pack('v', $cce); + $data .= pack('v', $ixals); + $data .= pack('v', $itab); + $data .= pack('C', $cchCustMenu); + $data .= pack('C', $cchDescription); + $data .= pack('C', $cchHelptopic); + $data .= pack('C', $cchStatustext); + $data .= pack('C', $rgch); + $data .= pack('C', $unknown03); + $data .= pack('v', $unknown04); + $data .= pack('v', $unknown05); + $data .= pack('v', $unknown06); + $data .= pack('v', $unknown07); + $data .= pack('v', $unknown08); + $data .= pack('v', $index); + $data .= pack('v', $index); + $data .= pack('v', $rowmin); + $data .= pack('v', $rowmax); + $data .= pack('C', $colmin); + $data .= pack('C', $colmax); $this->append($header . $data); } @@ -1141,80 +1138,80 @@ class Workbook extends BIFFwriter * writeNameShort() but we use a separate method to keep the code clean. * Code abstraction for reuse can be carried too far, and I should know. ;-) * - * @param integer $index Sheet index - * @param integer $type Built-in name type - * @param integer $rowmin Start row - * @param integer $rowmax End row - * @param integer $colmin Start colum - * @param integer $colmax End column + * @param int $index Sheet index + * @param int $type Built-in name type + * @param int $rowmin Start row + * @param int $rowmax End row + * @param int $colmin Start colum + * @param int $colmax End column */ private function writeNameLong($index, $type, $rowmin, $rowmax, $colmin, $colmax) { - $record = 0x0018; // Record identifier - $length = 0x003d; // Number of bytes to follow - $grbit = 0x0020; // Option flags - $chKey = 0x00; // Keyboard shortcut - $cch = 0x01; // Length of text name - $cce = 0x002e; // Length of text definition - $ixals = $index + 1; // Sheet index - $itab = $ixals; // Equal to ixals - $cchCustMenu = 0x00; // Length of cust menu text - $cchDescription = 0x00; // Length of description text - $cchHelptopic = 0x00; // Length of help topic text - $cchStatustext = 0x00; // Length of status bar text - $rgch = $type; // Built-in name type + $record = 0x0018; // Record identifier + $length = 0x003d; // Number of bytes to follow + $grbit = 0x0020; // Option flags + $chKey = 0x00; // Keyboard shortcut + $cch = 0x01; // Length of text name + $cce = 0x002e; // Length of text definition + $ixals = $index + 1; // Sheet index + $itab = $ixals; // Equal to ixals + $cchCustMenu = 0x00; // Length of cust menu text + $cchDescription = 0x00; // Length of description text + $cchHelptopic = 0x00; // Length of help topic text + $cchStatustext = 0x00; // Length of status bar text + $rgch = $type; // Built-in name type - $unknown01 = 0x29; - $unknown02 = 0x002b; - $unknown03 = 0x3b; - $unknown04 = 0xffff-$index; - $unknown05 = 0x0000; - $unknown06 = 0x0000; - $unknown07 = 0x1087; - $unknown08 = 0x8008; + $unknown01 = 0x29; + $unknown02 = 0x002b; + $unknown03 = 0x3b; + $unknown04 = 0xffff - $index; + $unknown05 = 0x0000; + $unknown06 = 0x0000; + $unknown07 = 0x1087; + $unknown08 = 0x8008; - $header = pack("vv", $record, $length); - $data = pack("v", $grbit); - $data .= pack("C", $chKey); - $data .= pack("C", $cch); - $data .= pack("v", $cce); - $data .= pack("v", $ixals); - $data .= pack("v", $itab); - $data .= pack("C", $cchCustMenu); - $data .= pack("C", $cchDescription); - $data .= pack("C", $cchHelptopic); - $data .= pack("C", $cchStatustext); - $data .= pack("C", $rgch); - $data .= pack("C", $unknown01); - $data .= pack("v", $unknown02); + $header = pack('vv', $record, $length); + $data = pack('v', $grbit); + $data .= pack('C', $chKey); + $data .= pack('C', $cch); + $data .= pack('v', $cce); + $data .= pack('v', $ixals); + $data .= pack('v', $itab); + $data .= pack('C', $cchCustMenu); + $data .= pack('C', $cchDescription); + $data .= pack('C', $cchHelptopic); + $data .= pack('C', $cchStatustext); + $data .= pack('C', $rgch); + $data .= pack('C', $unknown01); + $data .= pack('v', $unknown02); // Column definition - $data .= pack("C", $unknown03); - $data .= pack("v", $unknown04); - $data .= pack("v", $unknown05); - $data .= pack("v", $unknown06); - $data .= pack("v", $unknown07); - $data .= pack("v", $unknown08); - $data .= pack("v", $index); - $data .= pack("v", $index); - $data .= pack("v", 0x0000); - $data .= pack("v", 0x3fff); - $data .= pack("C", $colmin); - $data .= pack("C", $colmax); + $data .= pack('C', $unknown03); + $data .= pack('v', $unknown04); + $data .= pack('v', $unknown05); + $data .= pack('v', $unknown06); + $data .= pack('v', $unknown07); + $data .= pack('v', $unknown08); + $data .= pack('v', $index); + $data .= pack('v', $index); + $data .= pack('v', 0x0000); + $data .= pack('v', 0x3fff); + $data .= pack('C', $colmin); + $data .= pack('C', $colmax); // Row definition - $data .= pack("C", $unknown03); - $data .= pack("v", $unknown04); - $data .= pack("v", $unknown05); - $data .= pack("v", $unknown06); - $data .= pack("v", $unknown07); - $data .= pack("v", $unknown08); - $data .= pack("v", $index); - $data .= pack("v", $index); - $data .= pack("v", $rowmin); - $data .= pack("v", $rowmax); - $data .= pack("C", 0x00); - $data .= pack("C", 0xff); + $data .= pack('C', $unknown03); + $data .= pack('v', $unknown04); + $data .= pack('v', $unknown05); + $data .= pack('v', $unknown06); + $data .= pack('v', $unknown07); + $data .= pack('v', $unknown08); + $data .= pack('v', $index); + $data .= pack('v', $index); + $data .= pack('v', $rowmin); + $data .= pack('v', $rowmax); + $data .= pack('C', 0x00); + $data .= pack('C', 0xff); // End of data - $data .= pack("C", 0x10); + $data .= pack('C', 0x10); $this->append($header . $data); } @@ -1262,17 +1259,17 @@ class Workbook extends BIFFwriter $record = 0x0092; // Record identifier $length = 2 + 4 * count($aref); // Number of bytes to follow - $ccv = count($aref); // Number of RGB values to follow + $ccv = count($aref); // Number of RGB values to follow $data = ''; // The RGB data // Pack the RGB data foreach ($aref as $color) { foreach ($color as $byte) { - $data .= pack("C", $byte); + $data .= pack('C', $byte); } } - $header = pack("vvv", $record, $length, $ccv); + $header = pack('vvv', $record, $length, $ccv); $this->append($header . $data); } @@ -1296,20 +1293,20 @@ class Workbook extends BIFFwriter $continue_limit = 8224; // initialize array of record data blocks - $recordDatas = array(); + $recordDatas = []; // start SST record data block with total number of strings, total number of unique strings - $recordData = pack("VV", $this->stringTotal, $this->stringUnique); + $recordData = pack('VV', $this->stringTotal, $this->stringUnique); // loop through all (unique) strings in shared strings table foreach (array_keys($this->stringTable) as $string) { // here $string is a BIFF8 encoded string // length = character count - $headerinfo = unpack("vlength/Cencoding", $string); + $headerinfo = unpack('vlength/Cencoding', $string); // currently, this is always 1 = uncompressed - $encoding = $headerinfo["encoding"]; + $encoding = $headerinfo['encoding']; // initialize finished writing current $string $finished = false; @@ -1392,7 +1389,7 @@ class Workbook extends BIFFwriter // first block should have the SST record header, remaing should have CONTINUE header $record = ($i == 0) ? 0x00FC : 0x003C; - $header = pack("vv", $record, strlen($recordData)); + $header = pack('vv', $record, strlen($recordData)); $data = $header . $recordData; $chunk .= $this->writeData($data); @@ -1413,7 +1410,7 @@ class Workbook extends BIFFwriter $record = 0x00EB; $length = strlen($data); - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); return $this->writeData($header . $data); } else { diff --git a/src/PhpSpreadsheet/Writer/Excel5/Worksheet.php b/src/PhpSpreadsheet/Writer/Excel5/Worksheet.php index a55c2292..645aba5b 100644 --- a/src/PhpSpreadsheet/Writer/Excel5/Worksheet.php +++ b/src/PhpSpreadsheet/Writer/Excel5/Worksheet.php @@ -72,7 +72,7 @@ class Worksheet extends BIFFwriter /** * Maximum number of characters for a string (LABEL record in BIFF5) - * @var integer + * @var int */ private $xlsStringMaxLength; @@ -90,13 +90,13 @@ class Worksheet extends BIFFwriter /** * The active pane for the worksheet - * @var integer + * @var int */ private $activePane; /** * Whether to use outline. - * @var integer + * @var int */ private $outlineOn; @@ -120,13 +120,13 @@ class Worksheet extends BIFFwriter /** * Reference to the total number of strings in the workbook - * @var integer + * @var int */ private $stringTotal; /** * Reference to the number of unique strings in the workbook - * @var integer + * @var int */ private $stringUnique; @@ -200,7 +200,7 @@ class Worksheet extends BIFFwriter * @param array &$str_table String Table * @param array &$colors Colour Table * @param mixed $parser The formula parser created for the Workbook - * @param boolean $preCalculateFormulas Flag indicating whether formulas should be calculated or just written + * @param bool $preCalculateFormulas Flag indicating whether formulas should be calculated or just written * @param string $phpSheet The worksheet to write * @param \PhpSpreadsheet\Worksheet $phpSheet */ @@ -212,45 +212,44 @@ class Worksheet extends BIFFwriter // change BIFFwriter limit for CONTINUE records // $this->_limit = 8224; - $this->_preCalculateFormulas = $preCalculateFormulas; - $this->stringTotal = &$str_total; - $this->stringUnique = &$str_unique; - $this->stringTable = &$str_table; - $this->colors = &$colors; - $this->parser = $parser; + $this->stringTotal = &$str_total; + $this->stringUnique = &$str_unique; + $this->stringTable = &$str_table; + $this->colors = &$colors; + $this->parser = $parser; $this->phpSheet = $phpSheet; //$this->ext_sheets = array(); //$this->offset = 0; $this->xlsStringMaxLength = 255; - $this->columnInfo = array(); - $this->selection = array(0,0,0,0); - $this->activePane = 3; + $this->columnInfo = []; + $this->selection = [0, 0, 0, 0]; + $this->activePane = 3; $this->_print_headers = 0; - $this->outlineStyle = 0; - $this->outlineBelow = 1; - $this->outlineRight = 1; - $this->outlineOn = 1; + $this->outlineStyle = 0; + $this->outlineBelow = 1; + $this->outlineRight = 1; + $this->outlineOn = 1; - $this->fontHashIndex = array(); + $this->fontHashIndex = []; // calculate values for DIMENSIONS record $minR = 1; $minC = 'A'; - $maxR = $this->phpSheet->getHighestRow(); + $maxR = $this->phpSheet->getHighestRow(); $maxC = $this->phpSheet->getHighestColumn(); // Determine lowest and highest column and row // $this->firstRowIndex = ($minR > 65535) ? 65535 : $minR; - $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ; + $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR; $this->firstColumnIndex = \PhpSpreadsheet\Cell::columnIndexFromString($minC); - $this->lastColumnIndex = \PhpSpreadsheet\Cell::columnIndexFromString($maxC); + $this->lastColumnIndex = \PhpSpreadsheet\Cell::columnIndexFromString($maxC); // if ($this->firstColumnIndex > 255) $this->firstColumnIndex = 255; if ($this->lastColumnIndex > 255) { @@ -264,7 +263,6 @@ class Worksheet extends BIFFwriter * Add data to the beginning of the workbook (note the reverse order) * and to the end of the workbook. * - * @access public * @see \PhpSpreadsheet\Writer\Excel5\Workbook::storeWorkbook() */ public function close() @@ -294,7 +292,7 @@ class Worksheet extends BIFFwriter } $columnDimensions = $phpSheet->getColumnDimensions(); - $maxCol = $this->lastColumnIndex -1; + $maxCol = $this->lastColumnIndex - 1; for ($i = 0; $i <= $maxCol; ++$i) { $hidden = 0; $level = 0; @@ -320,7 +318,7 @@ class Worksheet extends BIFFwriter // $xfIndex The optional cell style Xf index to apply to the columns // $hidden The optional hidden atribute // $level The optional outline level - $this->columnInfo[] = array($i, $i, $width, $xfIndex, $hidden, $level); + $this->columnInfo[] = [$i, $i, $width, $xfIndex, $hidden, $level]; } // Write GUTS @@ -401,7 +399,7 @@ class Worksheet extends BIFFwriter $cVal = $cell->getValue(); if ($cVal instanceof \PhpSpreadsheet\RichText) { // $this->writeString($row, $column, $cVal->getPlainText(), $xfIndex); - $arrcRun = array(); + $arrcRun = []; $str_len = \PhpSpreadsheet\Shared\StringHelper::countCharacters($cVal->getPlainText(), 'UTF-8'); $str_pos = 0; $elements = $cVal->getRichTextElements(); @@ -412,7 +410,7 @@ class Worksheet extends BIFFwriter } else { $str_fontidx = 0; } - $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx); + $arrcRun[] = ['strlen' => $str_pos, 'fontidx' => $str_fontidx]; // Position FROM $str_pos += \PhpSpreadsheet\Shared\StringHelper::countCharacters($element->getText(), 'UTF-8'); } @@ -499,7 +497,7 @@ class Worksheet extends BIFFwriter $arrConditionalStyles = $phpSheet->getConditionalStylesCollection(); if (!empty($arrConditionalStyles)) { - $arrConditional = array(); + $arrConditional = []; // @todo CFRule & CFHeader // Write CFHEADER record $this->writeCFHeader(); @@ -544,7 +542,7 @@ class Worksheet extends BIFFwriter } $firstCellCoordinates = \PhpSpreadsheet\Cell::coordinateFromString($firstCell); // e.g. array(0, 1) - $lastCellCoordinates = \PhpSpreadsheet\Cell::coordinateFromString($lastCell); // e.g. array(1, 6) + $lastCellCoordinates = \PhpSpreadsheet\Cell::coordinateFromString($lastCell); // e.g. array(1, 6) return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, \PhpSpreadsheet\Cell::columnIndexFromString($firstCellCoordinates[0]) - 1, \PhpSpreadsheet\Cell::columnIndexFromString($lastCellCoordinates[0]) - 1); } @@ -561,8 +559,9 @@ class Worksheet extends BIFFwriter // Return data stored in memory if (isset($this->_data)) { - $tmp = $this->_data; + $tmp = $this->_data; unset($this->_data); + return $tmp; } // No data to return @@ -572,8 +571,7 @@ class Worksheet extends BIFFwriter /** * Set the option to print the row and column headers on the printed page. * - * @access public - * @param integer $print Whether to print the headers or not. Defaults to 1 (print). + * @param int $print Whether to print the headers or not. Defaults to 1 (print). */ public function printRowColHeaders($print = 1) { @@ -591,7 +589,7 @@ class Worksheet extends BIFFwriter */ public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false) { - $this->outlineOn = $visible; + $this->outlineOn = $visible; $this->outlineBelow = $symbols_below; $this->outlineRight = $symbols_right; $this->outlineStyle = $auto_style; @@ -610,26 +608,27 @@ class Worksheet extends BIFFwriter * Returns 0 : normal termination * -2 : row or column out of range * - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column + * @param int $row Zero indexed row + * @param int $col Zero indexed column * @param float $num The number to write * @param mixed $xfIndex The optional XF format - * @return integer + * @return int */ private function writeNumber($row, $col, $num, $xfIndex) { - $record = 0x0203; // Record identifier - $length = 0x000E; // Number of bytes to follow + $record = 0x0203; // Record identifier + $length = 0x000E; // Number of bytes to follow - $header = pack("vv", $record, $length); - $data = pack("vvv", $row, $col, $xfIndex); - $xl_double = pack("d", $num); + $header = pack('vv', $record, $length); + $data = pack('vvv', $row, $col, $xfIndex); + $xl_double = pack('d', $num); if (self::getByteOrder()) { // if it's Big Endian $xl_double = strrev($xl_double); } - $this->append($header.$data.$xl_double); - return(0); + $this->append($header . $data . $xl_double); + + return 0; } /** @@ -656,19 +655,19 @@ class Worksheet extends BIFFwriter */ private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun) { - $record = 0x00FD; // Record identifier - $length = 0x000A; // Bytes to follow + $record = 0x00FD; // Record identifier + $length = 0x000A; // Bytes to follow $str = \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeShort($str, $arrcRun); /* check if string is already present */ if (!isset($this->stringTable[$str])) { $this->stringTable[$str] = $this->stringUnique++; } - $this->stringTotal++; + ++$this->stringTotal; - $header = pack('vv', $record, $length); - $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); - $this->append($header.$data); + $header = pack('vv', $record, $length); + $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); + $this->append($header . $data); } /** @@ -679,32 +678,32 @@ class Worksheet extends BIFFwriter * -2 : row or column out of range * -3 : long string truncated to 255 chars * - * @access public - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column + * @param int $row Zero indexed row + * @param int $col Zero indexed column * @param string $str The string to write * @param mixed $xfIndex The XF format index for the cell - * @return integer + * @return int */ private function writeLabel($row, $col, $str, $xfIndex) { - $strlen = strlen($str); - $record = 0x0204; // Record identifier - $length = 0x0008 + $strlen; // Bytes to follow + $strlen = strlen($str); + $record = 0x0204; // Record identifier + $length = 0x0008 + $strlen; // Bytes to follow $str_error = 0; if ($strlen > $this->xlsStringMaxLength) { // LABEL must be < 255 chars - $str = substr($str, 0, $this->xlsStringMaxLength); - $length = 0x0008 + $this->xlsStringMaxLength; - $strlen = $this->xlsStringMaxLength; + $str = substr($str, 0, $this->xlsStringMaxLength); + $length = 0x0008 + $this->xlsStringMaxLength; + $strlen = $this->xlsStringMaxLength; $str_error = -3; } - $header = pack("vv", $record, $length); - $data = pack("vvvv", $row, $col, $xfIndex, $strlen); + $header = pack('vv', $record, $length); + $data = pack('vvvv', $row, $col, $xfIndex, $strlen); $this->append($header . $data . $str); - return($str_error); + + return $str_error; } /** @@ -715,17 +714,16 @@ class Worksheet extends BIFFwriter * -2 : row or column out of range * -3 : long string truncated to 255 chars * - * @access public - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column + * @param int $row Zero indexed row + * @param int $col Zero indexed column * @param string $str The string to write * @param mixed $xfIndex The XF format index for the cell - * @return integer + * @return int */ private function writeLabelSst($row, $col, $str, $xfIndex) { - $record = 0x00FD; // Record identifier - $length = 0x000A; // Bytes to follow + $record = 0x00FD; // Record identifier + $length = 0x000A; // Bytes to follow $str = \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeLong($str); @@ -733,41 +731,42 @@ class Worksheet extends BIFFwriter if (!isset($this->stringTable[$str])) { $this->stringTable[$str] = $this->stringUnique++; } - $this->stringTotal++; + ++$this->stringTotal; - $header = pack('vv', $record, $length); - $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); - $this->append($header.$data); + $header = pack('vv', $record, $length); + $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); + $this->append($header . $data); } /** * Writes a note associated with the cell given by the row and column. * NOTE records don't have a length limit. * - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column + * @param int $row Zero indexed row + * @param int $col Zero indexed column * @param string $note The note to write */ private function writeNote($row, $col, $note) { - $note_length = strlen($note); - $record = 0x001C; // Record identifier - $max_length = 2048; // Maximun length for a NOTE record + $note_length = strlen($note); + $record = 0x001C; // Record identifier + $max_length = 2048; // Maximun length for a NOTE record // Length for this record is no more than 2048 + 6 - $length = 0x0006 + min($note_length, 2048); - $header = pack("vv", $record, $length); - $data = pack("vvv", $row, $col, $note_length); + $length = 0x0006 + min($note_length, 2048); + $header = pack('vv', $record, $length); + $data = pack('vvv', $row, $col, $note_length); $this->append($header . $data . substr($note, 0, 2048)); for ($i = $max_length; $i < $note_length; $i += $max_length) { - $chunk = substr($note, $i, $max_length); + $chunk = substr($note, $i, $max_length); $length = 0x0006 + strlen($chunk); - $header = pack("vv", $record, $length); - $data = pack("vvv", -1, 0, strlen($chunk)); - $this->append($header.$data.$chunk); + $header = pack('vv', $record, $length); + $data = pack('vvv', -1, 0, strlen($chunk)); + $this->append($header . $data . $chunk); } - return(0); + + return 0; } /** @@ -782,18 +781,19 @@ class Worksheet extends BIFFwriter * -1 : insufficient number of arguments * -2 : row or column out of range * - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column + * @param int $row Zero indexed row + * @param int $col Zero indexed column * @param mixed $xfIndex The XF format index */ public function writeBlank($row, $col, $xfIndex) { - $record = 0x0201; // Record identifier - $length = 0x0006; // Number of bytes to follow + $record = 0x0201; // Record identifier + $length = 0x0006; // Number of bytes to follow - $header = pack("vv", $record, $length); - $data = pack("vvv", $row, $col, $xfIndex); + $header = pack('vv', $record, $length); + $data = pack('vvv', $row, $col, $xfIndex); $this->append($header . $data); + return 0; } @@ -803,7 +803,7 @@ class Worksheet extends BIFFwriter * @param int $row Row index (0-based) * @param int $col Column index (0-based) * @param int $value - * @param boolean $isError Error or Boolean? + * @param bool $isError Error or Boolean? * @param int $xfIndex */ private function writeBoolErr($row, $col, $value, $isError, $xfIndex) @@ -811,9 +811,10 @@ class Worksheet extends BIFFwriter $record = 0x0205; $length = 8; - $header = pack("vv", $record, $length); - $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError); + $header = pack('vv', $record, $length); + $data = pack('vvvCC', $row, $col, $xfIndex, $value, $isError); $this->append($header . $data); + return 0; } @@ -826,16 +827,16 @@ class Worksheet extends BIFFwriter * -1 : formula errors (bad formula) * -2 : row or column out of range * - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column + * @param int $row Zero indexed row + * @param int $col Zero indexed column * @param string $formula The formula text string * @param mixed $xfIndex The XF format index * @param mixed $calculatedValue Calculated value - * @return integer + * @return int */ private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) { - $record = 0x0006; // Record identifier + $record = 0x0006; // Record identifier // Initialize possible additional value for STRING record that should be written after the FORMULA record? $stringValue = null; @@ -846,7 +847,7 @@ class Worksheet extends BIFFwriter // we use best effort to determine data type if (is_bool($calculatedValue)) { // Boolean value - $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF); + $num = pack('CCCvCv', 0x01, 0x00, (int) $calculatedValue, 0x00, 0x00, 0xFFFF); } elseif (is_int($calculatedValue) || is_float($calculatedValue)) { // Numeric value $num = pack('d', $calculatedValue); @@ -870,8 +871,8 @@ class Worksheet extends BIFFwriter $num = pack('d', 0x00); } - $grbit = 0x03; // Option flags - $unknown = 0x0000; // Must be zero + $grbit = 0x03; // Option flags + $unknown = 0x0000; // Must be zero // Strip the '=' or '@' sign at the beginning of the formula string if ($formula{0} == '=') { @@ -879,6 +880,7 @@ class Worksheet extends BIFFwriter } else { // Error handling $this->writeString($row, $col, 'Unrecognised character for formula'); + return -1; } @@ -887,20 +889,21 @@ class Worksheet extends BIFFwriter $error = $this->parser->parse($formula); $formula = $this->parser->toReversePolish(); - $formlen = strlen($formula); // Length of the binary string - $length = 0x16 + $formlen; // Length of the record data + $formlen = strlen($formula); // Length of the binary string + $length = 0x16 + $formlen; // Length of the record data - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); - $data = pack("vvv", $row, $col, $xfIndex) + $data = pack('vvv', $row, $col, $xfIndex) . $num - . pack("vVv", $grbit, $unknown, $formlen); + . pack('vVv', $grbit, $unknown, $formlen); $this->append($header . $data . $formula); // Append also a STRING record if necessary if ($stringValue !== null) { $this->writeStringRecord($stringValue); } + return 0; } catch (\PhpSpreadsheet\Exception $e) { // do nothing @@ -938,15 +941,15 @@ class Worksheet extends BIFFwriter * -2 : row or column out of range * -3 : long string truncated to 255 chars * - * @param integer $row Row - * @param integer $col Column + * @param int $row Row + * @param int $col Column * @param string $url URL string - * @return integer + * @return int */ private function writeUrl($row, $col, $url) { // Add start row and col to arg list - return($this->writeUrlRange($row, $col, $row, $col, $url)); + return $this->writeUrlRange($row, $col, $row, $col, $url); } /** @@ -955,25 +958,25 @@ class Worksheet extends BIFFwriter * to be written. These are either, Web (http, ftp, mailto), Internal * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1'). * - * @access private * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column + * @param int $row1 Start row + * @param int $col1 Start column + * @param int $row2 End row + * @param int $col2 End column * @param string $url URL string - * @return integer + * @return int */ public function writeUrlRange($row1, $col1, $row2, $col2, $url) { // Check for internal/external sheet links or default to web link if (preg_match('[^internal:]', $url)) { - return($this->writeUrlInternal($row1, $col1, $row2, $col2, $url)); + return $this->writeUrlInternal($row1, $col1, $row2, $col2, $url); } if (preg_match('[^external:]', $url)) { - return($this->writeUrlExternal($row1, $col1, $row2, $col2, $url)); + return $this->writeUrlExternal($row1, $col1, $row2, $col2, $url); } - return($this->writeUrlWeb($row1, $col1, $row2, $col2, $url)); + + return $this->writeUrlWeb($row1, $col1, $row2, $col2, $url); } /** @@ -981,73 +984,72 @@ class Worksheet extends BIFFwriter * The link type ($options) is 0x03 is the same as absolute dir ref without * sheet. However it is differentiated by the $unknown2 data stream. * - * @access private * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column + * @param int $row1 Start row + * @param int $col1 Start column + * @param int $row2 End row + * @param int $col2 End column * @param string $url URL string - * @return integer + * @return int */ public function writeUrlWeb($row1, $col1, $row2, $col2, $url) { - $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow // Pack the undocumented parts of the hyperlink stream - $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); - $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B"); + $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); + $unknown2 = pack('H*', 'E0C9EA79F9BACE118C8200AA004BA90B'); // Pack the option flags - $options = pack("V", 0x03); + $options = pack('V', 0x03); // Convert URL to a null terminated wchar string - $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); - $url = $url . "\0\0\0"; + $url = implode("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); + $url = $url . "\0\0\0"; // Pack the length of the URL - $url_len = pack("V", strlen($url)); + $url_len = pack('V', strlen($url)); // Calculate the data length - $length = 0x34 + strlen($url); + $length = 0x34 + strlen($url); // Pack the header data - $header = pack("vv", $record, $length); - $data = pack("vvvv", $row1, $row2, $col1, $col2); + $header = pack('vv', $record, $length); + $data = pack('vvvv', $row1, $row2, $col1, $col2); // Write the packed data $this->append($header . $data . $unknown1 . $options . $unknown2 . $url_len . $url); + return 0; } /** * Used to write internal reference hyperlinks such as "Sheet1!A1". * - * @access private * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column + * @param int $row1 Start row + * @param int $col1 Start column + * @param int $row2 End row + * @param int $col2 End column * @param string $url URL string - * @return integer + * @return int */ public function writeUrlInternal($row1, $col1, $row2, $col2, $url) { - $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow // Strip URL type $url = preg_replace('/^internal:/', '', $url); // Pack the undocumented parts of the hyperlink stream - $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); + $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); // Pack the option flags - $options = pack("V", 0x08); + $options = pack('V', 0x08); // Convert the URL type and to a null terminated wchar string $url .= "\0"; @@ -1059,16 +1061,17 @@ class Worksheet extends BIFFwriter $url = \PhpSpreadsheet\Shared\StringHelper::convertEncoding($url, 'UTF-16LE', 'UTF-8'); // Calculate the data length - $length = 0x24 + strlen($url); + $length = 0x24 + strlen($url); // Pack the header data - $header = pack("vv", $record, $length); - $data = pack("vvvv", $row1, $row2, $col1, $col2); + $header = pack('vv', $record, $length); + $data = pack('vvvv', $row1, $row2, $col1, $col2); // Write the packed data $this->append($header . $data . $unknown1 . $options . $url_len . $url); + return 0; } @@ -1079,14 +1082,13 @@ class Worksheet extends BIFFwriter * Note: Excel writes some relative links with the $dir_long string. We ignore * these cases for the sake of simpler code. * - * @access private * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column + * @param int $row1 Start row + * @param int $col1 Start column + * @param int $row2 End row + * @param int $col2 End column * @param string $url URL string - * @return integer + * @return int */ public function writeUrlExternal($row1, $col1, $row2, $col2, $url) { @@ -1096,13 +1098,13 @@ class Worksheet extends BIFFwriter return; //($this->writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format)); } - $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow // Strip URL type and change Unix dir separator to Dos style (if needed) // $url = preg_replace('/^external:/', '', $url); - $url = preg_replace('/\//', "\\", $url); + $url = preg_replace('/\//', '\\', $url); // Determine if the link is relative or absolute: // relative if link contains no dir separator, "somefile.xls" @@ -1113,7 +1115,7 @@ class Worksheet extends BIFFwriter if (preg_match('/^[A-Z]:/', $url)) { $absolute = 0x02; // absolute path on Windows, e.g. C:\... } - $link_type = 0x01 | $absolute; + $link_type = 0x01 | $absolute; // Determine if the link contains a sheet reference and change some of the // parameters accordingly. @@ -1123,41 +1125,40 @@ class Worksheet extends BIFFwriter $link_type |= 0x08; } - // Pack the link type - $link_type = pack("V", $link_type); + $link_type = pack('V', $link_type); // Calculate the up-level dir count e.g.. (..\..\..\ == 3) - $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless); - $up_count = pack("v", $up_count); + $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless); + $up_count = pack('v', $up_count); // Store the short dos dir name (null terminated) - $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0"; + $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0"; // Store the long dir name as a wchar string (non-null terminated) - $dir_long = $dir_long . "\0"; + $dir_long = $dir_long . "\0"; // Pack the lengths of the dir strings - $dir_short_len = pack("V", strlen($dir_short)); - $dir_long_len = pack("V", strlen($dir_long)); - $stream_len = pack("V", 0); //strlen($dir_long) + 0x06); + $dir_short_len = pack('V', strlen($dir_short)); + $dir_long_len = pack('V', strlen($dir_long)); + $stream_len = pack('V', 0); //strlen($dir_long) + 0x06); // Pack the undocumented parts of the hyperlink stream - $unknown1 = pack("H*", 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); - $unknown2 = pack("H*", '0303000000000000C000000000000046'); - $unknown3 = pack("H*", 'FFFFADDE000000000000000000000000000000000000000'); - $unknown4 = pack("v", 0x03); + $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); + $unknown2 = pack('H*', '0303000000000000C000000000000046'); + $unknown3 = pack('H*', 'FFFFADDE000000000000000000000000000000000000000'); + $unknown4 = pack('v', 0x03); // Pack the main data stream - $data = pack("vvvv", $row1, $row2, $col1, $col2) . - $unknown1 . - $link_type . - $unknown2 . - $up_count . - $dir_short_len. - $dir_short . - $unknown3 . - $stream_len ;/*. + $data = pack('vvvv', $row1, $row2, $col1, $col2) . + $unknown1 . + $link_type . + $unknown2 . + $up_count . + $dir_short_len . + $dir_short . + $unknown3 . + $stream_len;/*. $dir_long_len . $unknown4 . $dir_long . @@ -1165,35 +1166,36 @@ class Worksheet extends BIFFwriter $sheet ;*/ // Pack the header data - $length = strlen($data); - $header = pack("vv", $record, $length); + $length = strlen($data); + $header = pack('vv', $record, $length); // Write the packed data - $this->append($header. $data); + $this->append($header . $data); + return 0; } /** * This method is used to set the height and format for a row. * - * @param integer $row The row to set - * @param integer $height Height we are giving to the row. + * @param int $row The row to set + * @param int $height Height we are giving to the row. * Use null to set XF without setting height - * @param integer $xfIndex The optional cell style Xf index to apply to the columns + * @param int $xfIndex The optional cell style Xf index to apply to the columns * @param bool $hidden The optional hidden attribute - * @param integer $level The optional outline level for row, in range [0,7] + * @param int $level The optional outline level for row, in range [0,7] */ private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0) { - $record = 0x0208; // Record identifier - $length = 0x0010; // Number of bytes to follow + $record = 0x0208; // Record identifier + $length = 0x0010; // Number of bytes to follow - $colMic = 0x0000; // First defined column - $colMac = 0x0000; // Last defined column - $irwMac = 0x0000; // Used by Excel to optimise loading - $reserved = 0x0000; // Reserved - $grbit = 0x0000; // Option flags - $ixfe = $xfIndex; + $colMic = 0x0000; // First defined column + $colMac = 0x0000; // Last defined column + $irwMac = 0x0000; // Used by Excel to optimise loading + $reserved = 0x0000; // Reserved + $grbit = 0x0000; // Option flags + $ixfe = $xfIndex; if ($height < 0) { $height = null; @@ -1224,9 +1226,9 @@ class Worksheet extends BIFFwriter } $grbit |= 0x0100; - $header = pack("vv", $record, $length); - $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe); - $this->append($header.$data); + $header = pack('vv', $record, $length); + $data = pack('vvvvvvvv', $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe); + $this->append($header . $data); } /** @@ -1239,8 +1241,8 @@ class Worksheet extends BIFFwriter $length = 0x000E; $data = pack('VVvvv', $this->firstRowIndex, $this->lastRowIndex + 1, $this->firstColumnIndex, $this->lastColumnIndex + 1, 0x0000); // reserved - $header = pack("vv", $record, $length); - $this->append($header.$data); + $header = pack('vv', $record, $length); + $this->append($header . $data); } /** @@ -1248,53 +1250,52 @@ class Worksheet extends BIFFwriter */ private function writeWindow2() { - $record = 0x023E; // Record identifier - $length = 0x0012; - - $grbit = 0x00B6; // Option flags - $rwTop = 0x0000; // Top row visible in window - $colLeft = 0x0000; // Leftmost column visible in window + $record = 0x023E; // Record identifier + $length = 0x0012; + $grbit = 0x00B6; // Option flags + $rwTop = 0x0000; // Top row visible in window + $colLeft = 0x0000; // Leftmost column visible in window // The options flags that comprise $grbit - $fDspFmla = 0; // 0 - bit - $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1 - $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2 - $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3 - $fDspZeros = 1; // 4 - $fDefaultHdr = 1; // 5 - $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6 - $fDspGuts = $this->outlineOn; // 7 + $fDspFmla = 0; // 0 - bit + $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1 + $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2 + $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3 + $fDspZeros = 1; // 4 + $fDefaultHdr = 1; // 5 + $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6 + $fDspGuts = $this->outlineOn; // 7 $fFrozenNoSplit = 0; // 0 - bit // no support in PhpSpreadsheet for selected sheet, therefore sheet is only selected if it is the active sheet - $fSelected = ($this->phpSheet === $this->phpSheet->getParent()->getActiveSheet()) ? 1 : 0; - $fPaged = 1; // 2 + $fSelected = ($this->phpSheet === $this->phpSheet->getParent()->getActiveSheet()) ? 1 : 0; + $fPaged = 1; // 2 $fPageBreakPreview = $this->phpSheet->getSheetView()->getView() === \PhpSpreadsheet\Worksheet\SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW; - $grbit = $fDspFmla; - $grbit |= $fDspGrid << 1; - $grbit |= $fDspRwCol << 2; - $grbit |= $fFrozen << 3; - $grbit |= $fDspZeros << 4; - $grbit |= $fDefaultHdr << 5; - $grbit |= $fArabic << 6; - $grbit |= $fDspGuts << 7; - $grbit |= $fFrozenNoSplit << 8; - $grbit |= $fSelected << 9; - $grbit |= $fPaged << 10; - $grbit |= $fPageBreakPreview << 11; + $grbit = $fDspFmla; + $grbit |= $fDspGrid << 1; + $grbit |= $fDspRwCol << 2; + $grbit |= $fFrozen << 3; + $grbit |= $fDspZeros << 4; + $grbit |= $fDefaultHdr << 5; + $grbit |= $fArabic << 6; + $grbit |= $fDspGuts << 7; + $grbit |= $fFrozenNoSplit << 8; + $grbit |= $fSelected << 9; + $grbit |= $fPaged << 10; + $grbit |= $fPageBreakPreview << 11; - $header = pack("vv", $record, $length); - $data = pack("vvv", $grbit, $rwTop, $colLeft); + $header = pack('vv', $record, $length); + $data = pack('vvv', $grbit, $rwTop, $colLeft); // FIXME !!! - $rgbHdr = 0x0040; // Row/column heading and gridline color index + $rgbHdr = 0x0040; // Row/column heading and gridline color index $zoom_factor_page_break = ($fPageBreakPreview ? $this->phpSheet->getSheetView()->getZoomScale() : 0x0000); - $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal(); + $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal(); - $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000); + $data .= pack('vvvvV', $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000); - $this->append($header.$data); + $this->append($header . $data); } /** @@ -1311,11 +1312,11 @@ class Worksheet extends BIFFwriter // convert to twips $defaultRowHeight = (int) 20 * $defaultRowHeight; - $record = 0x0225; // Record identifier - $length = 0x0004; // Number of bytes to follow + $record = 0x0225; // Record identifier + $length = 0x0004; // Number of bytes to follow - $header = pack("vv", $record, $length); - $data = pack("vv", 1, $defaultRowHeight); + $header = pack('vv', $record, $length); + $data = pack('vv', 1, $defaultRowHeight); $this->append($header . $data); } @@ -1326,11 +1327,11 @@ class Worksheet extends BIFFwriter { $defaultColWidth = 8; - $record = 0x0055; // Record identifier - $length = 0x0002; // Number of bytes to follow + $record = 0x0055; // Record identifier + $length = 0x0002; // Number of bytes to follow - $header = pack("vv", $record, $length); - $data = pack("v", $defaultColWidth); + $header = pack('vv', $record, $length); + $data = pack('v', $defaultColWidth); $this->append($header . $data); } @@ -1376,20 +1377,20 @@ class Worksheet extends BIFFwriter } else { $level = 0; } - $record = 0x007D; // Record identifier - $length = 0x000C; // Number of bytes to follow + $record = 0x007D; // Record identifier + $length = 0x000C; // Number of bytes to follow - $coldx *= 256; // Convert to units of 1/256 of a char + $coldx *= 256; // Convert to units of 1/256 of a char - $ixfe = $xfIndex; + $ixfe = $xfIndex; $reserved = 0x0000; // Reserved $level = max(0, min($level, 7)); $grbit |= $level << 8; - $header = pack("vv", $record, $length); - $data = pack("vvvvvv", $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved); - $this->append($header.$data); + $header = pack('vv', $record, $length); + $data = pack('vvvvvv', $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved); + $this->append($header . $data); } /** @@ -1405,7 +1406,7 @@ class Worksheet extends BIFFwriter list($first, $last) = $selectedCells; } else { $first = $selectedCells[0]; - $last = $selectedCells[0]; + $last = $selectedCells[0]; } list($colFirst, $rwFirst) = \PhpSpreadsheet\Cell::coordinateFromString($first); @@ -1418,38 +1419,38 @@ class Worksheet extends BIFFwriter // make sure we are not out of bounds $colFirst = min($colFirst, 255); - $colLast = min($colLast, 255); + $colLast = min($colLast, 255); $rwFirst = min($rwFirst, 65535); - $rwLast = min($rwLast, 65535); + $rwLast = min($rwLast, 65535); - $record = 0x001D; // Record identifier - $length = 0x000F; // Number of bytes to follow + $record = 0x001D; // Record identifier + $length = 0x000F; // Number of bytes to follow - $pnn = $this->activePane; // Pane position - $rwAct = $rwFirst; // Active row - $colAct = $colFirst; // Active column - $irefAct = 0; // Active cell ref - $cref = 1; // Number of refs + $pnn = $this->activePane; // Pane position + $rwAct = $rwFirst; // Active row + $colAct = $colFirst; // Active column + $irefAct = 0; // Active cell ref + $cref = 1; // Number of refs if (!isset($rwLast)) { - $rwLast = $rwFirst; // Last row in reference + $rwLast = $rwFirst; // Last row in reference } if (!isset($colLast)) { - $colLast = $colFirst; // Last col in reference + $colLast = $colFirst; // Last col in reference } // Swap last row/col for first row/col as necessary if ($rwFirst > $rwLast) { - list($rwFirst, $rwLast) = array($rwLast, $rwFirst); + list($rwFirst, $rwLast) = [$rwLast, $rwFirst]; } if ($colFirst > $colLast) { - list($colFirst, $colLast) = array($colLast, $colFirst); + list($colFirst, $colLast) = [$colLast, $colFirst]; } - $header = pack("vv", $record, $length); - $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast); + $header = pack('vv', $record, $length); + $data = pack('CvvvvvvCC', $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast); $this->append($header . $data); } @@ -1543,21 +1544,21 @@ class Worksheet extends BIFFwriter $record = 0x0867; // prepare options - $options = (int) !$this->phpSheet->getProtection()->getObjects() - | (int) !$this->phpSheet->getProtection()->getScenarios() << 1 - | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2 - | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3 - | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4 - | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5 - | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6 - | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7 - | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8 - | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9 - | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10 - | (int) !$this->phpSheet->getProtection()->getSort() << 11 - | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12 - | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13 - | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14 ; + $options = (int) !$this->phpSheet->getProtection()->getObjects() + | (int) !$this->phpSheet->getProtection()->getScenarios() << 1 + | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2 + | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3 + | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4 + | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5 + | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6 + | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7 + | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8 + | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9 + | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10 + | (int) !$this->phpSheet->getProtection()->getSort() << 11 + | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12 + | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13 + | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14; // record data $recordData = pack( @@ -1621,7 +1622,7 @@ class Worksheet extends BIFFwriter $length = strlen($recordData); $record = 0x0868; // Record identifier - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); $this->append($header . $recordData); } } @@ -1636,15 +1637,15 @@ class Worksheet extends BIFFwriter * complexity and eliminates the need for a two way dialogue between the formula * parser the worksheet objects. * - * @param integer $count The number of external sheet references in this worksheet + * @param int $count The number of external sheet references in this worksheet */ private function writeExterncount($count) { $record = 0x0016; // Record identifier $length = 0x0002; // Number of bytes to follow - $header = pack("vv", $record, $length); - $data = pack("v", $count); + $header = pack('vv', $record, $length); + $data = pack('v', $count); $this->append($header . $data); } @@ -1658,24 +1659,24 @@ class Worksheet extends BIFFwriter */ private function writeExternsheet($sheetname) { - $record = 0x0017; // Record identifier + $record = 0x0017; // Record identifier // References to the current sheet are encoded differently to references to // external sheets. // if ($this->phpSheet->getTitle() == $sheetname) { $sheetname = ''; - $length = 0x02; // The following 2 bytes - $cch = 1; // The following byte - $rgch = 0x02; // Self reference + $length = 0x02; // The following 2 bytes + $cch = 1; // The following byte + $rgch = 0x02; // Self reference } else { - $length = 0x02 + strlen($sheetname); - $cch = strlen($sheetname); - $rgch = 0x03; // Reference to a sheet in the current workbook + $length = 0x02 + strlen($sheetname); + $cch = strlen($sheetname); + $rgch = 0x03; // Reference to a sheet in the current workbook } - $header = pack("vv", $record, $length); - $data = pack("CC", $cch, $rgch); + $header = pack('vv', $record, $length); + $data = pack('CC', $cch, $rgch); $this->append($header . $data . $sheetname); } @@ -1687,7 +1688,7 @@ class Worksheet extends BIFFwriter */ private function writePanes() { - $panes = array(); + $panes = []; if ($freezePane = $this->phpSheet->getFreezePane()) { list($column, $row) = \PhpSpreadsheet\Cell::coordinateFromString($freezePane); $panes[0] = $row - 1; @@ -1697,23 +1698,23 @@ class Worksheet extends BIFFwriter return; } - $y = isset($panes[0]) ? $panes[0] : null; - $x = isset($panes[1]) ? $panes[1] : null; - $rwTop = isset($panes[2]) ? $panes[2] : null; + $y = isset($panes[0]) ? $panes[0] : null; + $x = isset($panes[1]) ? $panes[1] : null; + $rwTop = isset($panes[2]) ? $panes[2] : null; $colLeft = isset($panes[3]) ? $panes[3] : null; if (count($panes) > 4) { // if Active pane was received $pnnAct = $panes[4]; } else { $pnnAct = null; } - $record = 0x0041; // Record identifier - $length = 0x000A; // Number of bytes to follow + $record = 0x0041; // Record identifier + $length = 0x000A; // Number of bytes to follow // Code specific to frozen or thawed panes. if ($this->phpSheet->getFreezePane()) { // Set default values for $rwTop and $colLeft if (!isset($rwTop)) { - $rwTop = $y; + $rwTop = $y; } if (!isset($colLeft)) { $colLeft = $x; @@ -1721,7 +1722,7 @@ class Worksheet extends BIFFwriter } else { // Set default values for $rwTop and $colLeft if (!isset($rwTop)) { - $rwTop = 0; + $rwTop = 0; } if (!isset($colLeft)) { $colLeft = 0; @@ -1732,11 +1733,10 @@ class Worksheet extends BIFFwriter // The default column width is 8.43 // The following slope and intersection values were interpolated. // - $y = 20*$y + 255; - $x = 113.879*$x + 390; + $y = 20 * $y + 255; + $x = 113.879 * $x + 390; } - // Determine which pane should be active. There is also the undocumented // option to override this should it be necessary: may be removed later. // @@ -1757,8 +1757,8 @@ class Worksheet extends BIFFwriter $this->activePane = $pnnAct; // Used in writeSelection - $header = pack("vv", $record, $length); - $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct); + $header = pack('vv', $record, $length); + $data = pack('vvvvv', $x, $y, $rwTop, $colLeft, $pnnAct); $this->append($header . $data); } @@ -1767,25 +1767,25 @@ class Worksheet extends BIFFwriter */ private function writeSetup() { - $record = 0x00A1; // Record identifier - $length = 0x0022; // Number of bytes to follow + $record = 0x00A1; // Record identifier + $length = 0x0022; // Number of bytes to follow - $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size + $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size $iScale = $this->phpSheet->getPageSetup()->getScale() ? $this->phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor - $iPageStart = 0x01; // Starting page number - $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide - $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high - $grbit = 0x00; // Option flags - $iRes = 0x0258; // Print resolution - $iVRes = 0x0258; // Vertical print resolution + $iPageStart = 0x01; // Starting page number + $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide + $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high + $grbit = 0x00; // Option flags + $iRes = 0x0258; // Print resolution + $iVRes = 0x0258; // Vertical print resolution - $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin + $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin - $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin - $iCopies = 0x01; // Number of copies + $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin + $iCopies = 0x01; // Number of copies $fLeftToRight = 0x0; // Print over then down @@ -1793,33 +1793,33 @@ class Worksheet extends BIFFwriter $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == \PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE) ? 0x0 : 0x1; - $fNoPls = 0x0; // Setup not read from printer - $fNoColor = 0x0; // Print black and white - $fDraft = 0x0; // Print draft quality - $fNotes = 0x0; // Print notes - $fNoOrient = 0x0; // Orientation not set - $fUsePage = 0x0; // Use custom starting page + $fNoPls = 0x0; // Setup not read from printer + $fNoColor = 0x0; // Print black and white + $fDraft = 0x0; // Print draft quality + $fNotes = 0x0; // Print notes + $fNoOrient = 0x0; // Orientation not set + $fUsePage = 0x0; // Use custom starting page - $grbit = $fLeftToRight; - $grbit |= $fLandscape << 1; - $grbit |= $fNoPls << 2; - $grbit |= $fNoColor << 3; - $grbit |= $fDraft << 4; - $grbit |= $fNotes << 5; - $grbit |= $fNoOrient << 6; - $grbit |= $fUsePage << 7; + $grbit = $fLeftToRight; + $grbit |= $fLandscape << 1; + $grbit |= $fNoPls << 2; + $grbit |= $fNoColor << 3; + $grbit |= $fDraft << 4; + $grbit |= $fNotes << 5; + $grbit |= $fNoOrient << 6; + $grbit |= $fUsePage << 7; - $numHdr = pack("d", $numHdr); - $numFtr = pack("d", $numFtr); + $numHdr = pack('d', $numHdr); + $numFtr = pack('d', $numFtr); if (self::getByteOrder()) { // if it's Big Endian $numHdr = strrev($numHdr); $numFtr = strrev($numFtr); } - $header = pack("vv", $record, $length); - $data1 = pack("vvvvvvvv", $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes); - $data2 = $numHdr.$numFtr; - $data3 = pack("v", $iCopies); + $header = pack('vv', $record, $length); + $data1 = pack('vvvvvvvv', $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes); + $data2 = $numHdr . $numFtr; + $data3 = pack('v', $iCopies); $this->append($header . $data1 . $data2 . $data3); } @@ -1828,7 +1828,7 @@ class Worksheet extends BIFFwriter */ private function writeHeader() { - $record = 0x0014; // Record identifier + $record = 0x0014; // Record identifier /* removing for now // need to fix character count (multibyte!) @@ -1842,7 +1842,7 @@ class Worksheet extends BIFFwriter $recordData = \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddHeader()); $length = strlen($recordData); - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); $this->append($header . $recordData); } @@ -1852,7 +1852,7 @@ class Worksheet extends BIFFwriter */ private function writeFooter() { - $record = 0x0015; // Record identifier + $record = 0x0015; // Record identifier /* removing for now // need to fix character count (multibyte!) @@ -1866,27 +1866,25 @@ class Worksheet extends BIFFwriter $recordData = \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddFooter()); $length = strlen($recordData); - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); $this->append($header . $recordData); } /** * Store the horizontal centering HCENTER BIFF record. - * - * @access private */ private function writeHcenter() { - $record = 0x0083; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x0083; // Record identifier + $length = 0x0002; // Bytes to follow $fHCenter = $this->phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering - $header = pack("vv", $record, $length); - $data = pack("v", $fHCenter); + $header = pack('vv', $record, $length); + $data = pack('v', $fHCenter); - $this->append($header.$data); + $this->append($header . $data); } /** @@ -1894,13 +1892,13 @@ class Worksheet extends BIFFwriter */ private function writeVcenter() { - $record = 0x0084; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x0084; // Record identifier + $length = 0x0002; // Bytes to follow $fVCenter = $this->phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering - $header = pack("vv", $record, $length); - $data = pack("v", $fVCenter); + $header = pack('vv', $record, $length); + $data = pack('v', $fVCenter); $this->append($header . $data); } @@ -1909,13 +1907,13 @@ class Worksheet extends BIFFwriter */ private function writeMarginLeft() { - $record = 0x0026; // Record identifier - $length = 0x0008; // Bytes to follow + $record = 0x0026; // Record identifier + $length = 0x0008; // Bytes to follow - $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches + $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches - $header = pack("vv", $record, $length); - $data = pack("d", $margin); + $header = pack('vv', $record, $length); + $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } @@ -1928,13 +1926,13 @@ class Worksheet extends BIFFwriter */ private function writeMarginRight() { - $record = 0x0027; // Record identifier - $length = 0x0008; // Bytes to follow + $record = 0x0027; // Record identifier + $length = 0x0008; // Bytes to follow - $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches + $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches - $header = pack("vv", $record, $length); - $data = pack("d", $margin); + $header = pack('vv', $record, $length); + $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } @@ -1947,13 +1945,13 @@ class Worksheet extends BIFFwriter */ private function writeMarginTop() { - $record = 0x0028; // Record identifier - $length = 0x0008; // Bytes to follow + $record = 0x0028; // Record identifier + $length = 0x0008; // Bytes to follow - $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches + $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches - $header = pack("vv", $record, $length); - $data = pack("d", $margin); + $header = pack('vv', $record, $length); + $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } @@ -1966,13 +1964,13 @@ class Worksheet extends BIFFwriter */ private function writeMarginBottom() { - $record = 0x0029; // Record identifier - $length = 0x0008; // Bytes to follow + $record = 0x0029; // Record identifier + $length = 0x0008; // Bytes to follow - $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches + $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches - $header = pack("vv", $record, $length); - $data = pack("d", $margin); + $header = pack('vv', $record, $length); + $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } @@ -1985,13 +1983,13 @@ class Worksheet extends BIFFwriter */ private function writePrintHeaders() { - $record = 0x002a; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x002a; // Record identifier + $length = 0x0002; // Bytes to follow $fPrintRwCol = $this->_print_headers; // Boolean flag - $header = pack("vv", $record, $length); - $data = pack("v", $fPrintRwCol); + $header = pack('vv', $record, $length); + $data = pack('v', $fPrintRwCol); $this->append($header . $data); } @@ -2001,13 +1999,13 @@ class Worksheet extends BIFFwriter */ private function writePrintGridlines() { - $record = 0x002b; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x002b; // Record identifier + $length = 0x0002; // Bytes to follow - $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag + $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag - $header = pack("vv", $record, $length); - $data = pack("v", $fPrintGrid); + $header = pack('vv', $record, $length); + $data = pack('v', $fPrintGrid); $this->append($header . $data); } @@ -2017,13 +2015,13 @@ class Worksheet extends BIFFwriter */ private function writeGridset() { - $record = 0x0082; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x0082; // Record identifier + $length = 0x0002; // Bytes to follow - $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag + $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag - $header = pack("vv", $record, $length); - $data = pack("v", $fGridSet); + $header = pack('vv', $record, $length); + $data = pack('v', $fGridSet); $this->append($header . $data); } @@ -2032,14 +2030,14 @@ class Worksheet extends BIFFwriter */ private function writeAutoFilterInfo() { - $record = 0x009D; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x009D; // Record identifier + $length = 0x0002; // Bytes to follow $rangeBounds = \PhpSpreadsheet\Cell::rangeBoundaries($this->phpSheet->getAutoFilter()->getRange()); $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0]; - $header = pack("vv", $record, $length); - $data = pack("v", $iNumFilters); + $header = pack('vv', $record, $length); + $data = pack('v', $iNumFilters); $this->append($header . $data); } @@ -2052,11 +2050,11 @@ class Worksheet extends BIFFwriter */ private function writeGuts() { - $record = 0x0080; // Record identifier - $length = 0x0008; // Bytes to follow + $record = 0x0080; // Record identifier + $length = 0x0008; // Bytes to follow - $dxRwGut = 0x0000; // Size of row gutter - $dxColGut = 0x0000; // Size of col gutter + $dxRwGut = 0x0000; // Size of row gutter + $dxColGut = 0x0000; // Size of col gutter // determine maximum row outline level $maxRowOutlineLevel = 0; @@ -2064,7 +2062,7 @@ class Worksheet extends BIFFwriter $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel()); } - $col_level = 0; + $col_level = 0; // Calculate the maximum column outline level. The equivalent calculation // for the row outline level is carried out in writeRow(). @@ -2084,10 +2082,10 @@ class Worksheet extends BIFFwriter ++$col_level; } - $header = pack("vv", $record, $length); - $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level); + $header = pack('vv', $record, $length); + $data = pack('vvvv', $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level); - $this->append($header.$data); + $this->append($header . $data); } /** @@ -2096,9 +2094,9 @@ class Worksheet extends BIFFwriter */ private function writeWsbool() { - $record = 0x0081; // Record identifier - $length = 0x0002; // Bytes to follow - $grbit = 0x0000; + $record = 0x0081; // Record identifier + $length = 0x0002; // Bytes to follow + $grbit = 0x0000; // The only option that is of interest is the flag for fit to page. So we // set all the options in one go. @@ -2121,8 +2119,8 @@ class Worksheet extends BIFFwriter $grbit |= 0x0400; // Outline symbols displayed } - $header = pack("vv", $record, $length); - $data = pack("v", $grbit); + $header = pack('vv', $record, $length); + $data = pack('v', $grbit); $this->append($header . $data); } @@ -2132,8 +2130,8 @@ class Worksheet extends BIFFwriter private function writeBreaks() { // initialize - $vbreaks = array(); - $hbreaks = array(); + $vbreaks = []; + $hbreaks = []; foreach ($this->phpSheet->getBreaks() as $cell => $breakType) { // Fetch coordinates @@ -2164,16 +2162,16 @@ class Worksheet extends BIFFwriter array_shift($hbreaks); } - $record = 0x001b; // Record identifier - $cbrk = count($hbreaks); // Number of page breaks - $length = 2 + 6 * $cbrk; // Bytes to follow + $record = 0x001b; // Record identifier + $cbrk = count($hbreaks); // Number of page breaks + $length = 2 + 6 * $cbrk; // Bytes to follow - $header = pack("vv", $record, $length); - $data = pack("v", $cbrk); + $header = pack('vv', $record, $length); + $data = pack('v', $cbrk); // Append each page break foreach ($hbreaks as $hbreak) { - $data .= pack("vvv", $hbreak, 0x0000, 0x00ff); + $data .= pack('vvv', $hbreak, 0x0000, 0x00ff); } $this->append($header . $data); @@ -2191,16 +2189,16 @@ class Worksheet extends BIFFwriter array_shift($vbreaks); } - $record = 0x001a; // Record identifier - $cbrk = count($vbreaks); // Number of page breaks - $length = 2 + 6 * $cbrk; // Bytes to follow + $record = 0x001a; // Record identifier + $cbrk = count($vbreaks); // Number of page breaks + $length = 2 + 6 * $cbrk; // Bytes to follow - $header = pack("vv", $record, $length); - $data = pack("v", $cbrk); + $header = pack('vv', $record, $length); + $data = pack('v', $cbrk); // Append each page break foreach ($vbreaks as $vbreak) { - $data .= pack("vvv", $vbreak, 0x0000, 0xffff); + $data .= pack('vvv', $vbreak, 0x0000, 0xffff); } $this->append($header . $data); @@ -2217,15 +2215,15 @@ class Worksheet extends BIFFwriter return; } - $record = 0x0012; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x0012; // Record identifier + $length = 0x0002; // Bytes to follow - $fLock = 1; // Worksheet is protected + $fLock = 1; // Worksheet is protected - $header = pack("vv", $record, $length); - $data = pack("v", $fLock); + $header = pack('vv', $record, $length); + $data = pack('v', $fLock); - $this->append($header.$data); + $this->append($header . $data); } /** @@ -2286,13 +2284,13 @@ class Worksheet extends BIFFwriter return; } - $record = 0x0013; // Record identifier - $length = 0x0002; // Bytes to follow + $record = 0x0013; // Record identifier + $length = 0x0002; // Bytes to follow - $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password + $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password - $header = pack("vv", $record, $length); - $data = pack("v", $wPassword); + $header = pack('vv', $record, $length); + $data = pack('v', $wPassword); $this->append($header . $data); } @@ -2300,12 +2298,11 @@ class Worksheet extends BIFFwriter /** * Insert a 24bit bitmap image in a worksheet. * - * @access public - * @param integer $row The row we are going to insert the bitmap into - * @param integer $col The column we are going to insert the bitmap into + * @param int $row The row we are going to insert the bitmap into + * @param int $col The column we are going to insert the bitmap into * @param mixed $bitmap The bitmap filename or GD-image resource - * @param integer $x The horizontal position (offset) of the image inside the cell. - * @param integer $y The vertical position (offset) of the image inside the cell. + * @param int $x The horizontal position (offset) of the image inside the cell. + * @param int $y The vertical position (offset) of the image inside the cell. * @param float $scale_x The horizontal scale * @param float $scale_y The vertical scale */ @@ -2315,21 +2312,21 @@ class Worksheet extends BIFFwriter list($width, $height, $size, $data) = $bitmap_array; //$this->processBitmap($bitmap); // Scale the frame of the image. - $width *= $scale_x; + $width *= $scale_x; $height *= $scale_y; // Calculate the vertices of the image and write the OBJ record $this->positionImage($col, $row, $x, $y, $width, $height); // Write the IMDATA record to store the bitmap data - $record = 0x007f; - $length = 8 + $size; - $cf = 0x09; - $env = 0x01; - $lcb = $size; + $record = 0x007f; + $length = 8 + $size; + $cf = 0x09; + $env = 0x01; + $lcb = $size; - $header = pack("vvvvV", $record, $length, $cf, $env, $lcb); - $this->append($header.$data); + $header = pack('vvvvV', $record, $length, $cf, $env, $lcb); + $this->append($header . $data); } /** @@ -2375,19 +2372,18 @@ class Worksheet extends BIFFwriter * The SDK incorrectly states that the height should be expressed as a * percentage of 1024. * - * @access private - * @param integer $col_start Col containing upper left corner of object - * @param integer $row_start Row containing top left corner of object - * @param integer $x1 Distance to left side of object - * @param integer $y1 Distance to top of object - * @param integer $width Width of image frame - * @param integer $height Height of image frame + * @param int $col_start Col containing upper left corner of object + * @param int $row_start Row containing top left corner of object + * @param int $x1 Distance to left side of object + * @param int $y1 Distance to top of object + * @param int $width Width of image frame + * @param int $height Height of image frame */ public function positionImage($col_start, $row_start, $x1, $y1, $width, $height) { // Initialise end cell to the same as the start cell - $col_end = $col_start; // Col containing lower right corner of object - $row_end = $row_start; // Row containing bottom 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 // Zero the specified offset if greater than the cell dimensions if ($x1 >= \PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start))) { @@ -2397,8 +2393,8 @@ class Worksheet extends BIFFwriter $y1 = 0; } - $width = $width + $x1 -1; - $height = $height + $y1 -1; + $width = $width + $x1 - 1; + $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image while ($width >= \PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end))) { @@ -2418,21 +2414,21 @@ class Worksheet extends BIFFwriter if (\PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) == 0) { return; } - if (\PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) == 0) { + if (\PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) == 0) { return; } if (\PhpSpreadsheet\Shared\Excel5::sizeRow($this->phpSheet, $row_start + 1) == 0) { return; } - if (\PhpSpreadsheet\Shared\Excel5::sizeRow($this->phpSheet, $row_end + 1) == 0) { + if (\PhpSpreadsheet\Shared\Excel5::sizeRow($this->phpSheet, $row_end + 1) == 0) { return; } // Convert the pixel values to the percentage value expected by Excel - $x1 = $x1 / \PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) * 1024; - $y1 = $y1 / \PhpSpreadsheet\Shared\Excel5::sizeRow($this->phpSheet, $row_start + 1) * 256; - $x2 = $width / \PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object - $y2 = $height / \PhpSpreadsheet\Shared\Excel5::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object + $x1 = $x1 / \PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_start)) * 1024; + $y1 = $y1 / \PhpSpreadsheet\Shared\Excel5::sizeRow($this->phpSheet, $row_start + 1) * 256; + $x2 = $width / \PhpSpreadsheet\Shared\Excel5::sizeCol($this->phpSheet, \PhpSpreadsheet\Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object + $y2 = $height / \PhpSpreadsheet\Shared\Excel5::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object $this->writeObjPicture($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2); } @@ -2441,77 +2437,76 @@ class Worksheet extends BIFFwriter * Store the OBJ record that precedes an IMDATA record. This could be generalise * to support other Excel objects. * - * @param integer $colL Column containing upper left corner of object - * @param integer $dxL Distance from left side of cell - * @param integer $rwT Row containing top left corner of object - * @param integer $dyT Distance from top of cell - * @param integer $colR Column containing lower right corner of object - * @param integer $dxR Distance from right of cell - * @param integer $rwB Row containing bottom right corner of object - * @param integer $dyB Distance from bottom of cell + * @param int $colL Column containing upper left corner of object + * @param int $dxL Distance from left side of cell + * @param int $rwT Row containing top left corner of object + * @param int $dyT Distance from top of cell + * @param int $colR Column containing lower right corner of object + * @param int $dxR Distance from right of cell + * @param int $rwB Row containing bottom right corner of object + * @param int $dyB Distance from bottom of cell */ private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB) { - $record = 0x005d; // Record identifier - $length = 0x003c; // Bytes to follow + $record = 0x005d; // Record identifier + $length = 0x003c; // Bytes to follow - $cObj = 0x0001; // Count of objects in file (set to 1) - $OT = 0x0008; // Object type. 8 = Picture - $id = 0x0001; // Object ID - $grbit = 0x0614; // Option flags + $cObj = 0x0001; // Count of objects in file (set to 1) + $OT = 0x0008; // Object type. 8 = Picture + $id = 0x0001; // Object ID + $grbit = 0x0614; // Option flags - $cbMacro = 0x0000; // Length of FMLA structure - $Reserved1 = 0x0000; // Reserved - $Reserved2 = 0x0000; // Reserved + $cbMacro = 0x0000; // Length of FMLA structure + $Reserved1 = 0x0000; // Reserved + $Reserved2 = 0x0000; // Reserved - $icvBack = 0x09; // Background colour - $icvFore = 0x09; // Foreground colour - $fls = 0x00; // Fill pattern - $fAuto = 0x00; // Automatic fill - $icv = 0x08; // Line colour - $lns = 0xff; // Line style - $lnw = 0x01; // Line weight - $fAutoB = 0x00; // Automatic border - $frs = 0x0000; // Frame style - $cf = 0x0009; // Image format, 9 = bitmap - $Reserved3 = 0x0000; // Reserved - $cbPictFmla = 0x0000; // Length of FMLA structure - $Reserved4 = 0x0000; // Reserved - $grbit2 = 0x0001; // Option flags - $Reserved5 = 0x0000; // Reserved + $icvBack = 0x09; // Background colour + $icvFore = 0x09; // Foreground colour + $fls = 0x00; // Fill pattern + $fAuto = 0x00; // Automatic fill + $icv = 0x08; // Line colour + $lns = 0xff; // Line style + $lnw = 0x01; // Line weight + $fAutoB = 0x00; // Automatic border + $frs = 0x0000; // Frame style + $cf = 0x0009; // Image format, 9 = bitmap + $Reserved3 = 0x0000; // Reserved + $cbPictFmla = 0x0000; // Length of FMLA structure + $Reserved4 = 0x0000; // Reserved + $grbit2 = 0x0001; // Option flags + $Reserved5 = 0x0000; // Reserved - - $header = pack("vv", $record, $length); - $data = pack("V", $cObj); - $data .= pack("v", $OT); - $data .= pack("v", $id); - $data .= pack("v", $grbit); - $data .= pack("v", $colL); - $data .= pack("v", $dxL); - $data .= pack("v", $rwT); - $data .= pack("v", $dyT); - $data .= pack("v", $colR); - $data .= pack("v", $dxR); - $data .= pack("v", $rwB); - $data .= pack("v", $dyB); - $data .= pack("v", $cbMacro); - $data .= pack("V", $Reserved1); - $data .= pack("v", $Reserved2); - $data .= pack("C", $icvBack); - $data .= pack("C", $icvFore); - $data .= pack("C", $fls); - $data .= pack("C", $fAuto); - $data .= pack("C", $icv); - $data .= pack("C", $lns); - $data .= pack("C", $lnw); - $data .= pack("C", $fAutoB); - $data .= pack("v", $frs); - $data .= pack("V", $cf); - $data .= pack("v", $Reserved3); - $data .= pack("v", $cbPictFmla); - $data .= pack("v", $Reserved4); - $data .= pack("v", $grbit2); - $data .= pack("V", $Reserved5); + $header = pack('vv', $record, $length); + $data = pack('V', $cObj); + $data .= pack('v', $OT); + $data .= pack('v', $id); + $data .= pack('v', $grbit); + $data .= pack('v', $colL); + $data .= pack('v', $dxL); + $data .= pack('v', $rwT); + $data .= pack('v', $dyT); + $data .= pack('v', $colR); + $data .= pack('v', $dxR); + $data .= pack('v', $rwB); + $data .= pack('v', $dyB); + $data .= pack('v', $cbMacro); + $data .= pack('V', $Reserved1); + $data .= pack('v', $Reserved2); + $data .= pack('C', $icvBack); + $data .= pack('C', $icvFore); + $data .= pack('C', $fls); + $data .= pack('C', $fAuto); + $data .= pack('C', $icv); + $data .= pack('C', $lns); + $data .= pack('C', $lnw); + $data .= pack('C', $fAutoB); + $data .= pack('v', $frs); + $data .= pack('V', $cf); + $data .= pack('v', $Reserved3); + $data .= pack('v', $cbPictFmla); + $data .= pack('v', $Reserved4); + $data .= pack('v', $grbit2); + $data .= pack('V', $Reserved5); $this->append($header . $data); } @@ -2519,7 +2514,6 @@ class Worksheet extends BIFFwriter /** * Convert a GD-image into the internal format. * - * @access private * @param resource $image The image to process * @return array Array with data and properties of the bitmap */ @@ -2528,21 +2522,21 @@ class Worksheet extends BIFFwriter $width = imagesx($image); $height = imagesy($image); - $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); - for ($j=$height; $j--;) { - for ($i=0; $i < $width; ++$i) { + $data = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18); + for ($j = $height; --$j;) { + for ($i = 0; $i < $width; ++$i) { $color = imagecolorsforindex($image, imagecolorat($image, $i, $j)); - foreach (array("red", "green", "blue") as $key) { - $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127); + foreach (['red', 'green', 'blue'] as $key) { + $color[$key] = $color[$key] + round((255 - $color[$key]) * $color['alpha'] / 127); } - $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]); + $data .= chr($color['blue']) . chr($color['green']) . chr($color['red']); } - if (3*$width % 4) { - $data .= str_repeat("\x00", 4 - 3*$width % 4); + if (3 * $width % 4) { + $data .= str_repeat("\x00", 4 - 3 * $width % 4); } } - return array($width, $height, strlen($data), $data); + return [$width, $height, strlen($data), $data]; } /** @@ -2550,14 +2544,13 @@ class Worksheet extends BIFFwriter * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the * MSDN library. * - * @access private * @param string $bitmap The bitmap to process * @return array Array with data and properties of the bitmap */ public function processBitmap($bitmap) { // Open file. - $bmp_fd = @fopen($bitmap, "rb"); + $bmp_fd = @fopen($bitmap, 'rb'); if (!$bmp_fd) { throw new \PhpSpreadsheet\Writer\Exception("Couldn't import $bitmap"); } @@ -2571,8 +2564,8 @@ class Worksheet extends BIFFwriter } // The first 2 bytes are used to identify the bitmap. - $identity = unpack("A2ident", $data); - if ($identity['ident'] != "BM") { + $identity = unpack('A2ident', $data); + if ($identity['ident'] != 'BM') { throw new \PhpSpreadsheet\Writer\Exception("$bitmap doesn't appear to be a valid bitmap image.\n"); } @@ -2582,20 +2575,20 @@ class Worksheet extends BIFFwriter // Read and remove the bitmap size. This is more reliable than reading // the data size at offset 0x22. // - $size_array = unpack("Vsa", substr($data, 0, 4)); - $size = $size_array['sa']; - $data = substr($data, 4); - $size -= 0x36; // Subtract size of bitmap header. - $size += 0x0C; // Add size of BIFF header. + $size_array = unpack('Vsa', substr($data, 0, 4)); + $size = $size_array['sa']; + $data = substr($data, 4); + $size -= 0x36; // Subtract size of bitmap header. + $size += 0x0C; // Add size of BIFF header. // Remove bitmap data: reserved, offset, header length. $data = substr($data, 12); // Read and remove the bitmap width and height. Verify the sizes. - $width_and_height = unpack("V2", substr($data, 0, 8)); - $width = $width_and_height[1]; + $width_and_height = unpack('V2', substr($data, 0, 8)); + $width = $width_and_height[1]; $height = $width_and_height[2]; - $data = substr($data, 8); + $data = substr($data, 8); if ($width > 0xFFFF) { throw new \PhpSpreadsheet\Writer\Exception("$bitmap: largest image width supported is 65k.\n"); } @@ -2604,7 +2597,7 @@ class Worksheet extends BIFFwriter } // Read and remove the bitmap planes and bpp data. Verify them. - $planes_and_bitcount = unpack("v2", substr($data, 0, 4)); + $planes_and_bitcount = unpack('v2', substr($data, 0, 4)); $data = substr($data, 4); if ($planes_and_bitcount[2] != 24) { // Bitcount throw new \PhpSpreadsheet\Writer\Exception("$bitmap isn't a 24bit true color bitmap.\n"); @@ -2614,7 +2607,7 @@ class Worksheet extends BIFFwriter } // Read and remove the bitmap compression. Verify compression. - $compression = unpack("Vcomp", substr($data, 0, 4)); + $compression = unpack('Vcomp', substr($data, 0, 4)); $data = substr($data, 4); //$compression = 0; @@ -2626,10 +2619,10 @@ class Worksheet extends BIFFwriter $data = substr($data, 20); // Add the BITMAPCOREHEADER data - $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); - $data = $header . $data; + $header = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18); + $data = $header . $data; - return (array($width, $height, $size, $data)); + return [$width, $height, $size, $data]; } /** @@ -2643,11 +2636,11 @@ class Worksheet extends BIFFwriter return; } - $record = 0x00A0; // Record identifier - $length = 0x0004; // Bytes to follow + $record = 0x00A0; // Record identifier + $length = 0x0004; // Bytes to follow - $header = pack("vv", $record, $length); - $data = pack("vv", $this->phpSheet->getSheetView()->getZoomScale(), 100); + $header = pack('vv', $record, $length); + $data = pack('vv', $this->phpSheet->getSheetView()->getZoomScale(), 100); $this->append($header . $data); } @@ -2692,10 +2685,10 @@ class Worksheet extends BIFFwriter $record = 0x00EC; // Record identifier // chunk of Escher stream for one shape - $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]); + $dataChunk = substr($data, $spOffsets[$i - 1], $spOffsets[$i] - $spOffsets[$i - 1]); $length = strlen($dataChunk); - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); $this->append($header . $dataChunk); @@ -2770,14 +2763,14 @@ class Worksheet extends BIFFwriter $record = 0x01B2; // Record identifier $length = 0x0012; // Bytes to follow - $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records + $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position $verPos = 0x00000000; // Vertical position of prompt box, if fixed position - $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible + $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible $header = pack('vv', $record, $length); - $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection)); - $this->append($header.$data); + $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection)); + $this->append($header . $data); // DATAVALIDATION records $record = 0x01BE; // Record identifier @@ -2881,7 +2874,7 @@ class Worksheet extends BIFFwriter } $options |= $operator << 20; - $data = pack('V', $options); + $data = pack('V', $options); // prompt title $promptTitle = $dataValidation->getPromptTitle() !== '' ? @@ -2940,7 +2933,7 @@ class Worksheet extends BIFFwriter $data .= $this->writeBIFF8CellRangeAddressFixed($cellCoordinate); $length = strlen($data); - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); $this->append($header . $data); } @@ -2980,29 +2973,29 @@ class Worksheet extends BIFFwriter */ private function writePageLayoutView() { - $record = 0x088B; // Record identifier - $length = 0x0010; // Bytes to follow + $record = 0x088B; // Record identifier + $length = 0x0010; // Bytes to follow - $rt = 0x088B; // 2 - $grbitFrt = 0x0000; // 2 - $reserved = 0x0000000000000000; // 8 + $rt = 0x088B; // 2 + $grbitFrt = 0x0000; // 2 + $reserved = 0x0000000000000000; // 8 $wScalvePLV = $this->phpSheet->getSheetView()->getZoomScale(); // 2 // The options flags that comprise $grbit if ($this->phpSheet->getSheetView()->getView() == \PhpSpreadsheet\Worksheet\SheetView::SHEETVIEW_PAGE_LAYOUT) { - $fPageLayoutView = 1; + $fPageLayoutView = 1; } else { - $fPageLayoutView = 0; + $fPageLayoutView = 0; } - $fRulerVisible = 0; + $fRulerVisible = 0; $fWhitespaceHidden = 0; - $grbit = $fPageLayoutView; // 2 - $grbit |= $fRulerVisible << 1; - $grbit |= $fWhitespaceHidden << 3; + $grbit = $fPageLayoutView; // 2 + $grbit |= $fRulerVisible << 1; + $grbit |= $fWhitespaceHidden << 3; - $header = pack("vv", $record, $length); - $data = pack("vvVVvv", $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit); + $header = pack('vv', $record, $length); + $data = pack('vvVVvv', $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit); $this->append($header . $data); } @@ -3012,7 +3005,7 @@ class Worksheet extends BIFFwriter */ private function writeCFRule(\PhpSpreadsheet\Style\Conditional $conditional) { - $record = 0x01B1; // Record identifier + $record = 0x01B1; // Record identifier // $type : Type of the CF // $operatorType : Comparison operator @@ -3174,7 +3167,7 @@ class Worksheet extends BIFFwriter if ($bFormatFont == 1) { // Font Name if ($conditional->getStyle()->getFont()->getName() == null) { - $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); + $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); } else { $dataBlockFont = \PhpSpreadsheet\Shared\StringHelper::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName()); @@ -4157,7 +4150,7 @@ class Worksheet extends BIFFwriter } } - $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); + $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); if ($bFormatFont == 1) { // Block Formatting : OK $data .= $dataBlockFont; } @@ -4179,7 +4172,7 @@ class Worksheet extends BIFFwriter if (!is_null($operand2)) { $data .= $operand2; } - $header = pack('vv', $record, strlen($data)); + $header = pack('vv', $record, strlen($data)); $this->append($header . $data); } @@ -4188,14 +4181,14 @@ class Worksheet extends BIFFwriter */ private function writeCFHeader() { - $record = 0x01B0; // Record identifier - $length = 0x0016; // Bytes to follow + $record = 0x01B0; // Record identifier + $length = 0x0016; // Bytes to follow $numColumnMin = null; $numColumnMax = null; $numRowMin = null; $numRowMax = null; - $arrConditional = array(); + $arrConditional = []; foreach ($this->phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { foreach ($conditionalStyles as $conditional) { if ($conditional->getConditionType() == \PhpSpreadsheet\Style\Conditional::CONDITION_EXPRESSION @@ -4224,13 +4217,13 @@ class Worksheet extends BIFFwriter } } $needRedraw = 1; - $cellRange = pack('vvvv', $numRowMin-1, $numRowMax-1, $numColumnMin-1, $numColumnMax-1); + $cellRange = pack('vvvv', $numRowMin - 1, $numRowMax - 1, $numColumnMin - 1, $numColumnMax - 1); - $header = pack('vv', $record, $length); - $data = pack('vv', count($arrConditional), $needRedraw); - $data .= $cellRange; - $data .= pack('v', 0x0001); - $data .= $cellRange; + $header = pack('vv', $record, $length); + $data = pack('vv', count($arrConditional), $needRedraw); + $data .= $cellRange; + $data .= pack('v', 0x0001); + $data .= $cellRange; $this->append($header . $data); } } diff --git a/src/PhpSpreadsheet/Writer/Excel5/Xf.php b/src/PhpSpreadsheet/Writer/Excel5/Xf.php index 033446a4..ada7e397 100644 --- a/src/PhpSpreadsheet/Writer/Excel5/Xf.php +++ b/src/PhpSpreadsheet/Writer/Excel5/Xf.php @@ -66,93 +66,91 @@ class Xf /** * Style XF or a cell XF ? * - * @var boolean + * @var bool */ private $isStyleXf; /** * Index to the FONT record. Index 4 does not exist - * @var integer + * @var int */ private $fontIndex; /** * An index (2 bytes) to a FORMAT record (number format). - * @var integer + * @var int */ private $numberFormatIndex; /** * 1 bit, apparently not used. - * @var integer + * @var int */ private $textJustLast; /** * The cell's foreground color. - * @var integer + * @var int */ private $foregroundColor; /** * The cell's background color. - * @var integer + * @var int */ private $backgroundColor; /** * Color of the bottom border of the cell. - * @var integer + * @var int */ private $bottomBorderColor; /** * Color of the top border of the cell. - * @var integer + * @var int */ private $topBorderColor; /** - * Color of the left border of the cell. - * @var integer - */ + * Color of the left border of the cell. + * @var int + */ private $leftBorderColor; /** * Color of the right border of the cell. - * @var integer + * @var int */ private $rightBorderColor; /** * Constructor * - * @access public * @param \PhpSpreadsheet\Style The XF format */ public function __construct(\PhpSpreadsheet\Style $style = null) { - $this->isStyleXf = false; + $this->isStyleXf = false; $this->fontIndex = 0; - $this->numberFormatIndex = 0; + $this->numberFormatIndex = 0; - $this->textJustLast = 0; + $this->textJustLast = 0; - $this->foregroundColor = 0x40; - $this->backgroundColor = 0x41; + $this->foregroundColor = 0x40; + $this->backgroundColor = 0x41; - $this->_diag = 0; + $this->_diag = 0; - $this->bottomBorderColor = 0x40; - $this->topBorderColor = 0x40; - $this->leftBorderColor = 0x40; - $this->rightBorderColor = 0x40; - $this->_diag_color = 0x40; + $this->bottomBorderColor = 0x40; + $this->topBorderColor = 0x40; + $this->leftBorderColor = 0x40; + $this->rightBorderColor = 0x40; + $this->_diag_color = 0x40; $this->_style = $style; } - /** * Generate an Excel BIFF XF record (style or cell). * @@ -164,29 +162,29 @@ class Xf if ($this->isStyleXf) { $style = 0xFFF5; } else { - $style = self::mapLocked($this->_style->getProtection()->getLocked()); - $style |= self::mapHidden($this->_style->getProtection()->getHidden()) << 1; + $style = self::mapLocked($this->_style->getProtection()->getLocked()); + $style |= self::mapHidden($this->_style->getProtection()->getHidden()) << 1; } // Flags to indicate if attributes have been set. - $atr_num = ($this->numberFormatIndex != 0)?1:0; - $atr_fnt = ($this->fontIndex != 0)?1:0; - $atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0; - $atr_bdr = (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) || + $atr_num = ($this->numberFormatIndex != 0)?1:0; + $atr_fnt = ($this->fontIndex != 0)?1:0; + $atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0; + $atr_bdr = (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) || + self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) || + self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) || self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0; - $atr_pat = (($this->foregroundColor != 0x40) || + $atr_pat = (($this->foregroundColor != 0x40) || ($this->backgroundColor != 0x41) || self::mapFillType($this->_style->getFill()->getFillType()))?1:0; - $atr_prot = self::mapLocked($this->_style->getProtection()->getLocked()) + $atr_prot = self::mapLocked($this->_style->getProtection()->getLocked()) | self::mapHidden($this->_style->getProtection()->getHidden()); // Zero the default border colour if the border has not been set. if (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) { $this->bottomBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) { + if (self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) { $this->topBorderColor = 0; } if (self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) { @@ -205,59 +203,59 @@ class Xf $ifnt = $this->fontIndex; // Index to FONT record $ifmt = $this->numberFormatIndex; // Index to FORMAT record - $align = $this->mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment - $align |= (int) $this->_style->getAlignment()->getWrapText() << 3; - $align |= self::mapVAlign($this->_style->getAlignment()->getVertical()) << 4; + $align = $this->mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment + $align |= (int) $this->_style->getAlignment()->getWrapText() << 3; + $align |= self::mapVAlign($this->_style->getAlignment()->getVertical()) << 4; $align |= $this->textJustLast << 7; - $used_attrib = $atr_num << 2; - $used_attrib |= $atr_fnt << 3; - $used_attrib |= $atr_alc << 4; - $used_attrib |= $atr_bdr << 5; - $used_attrib |= $atr_pat << 6; + $used_attrib = $atr_num << 2; + $used_attrib |= $atr_fnt << 3; + $used_attrib |= $atr_alc << 4; + $used_attrib |= $atr_bdr << 5; + $used_attrib |= $atr_pat << 6; $used_attrib |= $atr_prot << 7; - $icv = $this->foregroundColor; // fg and bg pattern colors - $icv |= $this->backgroundColor << 7; + $icv = $this->foregroundColor; // fg and bg pattern colors + $icv |= $this->backgroundColor << 7; - $border1 = self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4; - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8; - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12; - $border1 |= $this->leftBorderColor << 16; - $border1 |= $this->rightBorderColor << 23; + $border1 = self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color + $border1 |= self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4; + $border1 |= self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8; + $border1 |= self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12; + $border1 |= $this->leftBorderColor << 16; + $border1 |= $this->rightBorderColor << 23; $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection(); $diag_tl_to_rb = $diagonalDirection == \PhpSpreadsheet\Style\Borders::DIAGONAL_BOTH || $diagonalDirection == \PhpSpreadsheet\Style\Borders::DIAGONAL_DOWN; $diag_tr_to_lb = $diagonalDirection == \PhpSpreadsheet\Style\Borders::DIAGONAL_BOTH || $diagonalDirection == \PhpSpreadsheet\Style\Borders::DIAGONAL_UP; - $border1 |= $diag_tl_to_rb << 30; - $border1 |= $diag_tr_to_lb << 31; + $border1 |= $diag_tl_to_rb << 30; + $border1 |= $diag_tr_to_lb << 31; - $border2 = $this->topBorderColor; // Border color - $border2 |= $this->bottomBorderColor << 7; - $border2 |= $this->_diag_color << 14; - $border2 |= self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21; - $border2 |= self::mapFillType($this->_style->getFill()->getFillType()) << 26; + $border2 = $this->topBorderColor; // Border color + $border2 |= $this->bottomBorderColor << 7; + $border2 |= $this->_diag_color << 14; + $border2 |= self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21; + $border2 |= self::mapFillType($this->_style->getFill()->getFillType()) << 26; - $header = pack("vv", $record, $length); + $header = pack('vv', $record, $length); //BIFF8 options: identation, shrinkToFit and text direction - $biff8_options = $this->_style->getAlignment()->getIndent(); + $biff8_options = $this->_style->getAlignment()->getIndent(); $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4; - $data = pack("vvvC", $ifnt, $ifmt, $style, $align); - $data .= pack("CCC", self::mapTextRotation($this->_style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); - $data .= pack("VVv", $border1, $border2, $icv); + $data = pack('vvvC', $ifnt, $ifmt, $style, $align); + $data .= pack('CCC', self::mapTextRotation($this->_style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); + $data .= pack('VVv', $border1, $border2, $icv); - return($header . $data); + return $header . $data; } /** * Is this a style XF ? * - * @param boolean $value + * @param bool $value */ public function setIsStyleXf($value) { @@ -267,7 +265,6 @@ class Xf /** * Sets the cell's bottom border color * - * @access public * @param int $colorIndex Color index */ public function setBottomColor($colorIndex) @@ -278,7 +275,6 @@ class Xf /** * Sets the cell's top border color * - * @access public * @param int $colorIndex Color index */ public function setTopColor($colorIndex) @@ -289,7 +285,6 @@ class Xf /** * Sets the cell's left border color * - * @access public * @param int $colorIndex Color index */ public function setLeftColor($colorIndex) @@ -300,7 +295,6 @@ class Xf /** * Sets the cell's right border color * - * @access public * @param int $colorIndex Color index */ public function setRightColor($colorIndex) @@ -311,7 +305,6 @@ class Xf /** * Sets the cell's diagonal border color * - * @access public * @param int $colorIndex Color index */ public function setDiagColor($colorIndex) @@ -319,11 +312,9 @@ class Xf $this->_diag_color = $colorIndex; } - /** * Sets the cell's foreground color * - * @access public * @param int $colorIndex Color index */ public function setFgColor($colorIndex) @@ -334,7 +325,6 @@ class Xf /** * Sets the cell's background color * - * @access public * @param int $colorIndex Color index */ public function setBgColor($colorIndex) @@ -346,8 +336,7 @@ class Xf * Sets the index to the number format record * It can be date, time, currency, etc... * - * @access public - * @param integer $numberFormatIndex Index to format record + * @param int $numberFormatIndex Index to format record */ public function setNumberFormatIndex($numberFormatIndex) { @@ -367,24 +356,23 @@ class Xf /** * Map of BIFF2-BIFF8 codes for border styles * @static array of int - * */ - private static $mapBorderStyles = array( - \PhpSpreadsheet\Style\Border::BORDER_NONE => 0x00, - \PhpSpreadsheet\Style\Border::BORDER_THIN => 0x01, - \PhpSpreadsheet\Style\Border::BORDER_MEDIUM => 0x02, - \PhpSpreadsheet\Style\Border::BORDER_DASHED => 0x03, - \PhpSpreadsheet\Style\Border::BORDER_DOTTED => 0x04, - \PhpSpreadsheet\Style\Border::BORDER_THICK => 0x05, - \PhpSpreadsheet\Style\Border::BORDER_DOUBLE => 0x06, - \PhpSpreadsheet\Style\Border::BORDER_HAIR => 0x07, - \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHED => 0x08, - \PhpSpreadsheet\Style\Border::BORDER_DASHDOT => 0x09, - \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHDOT => 0x0A, - \PhpSpreadsheet\Style\Border::BORDER_DASHDOTDOT => 0x0B, + private static $mapBorderStyles = [ + \PhpSpreadsheet\Style\Border::BORDER_NONE => 0x00, + \PhpSpreadsheet\Style\Border::BORDER_THIN => 0x01, + \PhpSpreadsheet\Style\Border::BORDER_MEDIUM => 0x02, + \PhpSpreadsheet\Style\Border::BORDER_DASHED => 0x03, + \PhpSpreadsheet\Style\Border::BORDER_DOTTED => 0x04, + \PhpSpreadsheet\Style\Border::BORDER_THICK => 0x05, + \PhpSpreadsheet\Style\Border::BORDER_DOUBLE => 0x06, + \PhpSpreadsheet\Style\Border::BORDER_HAIR => 0x07, + \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHED => 0x08, + \PhpSpreadsheet\Style\Border::BORDER_DASHDOT => 0x09, + \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHDOT => 0x0A, + \PhpSpreadsheet\Style\Border::BORDER_DASHDOTDOT => 0x0B, \PhpSpreadsheet\Style\Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, - \PhpSpreadsheet\Style\Border::BORDER_SLANTDASHDOT => 0x0D, - ); + \PhpSpreadsheet\Style\Border::BORDER_SLANTDASHDOT => 0x0D, + ]; /** * Map border style @@ -397,37 +385,37 @@ class Xf if (isset(self::$mapBorderStyles[$borderStyle])) { return self::$mapBorderStyles[$borderStyle]; } + return 0x00; } /** * Map of BIFF2-BIFF8 codes for fill types * @static array of int - * */ - private static $mapFillTypes = array( - \PhpSpreadsheet\Style\Fill::FILL_NONE => 0x00, - \PhpSpreadsheet\Style\Fill::FILL_SOLID => 0x01, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKGRAY => 0x03, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTGRAY => 0x04, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKVERTICAL => 0x06, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKDOWN => 0x07, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKUP => 0x08, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKGRID => 0x09, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, + private static $mapFillTypes = [ + \PhpSpreadsheet\Style\Fill::FILL_NONE => 0x00, + \PhpSpreadsheet\Style\Fill::FILL_SOLID => 0x01, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKGRAY => 0x03, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTGRAY => 0x04, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKVERTICAL => 0x06, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKDOWN => 0x07, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKUP => 0x08, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKGRID => 0x09, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTUP => 0x0E, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTGRID => 0x0F, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY125 => 0x11, - \PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY0625 => 0x12, - \PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 - \PhpSpreadsheet\Style\Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 - ); + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTUP => 0x0E, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTGRID => 0x0F, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY125 => 0x11, + \PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY0625 => 0x12, + \PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 + \PhpSpreadsheet\Style\Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 + ]; /** * Map fill type @@ -440,23 +428,23 @@ class Xf if (isset(self::$mapFillTypes[$fillType])) { return self::$mapFillTypes[$fillType]; } + return 0x00; } /** * Map of BIFF2-BIFF8 codes for horizontal alignment * @static array of int - * */ - private static $mapHAlignments = array( - \PhpSpreadsheet\Style\Alignment::HORIZONTAL_GENERAL => 0, - \PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT => 1, - \PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER => 2, - \PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT => 3, - \PhpSpreadsheet\Style\Alignment::HORIZONTAL_FILL => 4, - \PhpSpreadsheet\Style\Alignment::HORIZONTAL_JUSTIFY => 5, + private static $mapHAlignments = [ + \PhpSpreadsheet\Style\Alignment::HORIZONTAL_GENERAL => 0, + \PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT => 1, + \PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER => 2, + \PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT => 3, + \PhpSpreadsheet\Style\Alignment::HORIZONTAL_FILL => 4, + \PhpSpreadsheet\Style\Alignment::HORIZONTAL_JUSTIFY => 5, \PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, - ); + ]; /** * Map to BIFF2-BIFF8 codes for horizontal alignment @@ -469,20 +457,20 @@ class Xf if (isset(self::$mapHAlignments[$hAlign])) { return self::$mapHAlignments[$hAlign]; } + return 0; } /** * Map of BIFF2-BIFF8 codes for vertical alignment * @static array of int - * */ - private static $mapVAlignments = array( - \PhpSpreadsheet\Style\Alignment::VERTICAL_TOP => 0, - \PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER => 1, - \PhpSpreadsheet\Style\Alignment::VERTICAL_BOTTOM => 2, + private static $mapVAlignments = [ + \PhpSpreadsheet\Style\Alignment::VERTICAL_TOP => 0, + \PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER => 1, + \PhpSpreadsheet\Style\Alignment::VERTICAL_BOTTOM => 2, \PhpSpreadsheet\Style\Alignment::VERTICAL_JUSTIFY => 3, - ); + ]; /** * Map to BIFF2-BIFF8 codes for vertical alignment @@ -495,6 +483,7 @@ class Xf if (isset(self::$mapVAlignments[$vAlign])) { return self::$mapVAlignments[$vAlign]; } + return 2; } diff --git a/src/PhpSpreadsheet/Writer/HTML.php b/src/PhpSpreadsheet/Writer/HTML.php index 6bfc1298..0a027c71 100644 --- a/src/PhpSpreadsheet/Writer/HTML.php +++ b/src/PhpSpreadsheet/Writer/HTML.php @@ -57,14 +57,14 @@ class HTML extends BaseWriter implements IWriter /** * embed images, or link to images * - * @var boolean + * @var bool */ private $embedImages = false; /** * Use inline CSS? * - * @var boolean + * @var bool */ private $useInlineCss = false; @@ -92,7 +92,7 @@ class HTML extends BaseWriter implements IWriter /** * Flag whether spans have been calculated * - * @var boolean + * @var bool */ private $spansAreCalculated = false; @@ -101,33 +101,33 @@ class HTML extends BaseWriter implements IWriter * * @var array */ - private $isSpannedCell = array(); + private $isSpannedCell = []; /** * Excel cells that are upper-left corner in a cell merge * * @var array */ - private $isBaseCell = array(); + private $isBaseCell = []; /** * Excel rows that should not be written as HTML rows * * @var array */ - private $isSpannedRow = array(); + private $isSpannedRow = []; /** * Is the current writer creating PDF? * - * @var boolean + * @var bool */ protected $isPdf = false; /** * Generate the Navigation block * - * @var boolean + * @var bool */ private $generateSheetNavigationBlock = true; @@ -296,13 +296,14 @@ class HTML extends BaseWriter implements IWriter public function setSheetIndex($pValue = 0) { $this->sheetIndex = $pValue; + return $this; } /** * Get sheet index * - * @return boolean + * @return bool */ public function getGenerateSheetNavigationBlock() { @@ -312,12 +313,13 @@ class HTML extends BaseWriter implements IWriter /** * Set sheet index * - * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not + * @param bool $pValue Flag indicating whether the sheet navigation block should be generated or not * @return HTML */ public function setGenerateSheetNavigationBlock($pValue = true) { $this->generateSheetNavigationBlock = (bool) $pValue; + return $this; } @@ -327,15 +329,16 @@ class HTML extends BaseWriter implements IWriter public function writeAllSheets() { $this->sheetIndex = null; + return $this; } /** * Generate HTML header * - * @param boolean $pIncludeStyles Include styles? - * @return string + * @param bool $pIncludeStyles Include styles? * @throws \Spreadsheet\Writer\Exception + * @return string */ public function generateHTMLHeader($pIncludeStyles = false) { @@ -393,8 +396,8 @@ class HTML extends BaseWriter implements IWriter /** * Generate sheet data * - * @return string * @throws \Spreadsheet\Writer\Exception + * @return string */ public function generateSheetData() { @@ -409,7 +412,7 @@ class HTML extends BaseWriter implements IWriter } // Fetch sheets - $sheets = array(); + $sheets = []; if (is_null($this->sheetIndex)) { $sheets = $this->spreadsheet->getAllSheets(); } else { @@ -438,20 +441,20 @@ class HTML extends BaseWriter implements IWriter // calculate start of , $tbodyStart = $rowMin; - $theadStart = $theadEnd = 0; // default: no no + $theadStart = $theadEnd = 0; // default: no no if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) { $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop(); // we can only support repeating rows that start at top row if ($rowsToRepeatAtTop[0] == 1) { $theadStart = $rowsToRepeatAtTop[0]; - $theadEnd = $rowsToRepeatAtTop[1]; + $theadEnd = $rowsToRepeatAtTop[1]; $tbodyStart = $rowsToRepeatAtTop[1] + 1; } } // Loop through cells - $row = $rowMin-1; + $row = $rowMin - 1; while ($row++ < $rowMax) { // ? if ($row == $theadStart) { @@ -468,7 +471,7 @@ class HTML extends BaseWriter implements IWriter // Write row if there are HTML table cells in it if (!isset($this->isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row])) { // Start a new rowData - $rowData = array(); + $rowData = []; // Loop through columns $column = $dimension[0][0] - 1; while ($column++ < $dimension[1][0]) { @@ -512,8 +515,8 @@ class HTML extends BaseWriter implements IWriter /** * Generate sheet tabs * - * @return string * @throws \Spreadsheet\Writer\Exception + * @return string */ public function generateNavigation() { @@ -523,7 +526,7 @@ class HTML extends BaseWriter implements IWriter } // Fetch sheets - $sheets = array(); + $sheets = []; if (is_null($this->sheetIndex)) { $sheets = $this->spreadsheet->getAllSheets(); } else { @@ -584,31 +587,31 @@ class HTML extends BaseWriter implements IWriter } } $html = ''; - $colMax++; + ++$colMax; while ($row <= $rowMax) { $html .= ''; for ($col = 'A'; $col != $colMax; ++$col) { $html .= ''; - $html .= $this->writeImageInCell($pSheet, $col.$row); + $html .= $this->writeImageInCell($pSheet, $col . $row); if ($this->includeCharts) { - $html .= $this->writeChartInCell($pSheet, $col.$row); + $html .= $this->writeChartInCell($pSheet, $col . $row); } $html .= ''; } ++$row; $html .= ''; } + return $html; } - /** * Generate image tag in cell * * @param \Spreadsheet\Worksheet $pSheet \Spreadsheet\Worksheet * @param string $coordinates Cell coordinates - * @return string * @throws \Spreadsheet\Writer\Exception + * @return string */ private function writeImageInCell(\Spreadsheet\Worksheet $pSheet, $coordinates) { @@ -642,13 +645,13 @@ class HTML extends BaseWriter implements IWriter $imageData = $filename; } else { $imageDetails = getimagesize($filename); - if ($fp = fopen($filename, "rb", 0)) { + if ($fp = fopen($filename, 'rb', 0)) { $picture = fread($fp, filesize($filename)); fclose($fp); // base64 encode the binary data, then break it // into chunks according to RFC 2045 semantics $base64 = chunk_split(base64_encode($picture)); - $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64; + $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; } else { $imageData = $filename; } @@ -670,13 +673,13 @@ class HTML extends BaseWriter implements IWriter $contents = ob_get_contents(); // Instead, output above is saved to $contents ob_end_clean(); // End the output buffer. - $dataUri = "data:image/jpeg;base64," . base64_encode($contents); + $dataUri = 'data:image/jpeg;base64,' . base64_encode($contents); // Because of the nature of tables, width is more important than height. // max-width: 100% ensures that image doesnt overflow containing cell // width: X sets width of supplied image. // As a result, images bigger than cell will be contained and images smaller will not get stretched - $html .= ''; + $html .= ''; } } @@ -688,8 +691,8 @@ class HTML extends BaseWriter implements IWriter * * @param \Spreadsheet\Worksheet $pSheet \Spreadsheet\Worksheet * @param string $coordinates Cell coordinates - * @return string * @throws \Spreadsheet\Writer\Exception + * @return string */ private function writeChartInCell(\Spreadsheet\Worksheet $pSheet, $coordinates) { @@ -701,20 +704,20 @@ class HTML extends BaseWriter implements IWriter if ($chart instanceof Spreadsheet_Chart) { $chartCoordinates = $chart->getTopLeftPosition(); if ($chartCoordinates['cell'] == $coordinates) { - $chartFileName = \Spreadsheet\Shared\File::sysGetTempDir().'/'.uniqid().'.png'; + $chartFileName = \Spreadsheet\Shared\File::sysGetTempDir() . '/' . uniqid() . '.png'; if (!$chart->render($chartFileName)) { return; } $html .= PHP_EOL; $imageDetails = getimagesize($chartFileName); - if ($fp = fopen($chartFileName, "rb", 0)) { + if ($fp = fopen($chartFileName, 'rb', 0)) { $picture = fread($fp, filesize($chartFileName)); fclose($fp); // base64 encode the binary data, then break it // into chunks according to RFC 2045 semantics $base64 = chunk_split(base64_encode($picture)); - $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64; + $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; $html .= '
'; $html .= '' . PHP_EOL; @@ -733,9 +736,9 @@ class HTML extends BaseWriter implements IWriter /** * Generate CSS styles * - * @param boolean $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>) - * @return string + * @param bool $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>) * @throws \Spreadsheet\Writer\Exception + * @return string */ public function generateStyles($generateSurroundingHTML = true) { @@ -775,9 +778,9 @@ class HTML extends BaseWriter implements IWriter /** * Build CSS styles * - * @param boolean $generateSurroundingHTML Generate surrounding HTML style? (html { }) - * @return array + * @param bool $generateSurroundingHTML Generate surrounding HTML style? (html { }) * @throws \Spreadsheet\Writer\Exception + * @return array */ public function buildCSS($generateSurroundingHTML = true) { @@ -797,19 +800,18 @@ class HTML extends BaseWriter implements IWriter } // Construct CSS - $css = array(); + $css = []; // Start styles if ($generateSurroundingHTML) { // html { } - $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif'; - $css['html']['font-size'] = '11pt'; + $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif'; + $css['html']['font-size'] = '11pt'; $css['html']['background-color'] = 'white'; } - // table { } - $css['table']['border-collapse'] = 'collapse'; + $css['table']['border-collapse'] = 'collapse'; if (!$this->isPdf) { $css['table']['page-break-after'] = 'always'; } @@ -843,7 +845,7 @@ class HTML extends BaseWriter implements IWriter } // Fetch sheets - $sheets = array(); + $sheets = []; if (is_null($this->sheetIndex)) { $sheets = $this->spreadsheet->getAllSheets(); } else { @@ -886,7 +888,7 @@ class HTML extends BaseWriter implements IWriter $rowDimension = $sheet->getDefaultRowDimension(); // table.sheetN tr { } - $css['table.sheet' . $sheetIndex . ' tr'] = array(); + $css['table.sheet' . $sheetIndex . ' tr'] = []; if ($rowDimension->getRowHeight() == -1) { $pt_height = Font::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont()); @@ -895,7 +897,7 @@ class HTML extends BaseWriter implements IWriter } $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt'; if ($rowDimension->getVisible() === false) { - $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none'; + $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none'; $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden'; } @@ -904,7 +906,7 @@ class HTML extends BaseWriter implements IWriter $row = $rowDimension->getRowIndex() - 1; // table.sheetN tr.rowYYYYYY { } - $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = array(); + $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = []; if ($rowDimension->getRowHeight() == -1) { $pt_height = Font::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont()); @@ -960,14 +962,14 @@ class HTML extends BaseWriter implements IWriter private function createCSSStyleAlignment(\Spreadsheet\Style\Alignment $pStyle) { // Construct CSS - $css = array(); + $css = []; // Create CSS $css['vertical-align'] = $this->mapVAlign($pStyle->getVertical()); if ($textAlign = $this->mapHAlign($pStyle->getHorizontal())) { $css['text-align'] = $textAlign; - if (in_array($textAlign, array('left', 'right'))) { - $css['padding-'.$textAlign] = (string)((int)$pStyle->getIndent() * 9).'px'; + if (in_array($textAlign, ['left', 'right'])) { + $css['padding-' . $textAlign] = (string) ((int) $pStyle->getIndent() * 9) . 'px'; } } @@ -983,7 +985,7 @@ class HTML extends BaseWriter implements IWriter private function createCSSStyleFont(\Spreadsheet\Style\Font $pStyle) { // Construct CSS - $css = array(); + $css = []; // Create CSS if ($pStyle->getBold()) { @@ -1000,9 +1002,9 @@ class HTML extends BaseWriter implements IWriter $css['font-style'] = 'italic'; } - $css['color'] = '#' . $pStyle->getColor()->getRGB(); + $css['color'] = '#' . $pStyle->getColor()->getRGB(); $css['font-family'] = '\'' . $pStyle->getName() . '\''; - $css['font-size'] = $pStyle->getSize() . 'pt'; + $css['font-size'] = $pStyle->getSize() . 'pt'; return $css; } @@ -1016,13 +1018,13 @@ class HTML extends BaseWriter implements IWriter private function createCSSStyleBorders(\Spreadsheet\Style\Borders $pStyle) { // Construct CSS - $css = array(); + $css = []; // Create CSS $css['border-bottom'] = $this->createCSSStyleBorder($pStyle->getBottom()); - $css['border-top'] = $this->createCSSStyleBorder($pStyle->getTop()); - $css['border-left'] = $this->createCSSStyleBorder($pStyle->getLeft()); - $css['border-right'] = $this->createCSSStyleBorder($pStyle->getRight()); + $css['border-top'] = $this->createCSSStyleBorder($pStyle->getTop()); + $css['border-left'] = $this->createCSSStyleBorder($pStyle->getLeft()); + $css['border-right'] = $this->createCSSStyleBorder($pStyle->getRight()); return $css; } @@ -1053,7 +1055,7 @@ class HTML extends BaseWriter implements IWriter private function createCSSStyleFill(\Spreadsheet\Style\Fill $pStyle) { // Construct HTML - $css = array(); + $css = []; // Create CSS $value = $pStyle->getFillType() == \Spreadsheet\Style\Fill::FILL_NONE ? @@ -1080,8 +1082,8 @@ class HTML extends BaseWriter implements IWriter * Generate table header * * @param \Spreadsheet\Worksheet $pSheet The worksheet for the table we are writing - * @return string * @throws \Spreadsheet\Writer\Exception + * @return string */ private function generateTableHeader($pSheet) { @@ -1141,8 +1143,8 @@ class HTML extends BaseWriter implements IWriter * @param \Spreadsheet\Worksheet $pSheet \Spreadsheet\Worksheet * @param array $pValues Array containing cells in a row * @param int $pRow Row number (0-based) - * @return string * @throws \Spreadsheet\Writer\Exception + * @return string */ private function generateRow(\Spreadsheet\Worksheet $pSheet, $pValues = null, $pRow = 0, $cellType = 'td') { @@ -1189,7 +1191,7 @@ class HTML extends BaseWriter implements IWriter $cssClass = ''; $cssClass = 'column' . $colNum; } else { - $cssClass = array(); + $cssClass = []; if ($cellType == 'th') { if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum])) { $this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum]; @@ -1247,26 +1249,26 @@ class HTML extends BaseWriter implements IWriter $cellData = \Spreadsheet\Style\NumberFormat::toFormattedString( $cell->getCalculatedValue(), $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(), - array($this, 'formatColor') + [$this, 'formatColor'] ); } else { $cellData = \Spreadsheet\Style\NumberFormat::toFormattedString( $cell->getValue(), $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(), - array($this, 'formatColor') + [$this, 'formatColor'] ); } $cellData = htmlspecialchars($cellData); if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperScript()) { - $cellData = ''.$cellData.''; + $cellData = '' . $cellData . ''; } elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubScript()) { - $cellData = ''.$cellData.''; + $cellData = '' . $cellData . ''; } } // Converts the cell content so that spaces occuring at beginning of each new line are replaced by   // Example: " Hello\n to the world" is converted to "  Hello\n to the world" - $cellData = preg_replace("/(?m)(?:^|\\G) /", ' ', $cellData); + $cellData = preg_replace('/(?m)(?:^|\\G) /', ' ', $cellData); // convert newline "\n" to '
' $cellData = nl2br($cellData); @@ -1370,7 +1372,7 @@ class HTML extends BaseWriter implements IWriter $html .= $cellData; // Column end - $html .= '' . PHP_EOL; + $html .= '' . PHP_EOL; } // Next column @@ -1383,7 +1385,7 @@ class HTML extends BaseWriter implements IWriter // Return return $html; } else { - throw new \Spreadsheet\Writer\Exception("Invalid parameters passed."); + throw new \Spreadsheet\Writer\Exception('Invalid parameters passed.'); } } @@ -1393,9 +1395,9 @@ class HTML extends BaseWriter implements IWriter * @param array * @return string */ - private function assembleCSS($pValue = array()) + private function assembleCSS($pValue = []) { - $pairs = array(); + $pairs = []; foreach ($pValue as $property => $value) { $pairs[] = $property . ':' . $value; } @@ -1423,13 +1425,14 @@ class HTML extends BaseWriter implements IWriter public function setImagesRoot($pValue = '.') { $this->imagesRoot = $pValue; + return $this; } /** * Get embed images * - * @return boolean + * @return bool */ public function getEmbedImages() { @@ -1439,19 +1442,20 @@ class HTML extends BaseWriter implements IWriter /** * Set embed images * - * @param boolean $pValue + * @param bool $pValue * @return Spreadsheet_Writer_HTML */ public function setEmbedImages($pValue = '.') { $this->embedImages = $pValue; + return $this; } /** * Get use inline CSS? * - * @return boolean + * @return bool */ public function getUseInlineCss() { @@ -1461,12 +1465,13 @@ class HTML extends BaseWriter implements IWriter /** * Set use inline CSS? * - * @param boolean $pValue + * @param bool $pValue * @return Spreadsheet_Writer_HTML */ public function setUseInlineCss($pValue = false) { $this->useInlineCss = $pValue; + return $this; } @@ -1481,7 +1486,7 @@ class HTML extends BaseWriter implements IWriter { // Color information, e.g. [Red] is always at the beginning $color = null; // initialize - $matches = array(); + $matches = []; $color_regex = '/^\\[[a-zA-Z]+\\]/'; if (preg_match($color_regex, $pFormat, $matches)) { @@ -1510,18 +1515,18 @@ class HTML extends BaseWriter implements IWriter // In HTML only the upper-left cell should be written and it should have // appropriate rowspan / colspan attribute $sheetIndexes = $this->sheetIndex !== null ? - array($this->sheetIndex) : range(0, $this->spreadsheet->getSheetCount() - 1); + [$this->sheetIndex] : range(0, $this->spreadsheet->getSheetCount() - 1); foreach ($sheetIndexes as $sheetIndex) { $sheet = $this->spreadsheet->getSheet($sheetIndex); - $candidateSpannedRow = array(); + $candidateSpannedRow = []; // loop through all Excel merged cells foreach ($sheet->getMergeCells() as $cells) { - list($cells,) = \Spreadsheet\Cell::splitRange($cells); + list($cells) = \Spreadsheet\Cell::splitRange($cells); $first = $cells[0]; - $last = $cells[1]; + $last = $cells[1]; list($fc, $fr) = \Spreadsheet\Cell::coordinateFromString($first); $fc = \Spreadsheet\Cell::columnIndexFromString($fc) - 1; @@ -1539,17 +1544,17 @@ class HTML extends BaseWriter implements IWriter while ($c++ < $lc) { if (!($c == $fc && $r == $fr)) { // not the upper-left cell (should not be written in HTML) - $this->isSpannedCell[$sheetIndex][$r][$c] = array( - 'baseCell' => array($fr, $fc), - ); + $this->isSpannedCell[$sheetIndex][$r][$c] = [ + 'baseCell' => [$fr, $fc], + ]; } else { // upper-left is the base cell that should hold the colspan/rowspan attribute - $this->isBaseCell[$sheetIndex][$r][$c] = array( + $this->isBaseCell[$sheetIndex][$r][$c] = [ 'xlrowspan' => $lr - $fr + 1, // Excel rowspan - 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change + 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change 'xlcolspan' => $lc - $fc + 1, // Excel colspan - 'colspan' => $lc - $fc + 1, // HTML colspan, value may change - ); + 'colspan' => $lc - $fc + 1, // HTML colspan, value may change + ]; } } } @@ -1569,7 +1574,7 @@ class HTML extends BaseWriter implements IWriter // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1 if (isset($this->isSpannedRow[$sheetIndex])) { foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) { - $adjustedBaseCells = array(); + $adjustedBaseCells = []; $c = -1; $e = $countColumns - 1; while ($c++ < $e) { diff --git a/src/PhpSpreadsheet/Writer/OpenDocument.php b/src/PhpSpreadsheet/Writer/OpenDocument.php index 3aa2824f..c052466c 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument.php @@ -31,7 +31,7 @@ class OpenDocument extends BaseWriter implements IWriter * * @var OpenDocument\WriterPart[] */ - private $writerParts = array(); + private $writerParts = []; /** * Private PhpSpreadsheet @@ -49,15 +49,15 @@ class OpenDocument extends BaseWriter implements IWriter { $this->setPhpSpreadsheet($spreadsheet); - $writerPartsArray = array( - 'content' => \PhpSpreadsheet\Writer\OpenDocument\Content::class, - 'meta' => \PhpSpreadsheet\Writer\OpenDocument\Meta::class, - 'meta_inf' => \PhpSpreadsheet\Writer\OpenDocument\MetaInf::class, - 'mimetype' => \PhpSpreadsheet\Writer\OpenDocument\Mimetype::class, - 'settings' => \PhpSpreadsheet\Writer\OpenDocument\Settings::class, - 'styles' => \PhpSpreadsheet\Writer\OpenDocument\Styles::class, + $writerPartsArray = [ + 'content' => \PhpSpreadsheet\Writer\OpenDocument\Content::class, + 'meta' => \PhpSpreadsheet\Writer\OpenDocument\Meta::class, + 'meta_inf' => \PhpSpreadsheet\Writer\OpenDocument\MetaInf::class, + 'mimetype' => \PhpSpreadsheet\Writer\OpenDocument\Mimetype::class, + 'settings' => \PhpSpreadsheet\Writer\OpenDocument\Settings::class, + 'styles' => \PhpSpreadsheet\Writer\OpenDocument\Styles::class, 'thumbnails' => \PhpSpreadsheet\Writer\OpenDocument\Thumbnails::class, - ); + ]; foreach ($writerPartsArray as $writer => $class) { $this->writerParts[$writer] = new $class($this); @@ -162,8 +162,8 @@ class OpenDocument extends BaseWriter implements IWriter /** * Get PhpSpreadsheet object * - * @return PhpSpreadsheet * @throws \PhpSpreadsheet\Writer\Exception + * @return PhpSpreadsheet */ public function getPhpSpreadsheet() { @@ -184,6 +184,7 @@ class OpenDocument extends BaseWriter implements IWriter public function setPhpSpreadsheet(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { $this->spreadSheet = $spreadsheet; + return $this; } } diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/Cell/Comment.php b/src/PhpSpreadsheet/Writer/OpenDocument/Cell/Comment.php index 1901b7b5..8841fa9a 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/Cell/Comment.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/Cell/Comment.php @@ -27,7 +27,6 @@ namespace PhpSpreadsheet\Writer\OpenDocument\Cell; * @version ##VERSION##, ##DATE## */ - /** * @category PhpSpreadsheet * @copyright Copyright (c) 2006 - 2015 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) @@ -47,9 +46,9 @@ class Comment //$objWriter->writeAttribute('draw:style-name', 'gr1'); //$objWriter->writeAttribute('draw:text-style-name', 'P1'); $objWriter->writeAttribute('svg:width', $comment->getWidth()); - $objWriter->writeAttribute('svg:height', $comment->getHeight()); - $objWriter->writeAttribute('svg:x', $comment->getMarginLeft()); - $objWriter->writeAttribute('svg:y', $comment->getMarginTop()); + $objWriter->writeAttribute('svg:height', $comment->getHeight()); + $objWriter->writeAttribute('svg:x', $comment->getMarginLeft()); + $objWriter->writeAttribute('svg:y', $comment->getMarginTop()); //$objWriter->writeAttribute('draw:caption-point-x', $comment->getMarginLeft()); //$objWriter->writeAttribute('draw:caption-point-y', $comment->getMarginTop()); $objWriter->writeElement('dc:creator', $comment->getAuthor()); diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/Content.php b/src/PhpSpreadsheet/Writer/OpenDocument/Content.php index f2312409..8ab14baf 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/Content.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/Content.php @@ -27,7 +27,6 @@ namespace PhpSpreadsheet\Writer\OpenDocument; * @version ##VERSION##, ##DATE## */ - /** * @category PhpSpreadsheet * @copyright Copyright (c) 2006 - 2015 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) @@ -42,8 +41,8 @@ class Content extends WriterPart * Write content.xml to XML format * * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function write(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { @@ -63,51 +62,51 @@ class Content extends WriterPart // Content $objWriter->startElement('office:document-content'); - $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); - $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); - $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); - $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); - $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); - $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); - $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); - $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); - $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); - $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); - $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); - $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); - $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); - $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); - $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); - $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); - $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); - $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); - $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); - $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); - $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); - $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); - $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); - $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); - $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); - $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); - $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); - $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); - $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); - $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); - $objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); - $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); - $objWriter->writeAttribute('office:version', '1.2'); + $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); + $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); + $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); + $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); + $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); + $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); + $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); + $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); + $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); + $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); + $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); + $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); + $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); + $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); + $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); + $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); + $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); + $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); + $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); + $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); + $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); + $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); + $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); + $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); + $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); + $objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); + $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); + $objWriter->writeAttribute('office:version', '1.2'); - $objWriter->writeElement('office:scripts'); - $objWriter->writeElement('office:font-face-decls'); - $objWriter->writeElement('office:automatic-styles'); + $objWriter->writeElement('office:scripts'); + $objWriter->writeElement('office:font-face-decls'); + $objWriter->writeElement('office:automatic-styles'); - $objWriter->startElement('office:body'); - $objWriter->startElement('office:spreadsheet'); - $objWriter->writeElement('table:calculation-settings'); - $this->writeSheets($objWriter); - $objWriter->writeElement('table:named-expressions'); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->startElement('office:body'); + $objWriter->startElement('office:spreadsheet'); + $objWriter->writeElement('table:calculation-settings'); + $this->writeSheets($objWriter); + $objWriter->writeElement('table:named-expressions'); + $objWriter->endElement(); + $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); @@ -123,15 +122,15 @@ class Content extends WriterPart $spreadsheet = $this->getParentWriter()->getPhpSpreadsheet(); /* @var $spreadsheet PhpSpreadsheet */ $sheet_count = $spreadsheet->getSheetCount(); - for ($i = 0; $i < $sheet_count; $i++) { + for ($i = 0; $i < $sheet_count; ++$i) { //$this->getWriterPart('Worksheet')->writeWorksheet()); $objWriter->startElement('table:table'); - $objWriter->writeAttribute('table:name', $spreadsheet->getSheet($i)->getTitle()); - $objWriter->writeElement('office:forms'); - $objWriter->startElement('table:table-column'); - $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); - $objWriter->endElement(); - $this->writeRows($objWriter, $spreadsheet->getSheet($i)); + $objWriter->writeAttribute('table:name', $spreadsheet->getSheet($i)->getTitle()); + $objWriter->writeElement('office:forms'); + $objWriter->startElement('table:table-column'); + $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); + $objWriter->endElement(); + $this->writeRows($objWriter, $spreadsheet->getSheet($i)); $objWriter->endElement(); } } @@ -148,7 +147,7 @@ class Content extends WriterPart $span_row = 0; $rows = $sheet->getRowIterator(); while ($rows->valid()) { - $number_rows_repeated--; + --$number_rows_repeated; $row = $rows->current(); if ($row->getCellIterator()->valid()) { if ($span_row) { @@ -157,7 +156,7 @@ class Content extends WriterPart $objWriter->writeAttribute('table:number-rows-repeated', $span_row); } $objWriter->startElement('table:table-cell'); - $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); + $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); $objWriter->endElement(); $objWriter->endElement(); $span_row = 0; @@ -166,7 +165,7 @@ class Content extends WriterPart $this->writeCells($objWriter, $row); $objWriter->endElement(); } else { - $span_row++; + ++$span_row; } $rows->next(); } @@ -254,8 +253,8 @@ class Content extends WriterPart * Write span * * @param \PhpSpreadsheet\Shared\XMLWriter $objWriter - * @param integer $curColumn - * @param integer $prevColumn + * @param int $curColumn + * @param int $prevColumn */ private function writeCellSpan(\PhpSpreadsheet\Shared\XMLWriter $objWriter, $curColumn, $prevColumn) { @@ -264,7 +263,7 @@ class Content extends WriterPart $objWriter->writeElement('table:table-cell'); } elseif ($diff > 1) { $objWriter->startElement('table:table-cell'); - $objWriter->writeAttribute('table:number-columns-repeated', $diff); + $objWriter->writeAttribute('table:number-columns-repeated', $diff); $objWriter->endElement(); } } diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/Meta.php b/src/PhpSpreadsheet/Writer/OpenDocument/Meta.php index 1edd0032..bd5082c7 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/Meta.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/Meta.php @@ -30,8 +30,8 @@ class Meta extends WriterPart * Write meta.xml to XML format * * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function write(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/MetaInf.php b/src/PhpSpreadsheet/Writer/OpenDocument/MetaInf.php index 791dfcee..94374cad 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/MetaInf.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/MetaInf.php @@ -30,8 +30,8 @@ class MetaInf extends WriterPart * Write META-INF/manifest.xml to XML format * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeManifest(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { @@ -51,34 +51,34 @@ class MetaInf extends WriterPart // Manifest $objWriter->startElement('manifest:manifest'); - $objWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); - $objWriter->writeAttribute('manifest:version', '1.2'); + $objWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); + $objWriter->writeAttribute('manifest:version', '1.2'); - $objWriter->startElement('manifest:file-entry'); - $objWriter->writeAttribute('manifest:full-path', '/'); - $objWriter->writeAttribute('manifest:version', '1.2'); - $objWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.spreadsheet'); - $objWriter->endElement(); - $objWriter->startElement('manifest:file-entry'); - $objWriter->writeAttribute('manifest:full-path', 'meta.xml'); - $objWriter->writeAttribute('manifest:media-type', 'text/xml'); - $objWriter->endElement(); - $objWriter->startElement('manifest:file-entry'); - $objWriter->writeAttribute('manifest:full-path', 'settings.xml'); - $objWriter->writeAttribute('manifest:media-type', 'text/xml'); - $objWriter->endElement(); - $objWriter->startElement('manifest:file-entry'); - $objWriter->writeAttribute('manifest:full-path', 'content.xml'); - $objWriter->writeAttribute('manifest:media-type', 'text/xml'); - $objWriter->endElement(); - $objWriter->startElement('manifest:file-entry'); - $objWriter->writeAttribute('manifest:full-path', 'Thumbnails/thumbnail.png'); - $objWriter->writeAttribute('manifest:media-type', 'image/png'); - $objWriter->endElement(); - $objWriter->startElement('manifest:file-entry'); - $objWriter->writeAttribute('manifest:full-path', 'styles.xml'); - $objWriter->writeAttribute('manifest:media-type', 'text/xml'); - $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', '/'); + $objWriter->writeAttribute('manifest:version', '1.2'); + $objWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.spreadsheet'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'meta.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'settings.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'content.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'Thumbnails/thumbnail.png'); + $objWriter->writeAttribute('manifest:media-type', 'image/png'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'styles.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/Mimetype.php b/src/PhpSpreadsheet/Writer/OpenDocument/Mimetype.php index 7e6a713b..1eddda63 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/Mimetype.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/Mimetype.php @@ -28,8 +28,8 @@ class Mimetype extends WriterPart * Write mimetype to plain text format * * @param \PhpSpreadsheet\SpreadSheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function write(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/Settings.php b/src/PhpSpreadsheet/Writer/OpenDocument/Settings.php index e7cb9a7c..10ae515c 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/Settings.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/Settings.php @@ -30,8 +30,8 @@ class Settings extends WriterPart * Write settings.xml to XML format * * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function write(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { @@ -51,23 +51,23 @@ class Settings extends WriterPart // Settings $objWriter->startElement('office:document-settings'); - $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); - $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); - $objWriter->writeAttribute('xmlns:config', 'urn:oasis:names:tc:opendocument:xmlns:config:1.0'); - $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); - $objWriter->writeAttribute('office:version', '1.2'); + $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $objWriter->writeAttribute('xmlns:config', 'urn:oasis:names:tc:opendocument:xmlns:config:1.0'); + $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $objWriter->writeAttribute('office:version', '1.2'); - $objWriter->startElement('office:settings'); - $objWriter->startElement('config:config-item-set'); - $objWriter->writeAttribute('config:name', 'ooo:view-settings'); - $objWriter->startElement('config:config-item-map-indexed'); - $objWriter->writeAttribute('config:name', 'Views'); - $objWriter->endElement(); - $objWriter->endElement(); - $objWriter->startElement('config:config-item-set'); - $objWriter->writeAttribute('config:name', 'ooo:configuration-settings'); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->startElement('office:settings'); + $objWriter->startElement('config:config-item-set'); + $objWriter->writeAttribute('config:name', 'ooo:view-settings'); + $objWriter->startElement('config:config-item-map-indexed'); + $objWriter->writeAttribute('config:name', 'Views'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->startElement('config:config-item-set'); + $objWriter->writeAttribute('config:name', 'ooo:configuration-settings'); + $objWriter->endElement(); + $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/Styles.php b/src/PhpSpreadsheet/Writer/OpenDocument/Styles.php index 345ff3da..6c5bcdf1 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/Styles.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/Styles.php @@ -30,8 +30,8 @@ class Styles extends WriterPart * Write styles.xml to XML format * * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function write(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { @@ -51,39 +51,39 @@ class Styles extends WriterPart // Content $objWriter->startElement('office:document-styles'); - $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); - $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); - $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); - $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); - $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); - $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); - $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); - $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); - $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); - $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); - $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); - $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); - $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); - $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); - $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); - $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); - $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); - $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); - $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); - $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); - $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); - $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); - $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); - $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); - $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); - $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); - $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); - $objWriter->writeAttribute('office:version', '1.2'); + $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); + $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); + $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); + $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); + $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); + $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); + $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); + $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); + $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); + $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); + $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); + $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); + $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); + $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); + $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); + $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); + $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); + $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); + $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); + $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); + $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); + $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); + $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); + $objWriter->writeAttribute('office:version', '1.2'); - $objWriter->writeElement('office:font-face-decls'); - $objWriter->writeElement('office:styles'); - $objWriter->writeElement('office:automatic-styles'); - $objWriter->writeElement('office:master-styles'); + $objWriter->writeElement('office:font-face-decls'); + $objWriter->writeElement('office:styles'); + $objWriter->writeElement('office:automatic-styles'); + $objWriter->writeElement('office:master-styles'); $objWriter->endElement(); return $objWriter->getData(); diff --git a/src/PhpSpreadsheet/Writer/OpenDocument/Thumbnails.php b/src/PhpSpreadsheet/Writer/OpenDocument/Thumbnails.php index bc423afd..f92b2808 100644 --- a/src/PhpSpreadsheet/Writer/OpenDocument/Thumbnails.php +++ b/src/PhpSpreadsheet/Writer/OpenDocument/Thumbnails.php @@ -30,8 +30,8 @@ class Thumbnails extends WriterPart * Write Thumbnails/thumbnail.png to PNG format * * @param \PhpSpreadsheet\Spreadsheet $spreadsheet - * @return string XML Output * @throws \PhpSpreadsheet\Writer\Exception + * @return string XML Output */ public function writeThumbnail(\PhpSpreadsheet\SpreadSheet $spreadsheet = null) { diff --git a/src/PhpSpreadsheet/Writer/PDF.php b/src/PhpSpreadsheet/Writer/PDF.php index 842f1b8f..c716d25e 100644 --- a/src/PhpSpreadsheet/Writer/PDF.php +++ b/src/PhpSpreadsheet/Writer/PDF.php @@ -26,7 +26,6 @@ namespace PhpSpreadsheet\Writer; */ class PDF implements IWriter { - /** * The wrapper for the requested PDF rendering engine * @@ -44,12 +43,12 @@ class PDF implements IWriter { $pdfLibraryName = \PhpSpreadsheet\Settings::getPdfRendererName(); if (is_null($pdfLibraryName)) { - throw new Exception("PDF Rendering library has not been defined."); + throw new Exception('PDF Rendering library has not been defined.'); } $pdfLibraryPath = \PhpSpreadsheet\Settings::getPdfRendererPath(); if (is_null($pdfLibraryName)) { - throw new Exception("PDF Rendering library path has not been defined."); + throw new Exception('PDF Rendering library path has not been defined.'); } $includePath = str_replace('\\', '/', get_include_path()); $rendererPath = str_replace('\\', '/', $pdfLibraryPath); @@ -61,7 +60,6 @@ class PDF implements IWriter $this->renderer = new $rendererName($spreadsheet); } - /** * Magic method to handle direct calls to the configured PDF renderer wrapper class. * @@ -72,10 +70,10 @@ class PDF implements IWriter public function __call($name, $arguments) { if ($this->renderer === null) { - throw new Exception("PDF Rendering library has not been defined."); + throw new Exception('PDF Rendering library has not been defined.'); } - return call_user_func_array(array($this->renderer, $name), $arguments); + return call_user_func_array([$this->renderer, $name], $arguments); } /** diff --git a/src/PhpSpreadsheet/Writer/PDF/Core.php b/src/PhpSpreadsheet/Writer/PDF/Core.php index 32f47672..98c34a07 100644 --- a/src/PhpSpreadsheet/Writer/PDF/Core.php +++ b/src/PhpSpreadsheet/Writer/PDF/Core.php @@ -54,7 +54,6 @@ abstract class Core extends \PhpSpreadsheet\Writer\HTML */ protected $paperSize; - /** * Temporary storage for Save Array Return type * @@ -67,140 +66,74 @@ abstract class Core extends \PhpSpreadsheet\Writer\HTML * * @var array */ - protected static $paperSizes = array( - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER - => 'LETTER', // (8.5 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_SMALL - => 'LETTER', // (8.5 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_TABLOID - => array(792.00, 1224.00), // (11 in. by 17 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LEDGER - => array(1224.00, 792.00), // (17 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LEGAL - => 'LEGAL', // (8.5 in. by 14 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STATEMENT - => array(396.00, 612.00), // (5.5 in. by 8.5 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_EXECUTIVE - => 'EXECUTIVE', // (7.25 in. by 10.5 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3 - => 'A3', // (297 mm by 420 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4 - => 'A4', // (210 mm by 297 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_SMALL - => 'A4', // (210 mm by 297 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A5 - => 'A5', // (148 mm by 210 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B4 - => 'B4', // (250 mm by 353 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B5 - => 'B5', // (176 mm by 250 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_FOLIO - => 'FOLIO', // (8.5 in. by 13 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_QUARTO - => array(609.45, 779.53), // (215 mm by 275 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_1 - => array(720.00, 1008.00), // (10 in. by 14 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_2 - => array(792.00, 1224.00), // (11 in. by 17 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NOTE - => 'LETTER', // (8.5 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO9_ENVELOPE - => array(279.00, 639.00), // (3.875 in. by 8.875 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO10_ENVELOPE - => array(297.00, 684.00), // (4.125 in. by 9.5 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO11_ENVELOPE - => array(324.00, 747.00), // (4.5 in. by 10.375 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO12_ENVELOPE - => array(342.00, 792.00), // (4.75 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO14_ENVELOPE - => array(360.00, 828.00), // (5 in. by 11.5 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C - => array(1224.00, 1584.00), // (17 in. by 22 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_D - => array(1584.00, 2448.00), // (22 in. by 34 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_E - => array(2448.00, 3168.00), // (34 in. by 44 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_DL_ENVELOPE - => array(311.81, 623.62), // (110 mm by 220 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C5_ENVELOPE - => 'C5', // (162 mm by 229 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C3_ENVELOPE - => 'C3', // (324 mm by 458 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C4_ENVELOPE - => 'C4', // (229 mm by 324 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C6_ENVELOPE - => 'C6', // (114 mm by 162 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C65_ENVELOPE - => array(323.15, 649.13), // (114 mm by 229 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B4_ENVELOPE - => 'B4', // (250 mm by 353 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B5_ENVELOPE - => 'B5', // (176 mm by 250 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B6_ENVELOPE - => array(498.90, 354.33), // (176 mm by 125 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_ITALY_ENVELOPE - => array(311.81, 651.97), // (110 mm by 230 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_MONARCH_ENVELOPE - => array(279.00, 540.00), // (3.875 in. by 7.5 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_6_3_4_ENVELOPE - => array(261.00, 468.00), // (3.625 in. by 6.5 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_US_STANDARD_FANFOLD - => array(1071.00, 792.00), // (14.875 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD - => array(612.00, 864.00), // (8.5 in. by 12 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD - => 'FOLIO', // (8.5 in. by 13 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_ISO_B4 - => 'B4', // (250 mm by 353 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD - => array(566.93, 419.53), // (200 mm by 148 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_PAPER_1 - => array(648.00, 792.00), // (9 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_PAPER_2 - => array(720.00, 792.00), // (10 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_PAPER_3 - => array(1080.00, 792.00), // (15 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_INVITE_ENVELOPE - => array(623.62, 623.62), // (220 mm by 220 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER - => array(667.80, 864.00), // (9.275 in. by 12 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER - => array(667.80, 1080.00), // (9.275 in. by 15 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER - => array(841.68, 1296.00), // (11.69 in. by 18 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_EXTRA_PAPER - => array(668.98, 912.76), // (236 mm by 322 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER - => array(595.80, 792.00), // (8.275 in. by 11 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER - => 'A4', // (210 mm by 297 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER - => array(667.80, 864.00), // (9.275 in. by 12 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER - => array(643.46, 1009.13), // (227 mm by 356 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER - => array(864.57, 1380.47), // (305 mm by 487 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_PLUS_PAPER - => array(612.00, 913.68), // (8.5 in. by 12.69 in.) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_PLUS_PAPER - => array(595.28, 935.43), // (210 mm by 330 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER - => 'A5', // (148 mm by 210 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER - => array(515.91, 728.50), // (182 mm by 257 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3_EXTRA_PAPER - => array(912.76, 1261.42), // (322 mm by 445 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A5_EXTRA_PAPER - => array(493.23, 666.14), // (174 mm by 235 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER - => array(569.76, 782.36), // (201 mm by 276 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A2_PAPER - => 'A2', // (420 mm by 594 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER - => 'A3', // (297 mm by 420 mm) - \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER - => array(912.76, 1261.42) // (322 mm by 445 mm) - ); + protected static $paperSizes = [ + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER => 'LETTER', // (8.5 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_SMALL => 'LETTER', // (8.5 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_TABLOID => [792.00, 1224.00], // (11 in. by 17 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LEDGER => [1224.00, 792.00], // (17 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LEGAL => 'LEGAL', // (8.5 in. by 14 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STATEMENT => [396.00, 612.00], // (5.5 in. by 8.5 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_EXECUTIVE => 'EXECUTIVE', // (7.25 in. by 10.5 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3 => 'A3', // (297 mm by 420 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4 => 'A4', // (210 mm by 297 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_SMALL => 'A4', // (210 mm by 297 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A5 => 'A5', // (148 mm by 210 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B4 => 'B4', // (250 mm by 353 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B5 => 'B5', // (176 mm by 250 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_FOLIO => 'FOLIO', // (8.5 in. by 13 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_QUARTO => [609.45, 779.53], // (215 mm by 275 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_1 => [720.00, 1008.00], // (10 in. by 14 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_2 => [792.00, 1224.00], // (11 in. by 17 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NOTE => 'LETTER', // (8.5 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO9_ENVELOPE => [279.00, 639.00], // (3.875 in. by 8.875 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO10_ENVELOPE => [297.00, 684.00], // (4.125 in. by 9.5 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO11_ENVELOPE => [324.00, 747.00], // (4.5 in. by 10.375 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO12_ENVELOPE => [342.00, 792.00], // (4.75 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_NO14_ENVELOPE => [360.00, 828.00], // (5 in. by 11.5 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C => [1224.00, 1584.00], // (17 in. by 22 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_D => [1584.00, 2448.00], // (22 in. by 34 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_E => [2448.00, 3168.00], // (34 in. by 44 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_DL_ENVELOPE => [311.81, 623.62], // (110 mm by 220 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C5_ENVELOPE => 'C5', // (162 mm by 229 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C3_ENVELOPE => 'C3', // (324 mm by 458 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C4_ENVELOPE => 'C4', // (229 mm by 324 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C6_ENVELOPE => 'C6', // (114 mm by 162 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_C65_ENVELOPE => [323.15, 649.13], // (114 mm by 229 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B4_ENVELOPE => 'B4', // (250 mm by 353 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B5_ENVELOPE => 'B5', // (176 mm by 250 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_B6_ENVELOPE => [498.90, 354.33], // (176 mm by 125 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_ITALY_ENVELOPE => [311.81, 651.97], // (110 mm by 230 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_MONARCH_ENVELOPE => [279.00, 540.00], // (3.875 in. by 7.5 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_6_3_4_ENVELOPE => [261.00, 468.00], // (3.625 in. by 6.5 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_US_STANDARD_FANFOLD => [1071.00, 792.00], // (14.875 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD => [612.00, 864.00], // (8.5 in. by 12 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD => 'FOLIO', // (8.5 in. by 13 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_ISO_B4 => 'B4', // (250 mm by 353 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD => [566.93, 419.53], // (200 mm by 148 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_PAPER_1 => [648.00, 792.00], // (9 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_PAPER_2 => [720.00, 792.00], // (10 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_STANDARD_PAPER_3 => [1080.00, 792.00], // (15 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_INVITE_ENVELOPE => [623.62, 623.62], // (220 mm by 220 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER => [667.80, 1080.00], // (9.275 in. by 15 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER => [841.68, 1296.00], // (11.69 in. by 18 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_EXTRA_PAPER => [668.98, 912.76], // (236 mm by 322 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER => [595.80, 792.00], // (8.275 in. by 11 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER => 'A4', // (210 mm by 297 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER => [643.46, 1009.13], // (227 mm by 356 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER => [864.57, 1380.47], // (305 mm by 487 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER_PLUS_PAPER => [612.00, 913.68], // (8.5 in. by 12.69 in.) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4_PLUS_PAPER => [595.28, 935.43], // (210 mm by 330 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER => 'A5', // (148 mm by 210 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER => [515.91, 728.50], // (182 mm by 257 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3_EXTRA_PAPER => [912.76, 1261.42], // (322 mm by 445 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A5_EXTRA_PAPER => [493.23, 666.14], // (174 mm by 235 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER => [569.76, 782.36], // (201 mm by 276 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A2_PAPER => 'A2', // (420 mm by 594 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER => 'A3', // (297 mm by 420 mm) + \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER => [912.76, 1261.42], // (322 mm by 445 mm) + ]; /** * Create a new PDF Writer instance @@ -236,6 +169,7 @@ abstract class Core extends \PhpSpreadsheet\Writer\HTML public function setFont($fontName) { $this->font = $fontName; + return $this; } @@ -258,6 +192,7 @@ abstract class Core extends \PhpSpreadsheet\Writer\HTML public function setPaperSize($pValue = \PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER) { $this->paperSize = $pValue; + return $this; } @@ -280,6 +215,7 @@ abstract class Core extends \PhpSpreadsheet\Writer\HTML public function setOrientation($pValue = \PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_DEFAULT) { $this->orientation = $pValue; + return $this; } @@ -307,6 +243,7 @@ abstract class Core extends \PhpSpreadsheet\Writer\HTML } else { throw new \PhpSpreadsheet\Writer\Exception("Directory does not exist: $pValue"); } + return $this; } diff --git a/src/PhpSpreadsheet/Writer/PDF/DomPDF.php b/src/PhpSpreadsheet/Writer/PDF/DomPDF.php index 2b651cc3..f525c4f3 100644 --- a/src/PhpSpreadsheet/Writer/PDF/DomPDF.php +++ b/src/PhpSpreadsheet/Writer/PDF/DomPDF.php @@ -2,7 +2,7 @@ namespace PhpSpreadsheet\Writer\PDF; -/** Require DomPDF library */ +/* Require DomPDF library */ $pdfRendererClassFile = \PhpSpreadsheet\Settings::getPdfRendererPath() . '/dompdf_config.inc.php'; if (file_exists($pdfRendererClassFile)) { require_once $pdfRendererClassFile; @@ -87,9 +87,8 @@ class DomPDF extends Core implements \PhpSpreadsheet\Writer\IWriter $paperSize = self::$paperSizes[$printPaperSize]; } - // Create PDF - $pdf = new DOMPDF(); + $pdf = new self(); $pdf->set_paper(strtolower($paperSize), $orientation); $pdf->load_html( diff --git a/src/PhpSpreadsheet/Writer/PDF/MPDF.php b/src/PhpSpreadsheet/Writer/PDF/MPDF.php index 6bd976f4..fa377a95 100644 --- a/src/PhpSpreadsheet/Writer/PDF/MPDF.php +++ b/src/PhpSpreadsheet/Writer/PDF/MPDF.php @@ -2,7 +2,7 @@ namespace PhpSpreadsheet\Writer\PDF; -/** Require mPDF library */ +/* Require mPDF library */ $pdfRendererClassFile = \PhpSpreadsheet\Settings::getPdfRendererPath() . '/mpdf.php'; if (file_exists($pdfRendererClassFile)) { require_once $pdfRendererClassFile; @@ -88,9 +88,8 @@ class MPDF extends Core implements \PhpSpreadsheet\Writer\IWriter $paperSize = self::$paperSizes[$printPaperSize]; } - // Create PDF - $pdf = new mpdf(); + $pdf = new self(); $ortmp = $orientation; $pdf->_setPageSize(strtoupper($paperSize), $ortmp); $pdf->DefOrientation = $orientation; diff --git a/src/PhpSpreadsheet/Writer/PDF/TcPDF.php b/src/PhpSpreadsheet/Writer/PDF/TcPDF.php index 5aead92e..b8a3855f 100644 --- a/src/PhpSpreadsheet/Writer/PDF/TcPDF.php +++ b/src/PhpSpreadsheet/Writer/PDF/TcPDF.php @@ -2,7 +2,7 @@ namespace PhpSpreadsheet\Writer\PDF; -/** Require tcPDF library */ +/* Require tcPDF library */ $pdfRendererClassFile = \PhpSpreadsheet\Settings::getPdfRendererPath() . '/tcpdf.php'; if (file_exists($pdfRendererClassFile)) { $k_path_url = \PhpSpreadsheet\Settings::getPdfRendererPath(); @@ -86,9 +86,8 @@ class TcPDF extends Core implements \PhpSpreadsheet\Writer\IWriter $paperSize = self::$paperSizes[$printPaperSize]; } - // Create PDF - $pdf = new TCPDF($orientation, 'pt', $paperSize); + $pdf = new self($orientation, 'pt', $paperSize); $pdf->setFontSubsetting(false); // Set margins, converting inches to points (using 72 dpi) $pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72); diff --git a/tests/PhpSpreadsheet/Calculation/DateTimeTest.php b/tests/PhpSpreadsheet/Calculation/DateTimeTest.php index 0372c7ad..9a46cbda 100644 --- a/tests/PhpSpreadsheet/Calculation/DateTimeTest.php +++ b/tests/PhpSpreadsheet/Calculation/DateTimeTest.php @@ -2,16 +2,15 @@ namespace PhpSpreadsheet\Tests\Calculation; -use PhpSpreadsheet\Shared\Date; -use PhpSpreadsheet\Calculation\Functions; use PhpSpreadsheet\Calculation\DateTime; +use PhpSpreadsheet\Calculation\Functions; +use PhpSpreadsheet\Shared\Date; /** * Class DateTimeTest */ class DateTimeTest extends \PHPUnit_Framework_TestCase { - public function setUp() { Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); @@ -24,7 +23,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'DATE'), $args); + $result = call_user_func_array([DateTime::class, 'DATE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -77,7 +76,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'DATEVALUE'), $args); + $result = call_user_func_array([DateTime::class, 'DATEVALUE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -114,7 +113,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'YEAR'), $args); + $result = call_user_func_array([DateTime::class, 'YEAR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -130,7 +129,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'MONTHOFYEAR'), $args); + $result = call_user_func_array([DateTime::class, 'MONTHOFYEAR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -149,7 +148,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'WEEKOFYEAR'), $args); + $result = call_user_func_array([DateTime::class, 'WEEKOFYEAR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -168,7 +167,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'DAYOFWEEK'), $args); + $result = call_user_func_array([DateTime::class, 'DAYOFWEEK'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -184,7 +183,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'DAYOFMONTH'), $args); + $result = call_user_func_array([DateTime::class, 'DAYOFMONTH'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -200,7 +199,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'TIME'), $args); + $result = call_user_func_array([DateTime::class, 'TIME'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -239,7 +238,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'TIMEVALUE'), $args); + $result = call_user_func_array([DateTime::class, 'TIMEVALUE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -278,7 +277,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'HOUROFDAY'), $args); + $result = call_user_func_array([DateTime::class, 'HOUROFDAY'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -296,7 +295,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'MINUTEOFHOUR'), $args); + $result = call_user_func_array([DateTime::class, 'MINUTEOFHOUR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -314,7 +313,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'SECONDOFMINUTE'), $args); + $result = call_user_func_array([DateTime::class, 'SECONDOFMINUTE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -330,7 +329,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'NETWORKDAYS'), $args); + $result = call_user_func_array([DateTime::class, 'NETWORKDAYS'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -346,7 +345,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'WORKDAY'), $args); + $result = call_user_func_array([DateTime::class, 'WORKDAY'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -362,7 +361,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'EDATE'), $args); + $result = call_user_func_array([DateTime::class, 'EDATE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -399,7 +398,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'EOMONTH'), $args); + $result = call_user_func_array([DateTime::class, 'EOMONTH'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -439,7 +438,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'DATEDIF'), $args); + $result = call_user_func_array([DateTime::class, 'DATEDIF'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -455,7 +454,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'DAYS360'), $args); + $result = call_user_func_array([DateTime::class, 'DAYS360'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -474,7 +473,7 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(DateTime::class, 'YEARFRAC'), $args); + $result = call_user_func_array([DateTime::class, 'YEARFRAC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } diff --git a/tests/PhpSpreadsheet/Calculation/EngineeringTest.php b/tests/PhpSpreadsheet/Calculation/EngineeringTest.php index 1bbce265..acf75dfd 100644 --- a/tests/PhpSpreadsheet/Calculation/EngineeringTest.php +++ b/tests/PhpSpreadsheet/Calculation/EngineeringTest.php @@ -7,7 +7,6 @@ use PhpSpreadsheet\Calculation\Functions; class EngineeringTest extends \PHPUnit_Framework_TestCase { - /** * @var \PhpSpreadsheet\Tests\Custom\ComplexAssert */ @@ -31,7 +30,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'BESSELI'), $args); + $result = call_user_func_array([Engineering::class, 'BESSELI'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -47,7 +46,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'BESSELJ'), $args); + $result = call_user_func_array([Engineering::class, 'BESSELJ'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -63,7 +62,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'BESSELK'), $args); + $result = call_user_func_array([Engineering::class, 'BESSELK'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -79,7 +78,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'BESSELY'), $args); + $result = call_user_func_array([Engineering::class, 'BESSELY'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -95,7 +94,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'COMPLEX'), $args); + $result = call_user_func_array([Engineering::class, 'COMPLEX'], $args); $this->assertEquals($expectedResult, $result); } @@ -111,7 +110,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMAGINARY'), $args); + $result = call_user_func_array([Engineering::class, 'IMAGINARY'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -127,7 +126,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMREAL'), $args); + $result = call_user_func_array([Engineering::class, 'IMREAL'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -143,7 +142,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMABS'), $args); + $result = call_user_func_array([Engineering::class, 'IMABS'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -160,7 +159,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMARGUMENT'), $args); + $result = call_user_func_array([Engineering::class, 'IMARGUMENT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -176,7 +175,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMCONJUGATE'), $args); + $result = call_user_func_array([Engineering::class, 'IMCONJUGATE'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -192,7 +191,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMCOS'), $args); + $result = call_user_func_array([Engineering::class, 'IMCOS'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -211,7 +210,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMDIV'), $args); + $result = call_user_func_array([Engineering::class, 'IMDIV'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -227,7 +226,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMEXP'), $args); + $result = call_user_func_array([Engineering::class, 'IMEXP'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -243,7 +242,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMLN'), $args); + $result = call_user_func_array([Engineering::class, 'IMLN'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -259,7 +258,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMLOG2'), $args); + $result = call_user_func_array([Engineering::class, 'IMLOG2'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -275,7 +274,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMLOG10'), $args); + $result = call_user_func_array([Engineering::class, 'IMLOG10'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -294,7 +293,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMPOWER'), $args); + $result = call_user_func_array([Engineering::class, 'IMPOWER'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -310,7 +309,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMPRODUCT'), $args); + $result = call_user_func_array([Engineering::class, 'IMPRODUCT'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -326,7 +325,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMSIN'), $args); + $result = call_user_func_array([Engineering::class, 'IMSIN'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -342,7 +341,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMSQRT'), $args); + $result = call_user_func_array([Engineering::class, 'IMSQRT'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -361,7 +360,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMSUB'), $args); + $result = call_user_func_array([Engineering::class, 'IMSUB'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -378,7 +377,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'IMSUM'), $args); + $result = call_user_func_array([Engineering::class, 'IMSUM'], $args); $this->assertTrue($this->complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $this->complexAssert->getErrorMessage()); } @@ -394,7 +393,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'ERF'), $args); + $result = call_user_func_array([Engineering::class, 'ERF'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -410,7 +409,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'ERFC'), $args); + $result = call_user_func_array([Engineering::class, 'ERFC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -426,7 +425,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'BINTODEC'), $args); + $result = call_user_func_array([Engineering::class, 'BINTODEC'], $args); $this->assertEquals($expectedResult, $result); } @@ -442,7 +441,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'BINTOHEX'), $args); + $result = call_user_func_array([Engineering::class, 'BINTOHEX'], $args); $this->assertEquals($expectedResult, $result); } @@ -458,7 +457,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'BINTOOCT'), $args); + $result = call_user_func_array([Engineering::class, 'BINTOOCT'], $args); $this->assertEquals($expectedResult, $result); } @@ -474,7 +473,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'DECTOBIN'), $args); + $result = call_user_func_array([Engineering::class, 'DECTOBIN'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -490,7 +489,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'DECTOHEX'), $args); + $result = call_user_func_array([Engineering::class, 'DECTOHEX'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -506,7 +505,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'DECTOOCT'), $args); + $result = call_user_func_array([Engineering::class, 'DECTOOCT'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -522,7 +521,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'HEXTOBIN'), $args); + $result = call_user_func_array([Engineering::class, 'HEXTOBIN'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -538,7 +537,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'HEXTODEC'), $args); + $result = call_user_func_array([Engineering::class, 'HEXTODEC'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -554,7 +553,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'HEXTOOCT'), $args); + $result = call_user_func_array([Engineering::class, 'HEXTOOCT'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -570,7 +569,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'OCTTOBIN'), $args); + $result = call_user_func_array([Engineering::class, 'OCTTOBIN'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -586,7 +585,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'OCTTODEC'), $args); + $result = call_user_func_array([Engineering::class, 'OCTTODEC'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -602,7 +601,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'OCTTOHEX'), $args); + $result = call_user_func_array([Engineering::class, 'OCTTOHEX'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -618,7 +617,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'DELTA'), $args); + $result = call_user_func_array([Engineering::class, 'DELTA'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -634,7 +633,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'GESTEP'), $args); + $result = call_user_func_array([Engineering::class, 'GESTEP'], $args); $this->assertEquals($expectedResult, $result, null); } @@ -674,7 +673,7 @@ class EngineeringTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Engineering::class,'CONVERTUOM'), $args); + $result = call_user_func_array([Engineering::class, 'CONVERTUOM'], $args); $this->assertEquals($expectedResult, $result, null); } diff --git a/tests/PhpSpreadsheet/Calculation/FinancialTest.php b/tests/PhpSpreadsheet/Calculation/FinancialTest.php index 28006a54..61b3752c 100644 --- a/tests/PhpSpreadsheet/Calculation/FinancialTest.php +++ b/tests/PhpSpreadsheet/Calculation/FinancialTest.php @@ -7,7 +7,6 @@ use PhpSpreadsheet\Calculation\Functions; class FinancialTest extends \PHPUnit_Framework_TestCase { - public function setUp() { Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); @@ -21,7 +20,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'ACCRINT'), $args); + $result = call_user_func_array([Financial::class, 'ACCRINT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -37,7 +36,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'ACCRINTM'), $args); + $result = call_user_func_array([Financial::class, 'ACCRINTM'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -53,7 +52,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'AMORDEGRC'), $args); + $result = call_user_func_array([Financial::class, 'AMORDEGRC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -69,7 +68,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'AMORLINC'), $args); + $result = call_user_func_array([Financial::class, 'AMORLINC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -85,7 +84,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'COUPDAYBS'), $args); + $result = call_user_func_array([Financial::class, 'COUPDAYBS'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -101,7 +100,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'COUPDAYS'), $args); + $result = call_user_func_array([Financial::class, 'COUPDAYS'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -117,7 +116,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'COUPDAYSNC'), $args); + $result = call_user_func_array([Financial::class, 'COUPDAYSNC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -133,7 +132,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'COUPNCD'), $args); + $result = call_user_func_array([Financial::class, 'COUPNCD'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -149,7 +148,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'COUPNUM'), $args); + $result = call_user_func_array([Financial::class, 'COUPNUM'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -165,7 +164,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'COUPPCD'), $args); + $result = call_user_func_array([Financial::class, 'COUPPCD'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -181,7 +180,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'CUMIPMT'), $args); + $result = call_user_func_array([Financial::class, 'CUMIPMT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -197,7 +196,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'CUMPRINC'), $args); + $result = call_user_func_array([Financial::class, 'CUMPRINC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -213,7 +212,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'DB'), $args); + $result = call_user_func_array([Financial::class, 'DB'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -229,7 +228,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'DDB'), $args); + $result = call_user_func_array([Financial::class, 'DDB'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -245,7 +244,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'DISC'), $args); + $result = call_user_func_array([Financial::class, 'DISC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -261,7 +260,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'DOLLARDE'), $args); + $result = call_user_func_array([Financial::class, 'DOLLARDE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -277,7 +276,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'DOLLARFR'), $args); + $result = call_user_func_array([Financial::class, 'DOLLARFR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -293,7 +292,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'EFFECT'), $args); + $result = call_user_func_array([Financial::class, 'EFFECT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -309,7 +308,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'FV'), $args); + $result = call_user_func_array([Financial::class, 'FV'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -325,7 +324,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'FVSCHEDULE'), $args); + $result = call_user_func_array([Financial::class, 'FVSCHEDULE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -341,7 +340,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'INTRATE'), $args); + $result = call_user_func_array([Financial::class, 'INTRATE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -357,7 +356,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'IPMT'), $args); + $result = call_user_func_array([Financial::class, 'IPMT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -373,7 +372,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'IRR'), $args); + $result = call_user_func_array([Financial::class, 'IRR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -389,7 +388,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'ISPMT'), $args); + $result = call_user_func_array([Financial::class, 'ISPMT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -405,7 +404,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'MIRR'), $args); + $result = call_user_func_array([Financial::class, 'MIRR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -421,7 +420,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'NOMINAL'), $args); + $result = call_user_func_array([Financial::class, 'NOMINAL'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -437,7 +436,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'NPER'), $args); + $result = call_user_func_array([Financial::class, 'NPER'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -453,7 +452,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'NPV'), $args); + $result = call_user_func_array([Financial::class, 'NPV'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -472,7 +471,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'PRICE'), $args); + $result = call_user_func_array([Financial::class, 'PRICE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -491,7 +490,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'RATE'), $args); + $result = call_user_func_array([Financial::class, 'RATE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -510,7 +509,7 @@ class FinancialTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Financial::class,'XIRR'), $args); + $result = call_user_func_array([Financial::class, 'XIRR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } diff --git a/tests/PhpSpreadsheet/Calculation/FunctionsTest.php b/tests/PhpSpreadsheet/Calculation/FunctionsTest.php index 3303c183..e21b236b 100644 --- a/tests/PhpSpreadsheet/Calculation/FunctionsTest.php +++ b/tests/PhpSpreadsheet/Calculation/FunctionsTest.php @@ -6,7 +6,6 @@ use PhpSpreadsheet\Calculation\Functions; class FunctionsTest extends \PHPUnit_Framework_TestCase { - public function setUp() { Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); @@ -67,7 +66,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isBlank'), $args); + $result = call_user_func_array([Functions::class, 'isBlank'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -83,7 +82,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isErr'), $args); + $result = call_user_func_array([Functions::class, 'isErr'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -99,7 +98,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isError'), $args); + $result = call_user_func_array([Functions::class, 'isError'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -115,7 +114,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'errorType'), $args); + $result = call_user_func_array([Functions::class, 'errorType'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -131,7 +130,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isLogical'), $args); + $result = call_user_func_array([Functions::class, 'isLogical'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -147,7 +146,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isNa'), $args); + $result = call_user_func_array([Functions::class, 'isNa'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -163,7 +162,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isNumber'), $args); + $result = call_user_func_array([Functions::class, 'isNumber'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -179,7 +178,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isText'), $args); + $result = call_user_func_array([Functions::class, 'isText'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -195,7 +194,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isNonText'), $args); + $result = call_user_func_array([Functions::class, 'isNonText'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -211,7 +210,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isEven'), $args); + $result = call_user_func_array([Functions::class, 'isEven'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -227,7 +226,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'isOdd'), $args); + $result = call_user_func_array([Functions::class, 'isOdd'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -243,7 +242,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'TYPE'), $args); + $result = call_user_func_array([Functions::class, 'TYPE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } @@ -259,7 +258,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Functions::class,'n'), $args); + $result = call_user_func_array([Functions::class, 'n'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } diff --git a/tests/PhpSpreadsheet/Calculation/LogicalTest.php b/tests/PhpSpreadsheet/Calculation/LogicalTest.php index 5cad07ac..7ad5256c 100644 --- a/tests/PhpSpreadsheet/Calculation/LogicalTest.php +++ b/tests/PhpSpreadsheet/Calculation/LogicalTest.php @@ -7,7 +7,6 @@ use PhpSpreadsheet\Calculation\Logical; class LogicalTest extends \PHPUnit_Framework_TestCase { - public function setUp() { Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); @@ -16,13 +15,13 @@ class LogicalTest extends \PHPUnit_Framework_TestCase public function testTRUE() { $result = Logical::TRUE(); - $this->assertEquals(true, $result); + $this->assertTrue($result); } public function testFALSE() { $result = Logical::FALSE(); - $this->assertEquals(false, $result); + $this->assertFalse($result); } /** @@ -32,7 +31,7 @@ class LogicalTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Logical::class,'logicalAnd'), $args); + $result = call_user_func_array([Logical::class, 'logicalAnd'], $args); $this->assertEquals($expectedResult, $result); } @@ -48,7 +47,7 @@ class LogicalTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Logical::class,'logicalOr'), $args); + $result = call_user_func_array([Logical::class, 'logicalOr'], $args); $this->assertEquals($expectedResult, $result); } @@ -64,7 +63,7 @@ class LogicalTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Logical::class,'NOT'), $args); + $result = call_user_func_array([Logical::class, 'NOT'], $args); $this->assertEquals($expectedResult, $result); } @@ -80,7 +79,7 @@ class LogicalTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Logical::class,'statementIf'), $args); + $result = call_user_func_array([Logical::class, 'statementIf'], $args); $this->assertEquals($expectedResult, $result); } @@ -96,7 +95,7 @@ class LogicalTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Logical::class,'IFERROR'), $args); + $result = call_user_func_array([Logical::class, 'IFERROR'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Calculation/LookupRefTest.php b/tests/PhpSpreadsheet/Calculation/LookupRefTest.php index 29fbaea4..20574732 100644 --- a/tests/PhpSpreadsheet/Calculation/LookupRefTest.php +++ b/tests/PhpSpreadsheet/Calculation/LookupRefTest.php @@ -10,7 +10,6 @@ use PhpSpreadsheet\Calculation\LookupRef; */ class LookupRefTest extends \PHPUnit_Framework_TestCase { - public function setUp() { Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); @@ -24,7 +23,7 @@ class LookupRefTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(LookupRef::class,'HLOOKUP'), $args); + $result = call_user_func_array([LookupRef::class, 'HLOOKUP'], $args); $this->assertEquals($expectedResult, $result); } @@ -41,7 +40,7 @@ class LookupRefTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(LookupRef::class,'VLOOKUP'), $args); + $result = call_user_func_array([LookupRef::class, 'VLOOKUP'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Calculation/MathTrigTest.php b/tests/PhpSpreadsheet/Calculation/MathTrigTest.php index 0cfb1f4d..ed017e81 100644 --- a/tests/PhpSpreadsheet/Calculation/MathTrigTest.php +++ b/tests/PhpSpreadsheet/Calculation/MathTrigTest.php @@ -8,7 +8,6 @@ use PhpSpreadsheet\Calculation\MathTrig; class MathTrigTest extends \PHPUnit_Framework_TestCase { - public function setUp() { Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); @@ -21,7 +20,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'ATAN2'), $args); + $result = call_user_func_array([MathTrig::class, 'ATAN2'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -37,7 +36,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'CEILING'), $args); + $result = call_user_func_array([MathTrig::class, 'CEILING'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -53,7 +52,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'COMBIN'), $args); + $result = call_user_func_array([MathTrig::class, 'COMBIN'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -69,7 +68,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'EVEN'), $args); + $result = call_user_func_array([MathTrig::class, 'EVEN'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -85,7 +84,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'ODD'), $args); + $result = call_user_func_array([MathTrig::class, 'ODD'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -101,7 +100,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'FACT'), $args); + $result = call_user_func_array([MathTrig::class, 'FACT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -117,7 +116,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'FACTDOUBLE'), $args); + $result = call_user_func_array([MathTrig::class, 'FACTDOUBLE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -133,7 +132,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'FLOOR'), $args); + $result = call_user_func_array([MathTrig::class, 'FLOOR'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -149,7 +148,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'GCD'), $args); + $result = call_user_func_array([MathTrig::class, 'GCD'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -165,7 +164,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'LCM'), $args); + $result = call_user_func_array([MathTrig::class, 'LCM'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -181,7 +180,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'INT'), $args); + $result = call_user_func_array([MathTrig::class, 'INT'], $args); $this->assertEquals($expectedResult, $result); } @@ -197,7 +196,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'SIGN'), $args); + $result = call_user_func_array([MathTrig::class, 'SIGN'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -213,7 +212,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'POWER'), $args); + $result = call_user_func_array([MathTrig::class, 'POWER'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -229,7 +228,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'logBase'), $args); + $result = call_user_func_array([MathTrig::class, 'logBase'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -245,7 +244,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'MOD'), $args); + $result = call_user_func_array([MathTrig::class, 'MOD'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -264,7 +263,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'MDETERM'), $args); + $result = call_user_func_array([MathTrig::class, 'MDETERM'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -283,7 +282,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'MINVERSE'), $args); + $result = call_user_func_array([MathTrig::class, 'MINVERSE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -302,7 +301,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'MMULT'), $args); + $result = call_user_func_array([MathTrig::class, 'MMULT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -318,7 +317,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'MULTINOMIAL'), $args); + $result = call_user_func_array([MathTrig::class, 'MULTINOMIAL'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -335,7 +334,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); - $result = call_user_func_array(array(MathTrig::class,'MROUND'), $args); + $result = call_user_func_array([MathTrig::class, 'MROUND'], $args); Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -352,7 +351,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'PRODUCT'), $args); + $result = call_user_func_array([MathTrig::class, 'PRODUCT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -368,7 +367,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'QUOTIENT'), $args); + $result = call_user_func_array([MathTrig::class, 'QUOTIENT'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -384,7 +383,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'ROUNDUP'), $args); + $result = call_user_func_array([MathTrig::class, 'ROUNDUP'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -400,7 +399,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'ROUNDDOWN'), $args); + $result = call_user_func_array([MathTrig::class, 'ROUNDDOWN'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -416,7 +415,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'SERIESSUM'), $args); + $result = call_user_func_array([MathTrig::class, 'SERIESSUM'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -432,7 +431,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'SUMSQ'), $args); + $result = call_user_func_array([MathTrig::class, 'SUMSQ'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -448,7 +447,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'TRUNC'), $args); + $result = call_user_func_array([MathTrig::class, 'TRUNC'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -464,7 +463,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'ROMAN'), $args); + $result = call_user_func_array([MathTrig::class, 'ROMAN'], $args); $this->assertEquals($expectedResult, $result); } @@ -480,7 +479,7 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class,'SQRTPI'), $args); + $result = call_user_func_array([MathTrig::class, 'SQRTPI'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } @@ -496,70 +495,70 @@ class MathTrigTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(MathTrig::class, 'SUMIF'), $args); + $result = call_user_func_array([MathTrig::class, 'SUMIF'], $args); $this->assertEquals($expectedResult, $result, null, 1E-12); } public function providerSUMIF() { - return array( - array( - array( - array(1), - array(5), - array(10), - ), + return [ + [ + [ + [1], + [5], + [10], + ], '>=5', 15, - ), - array( - array( - array('text'), - array(2), - ), + ], + [ + [ + ['text'], + [2], + ], '=text', - array( - array(10), - array(100), - ), + [ + [10], + [100], + ], 10, - ), - array( - array( - array('"text with quotes"'), - array(2), - ), + ], + [ + [ + ['"text with quotes"'], + [2], + ], '="text with quotes"', - array( - array(10), - array(100), - ), + [ + [10], + [100], + ], 10, - ), - array( - array( - array('"text with quotes"'), - array(''), - ), + ], + [ + [ + ['"text with quotes"'], + [''], + ], '>"', // Compare to the single characater " (double quote) - array( - array(10), - array(100), - ), - 10 - ), - array( - array( - array(''), - array('anything'), - ), + [ + [10], + [100], + ], + 10, + ], + [ + [ + [''], + ['anything'], + ], '>"', // Compare to the single characater " (double quote) - array( - array(10), - array(100), - ), - 100 - ), - ); + [ + [10], + [100], + ], + 100, + ], + ]; } } diff --git a/tests/PhpSpreadsheet/Calculation/TextDataTest.php b/tests/PhpSpreadsheet/Calculation/TextDataTest.php index 98251999..51de92b4 100644 --- a/tests/PhpSpreadsheet/Calculation/TextDataTest.php +++ b/tests/PhpSpreadsheet/Calculation/TextDataTest.php @@ -2,13 +2,12 @@ namespace PhpSpreadsheet\Tests\Calculation; -use PhpSpreadsheet\Shared\StringHelper; use PhpSpreadsheet\Calculation\Functions; use PhpSpreadsheet\Calculation\TextData; +use PhpSpreadsheet\Shared\StringHelper; class TextDataTest extends \PHPUnit_Framework_TestCase { - public function setUp() { Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); @@ -21,7 +20,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'CHARACTER'), $args); + $result = call_user_func_array([TextData::class, 'CHARACTER'], $args); $this->assertEquals($expectedResult, $result); } @@ -37,7 +36,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'ASCIICODE'), $args); + $result = call_user_func_array([TextData::class, 'ASCIICODE'], $args); $this->assertEquals($expectedResult, $result); } @@ -53,7 +52,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'CONCATENATE'), $args); + $result = call_user_func_array([TextData::class, 'CONCATENATE'], $args); $this->assertEquals($expectedResult, $result); } @@ -69,7 +68,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'LEFT'), $args); + $result = call_user_func_array([TextData::class, 'LEFT'], $args); $this->assertEquals($expectedResult, $result); } @@ -85,7 +84,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'MID'), $args); + $result = call_user_func_array([TextData::class, 'MID'], $args); $this->assertEquals($expectedResult, $result); } @@ -101,7 +100,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'RIGHT'), $args); + $result = call_user_func_array([TextData::class, 'RIGHT'], $args); $this->assertEquals($expectedResult, $result); } @@ -117,7 +116,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'LOWERCASE'), $args); + $result = call_user_func_array([TextData::class, 'LOWERCASE'], $args); $this->assertEquals($expectedResult, $result); } @@ -133,7 +132,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'UPPERCASE'), $args); + $result = call_user_func_array([TextData::class, 'UPPERCASE'], $args); $this->assertEquals($expectedResult, $result); } @@ -149,7 +148,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'PROPERCASE'), $args); + $result = call_user_func_array([TextData::class, 'PROPERCASE'], $args); $this->assertEquals($expectedResult, $result); } @@ -165,7 +164,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'STRINGLENGTH'), $args); + $result = call_user_func_array([TextData::class, 'STRINGLENGTH'], $args); $this->assertEquals($expectedResult, $result); } @@ -181,7 +180,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'SEARCHINSENSITIVE'), $args); + $result = call_user_func_array([TextData::class, 'SEARCHINSENSITIVE'], $args); $this->assertEquals($expectedResult, $result); } @@ -197,7 +196,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'SEARCHSENSITIVE'), $args); + $result = call_user_func_array([TextData::class, 'SEARCHSENSITIVE'], $args); $this->assertEquals($expectedResult, $result); } @@ -213,7 +212,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'REPLACE'), $args); + $result = call_user_func_array([TextData::class, 'REPLACE'], $args); $this->assertEquals($expectedResult, $result); } @@ -229,7 +228,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'SUBSTITUTE'), $args); + $result = call_user_func_array([TextData::class, 'SUBSTITUTE'], $args); $this->assertEquals($expectedResult, $result); } @@ -245,7 +244,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'TRIMSPACES'), $args); + $result = call_user_func_array([TextData::class, 'TRIMSPACES'], $args); $this->assertEquals($expectedResult, $result); } @@ -261,7 +260,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'TRIMNONPRINTABLE'), $args); + $result = call_user_func_array([TextData::class, 'TRIMNONPRINTABLE'], $args); $this->assertEquals($expectedResult, $result); } @@ -277,7 +276,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'DOLLAR'), $args); + $result = call_user_func_array([TextData::class, 'DOLLAR'], $args); $this->assertEquals($expectedResult, $result); } @@ -293,7 +292,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'FIXEDFORMAT'), $args); + $result = call_user_func_array([TextData::class, 'FIXEDFORMAT'], $args); $this->assertEquals($expectedResult, $result); } @@ -309,7 +308,7 @@ class TextDataTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class,'RETURNSTRING'), $args); + $result = call_user_func_array([TextData::class, 'RETURNSTRING'], $args); $this->assertEquals($expectedResult, $result); } @@ -324,13 +323,13 @@ class TextDataTest extends \PHPUnit_Framework_TestCase public function testTEXT() { // Enforce decimal and thousands separator values to UK/US, and currency code to USD - call_user_func(array(StringHelper::class, 'setDecimalSeparator'), '.'); - call_user_func(array(StringHelper::class, 'setThousandsSeparator'), ','); - call_user_func(array(StringHelper::class, 'setCurrencyCode'), '$'); + call_user_func([StringHelper::class, 'setDecimalSeparator'], '.'); + call_user_func([StringHelper::class, 'setThousandsSeparator'], ','); + call_user_func([StringHelper::class, 'setCurrencyCode'], '$'); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class, 'TEXTFORMAT'), $args); + $result = call_user_func_array([TextData::class, 'TEXTFORMAT'], $args); $this->assertEquals($expectedResult, $result); } @@ -344,13 +343,13 @@ class TextDataTest extends \PHPUnit_Framework_TestCase */ public function testVALUE() { - call_user_func(array(StringHelper::class, 'setDecimalSeparator'), '.'); - call_user_func(array(StringHelper::class, 'setThousandsSeparator'), ' '); - call_user_func(array(StringHelper::class, 'setCurrencyCode'), '$'); + call_user_func([StringHelper::class, 'setDecimalSeparator'], '.'); + call_user_func([StringHelper::class, 'setThousandsSeparator'], ' '); + call_user_func([StringHelper::class, 'setCurrencyCode'], '$'); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(TextData::class, 'VALUE'), $args); + $result = call_user_func_array([TextData::class, 'VALUE'], $args); $this->assertEquals($expectedResult, $result, null, 1E-8); } diff --git a/tests/PhpSpreadsheet/Cell/AdvancedValueBinderTest.php b/tests/PhpSpreadsheet/Cell/AdvancedValueBinderTest.php index 86e4e8f3..eec39ba4 100644 --- a/tests/PhpSpreadsheet/Cell/AdvancedValueBinderTest.php +++ b/tests/PhpSpreadsheet/Cell/AdvancedValueBinderTest.php @@ -2,13 +2,13 @@ namespace PhpSpreadsheet\Tests\Cell; -use PhpSpreadsheet\Worksheet; -use PhpSpreadsheet\Style\NumberFormat; -use PhpSpreadsheet\Shared\StringHelper; +use PhpSpreadsheet\CachedObjectStorage\Memory; use PhpSpreadsheet\Cell; use PhpSpreadsheet\Cell\AdvancedValueBinder; use PhpSpreadsheet\Cell\DataType; -use PhpSpreadsheet\CachedObjectStorage\Memory; +use PhpSpreadsheet\Shared\StringHelper; +use PhpSpreadsheet\Style\NumberFormat; +use PhpSpreadsheet\Worksheet; class AdvancedValueBinderTest extends \PHPUnit_Framework_TestCase { @@ -17,7 +17,7 @@ class AdvancedValueBinderTest extends \PHPUnit_Framework_TestCase if (!defined('PHPSPREADSHEET_ROOT')) { define('PHPSPREADSHEET_ROOT', APPLICATION_PATH . '/'); } - require_once(PHPSPREADSHEET_ROOT . '/Bootstrap.php'); + require_once PHPSPREADSHEET_ROOT . '/Bootstrap.php'; } public function provider() @@ -28,16 +28,16 @@ class AdvancedValueBinderTest extends \PHPUnit_Framework_TestCase $currencyUSD = NumberFormat::FORMAT_CURRENCY_USD_SIMPLE; $currencyEURO = str_replace('$', '€', NumberFormat::FORMAT_CURRENCY_USD_SIMPLE); - return array( - array('10%', 0.1, NumberFormat::FORMAT_PERCENTAGE_00, ',', '.', '$'), - array('$10.11', 10.11, $currencyUSD, ',', '.', '$'), - array('$1,010.12', 1010.12, $currencyUSD, ',', '.', '$'), - array('$20,20', 20.2, $currencyUSD, '.', ',', '$'), - array('$2.020,20', 2020.2, $currencyUSD, '.', ',', '$'), - array('€2.020,20', 2020.2, $currencyEURO, '.', ',', '€'), - array('€ 2.020,20', 2020.2, $currencyEURO, '.', ',', '€'), - array('€2,020.22', 2020.22, $currencyEURO, ',', '.', '€'), - ); + return [ + ['10%', 0.1, NumberFormat::FORMAT_PERCENTAGE_00, ',', '.', '$'], + ['$10.11', 10.11, $currencyUSD, ',', '.', '$'], + ['$1,010.12', 1010.12, $currencyUSD, ',', '.', '$'], + ['$20,20', 20.2, $currencyUSD, '.', ',', '$'], + ['$2.020,20', 2020.2, $currencyUSD, '.', ',', '$'], + ['€2.020,20', 2020.2, $currencyEURO, '.', ',', '€'], + ['€ 2.020,20', 2020.2, $currencyEURO, '.', ',', '€'], + ['€2,020.22', 2020.22, $currencyEURO, ',', '.', '€'], + ]; } /** @@ -47,7 +47,7 @@ class AdvancedValueBinderTest extends \PHPUnit_Framework_TestCase { $sheet = $this->getMock( Worksheet::class, - array('getStyle', 'getNumberFormat', 'setFormatCode','getCellCacheController') + ['getStyle', 'getNumberFormat', 'setFormatCode', 'getCellCacheController'] ); $cache = $this->getMockBuilder(Memory::class) ->disableOriginalConstructor() diff --git a/tests/PhpSpreadsheet/Cell/DataTypeTest.php b/tests/PhpSpreadsheet/Cell/DataTypeTest.php index 98c342b5..932ba859 100644 --- a/tests/PhpSpreadsheet/Cell/DataTypeTest.php +++ b/tests/PhpSpreadsheet/Cell/DataTypeTest.php @@ -6,18 +6,17 @@ use PhpSpreadsheet\Cell\DataType; class DataTypeTest extends \PHPUnit_Framework_TestCase { - public function setUp() { if (!defined('PHPSPREADSHEET_ROOT')) { define('PHPSPREADSHEET_ROOT', APPLICATION_PATH . '/'); } - require_once(PHPSPREADSHEET_ROOT . '/Bootstrap.php'); + require_once PHPSPREADSHEET_ROOT . '/Bootstrap.php'; } public function testGetErrorCodes() { - $result = call_user_func(array(DataType::class,'getErrorCodes')); + $result = call_user_func([DataType::class, 'getErrorCodes']); $this->assertInternalType('array', $result); $this->assertGreaterThan(0, count($result)); $this->assertArrayHasKey('#NULL!', $result); diff --git a/tests/PhpSpreadsheet/Cell/DefaultValueBinderTest.php b/tests/PhpSpreadsheet/Cell/DefaultValueBinderTest.php index 54595e96..d5db5d62 100644 --- a/tests/PhpSpreadsheet/Cell/DefaultValueBinderTest.php +++ b/tests/PhpSpreadsheet/Cell/DefaultValueBinderTest.php @@ -2,10 +2,10 @@ namespace PhpSpreadsheet\Tests\Cell; -use PhpSpreadsheet\Cell\DefaultValueBinder; use PhpSpreadsheet\Cell; -use PhpSpreadsheet\RichText; use PhpSpreadsheet\Cell\DataType; +use PhpSpreadsheet\Cell\DefaultValueBinder; +use PhpSpreadsheet\RichText; class DefaultValueBinderTest extends \PHPUnit_Framework_TestCase { @@ -16,7 +16,7 @@ class DefaultValueBinderTest extends \PHPUnit_Framework_TestCase if (!defined('PHPSPREADSHEET_ROOT')) { define('PHPSPREADSHEET_ROOT', APPLICATION_PATH . '/'); } - require_once(PHPSPREADSHEET_ROOT . '/Bootstrap.php'); + require_once PHPSPREADSHEET_ROOT . '/Bootstrap.php'; } protected function createCellStub() @@ -44,20 +44,20 @@ class DefaultValueBinderTest extends \PHPUnit_Framework_TestCase public function binderProvider() { - return array( - array(null), - array(''), - array('ABC'), - array('=SUM(A1:B2)'), - array(true), - array(false), - array(123), - array(-123.456), - array('123'), - array('-123.456'), - array('#REF!'), - array(new \DateTime()), - ); + return [ + [null], + [''], + ['ABC'], + ['=SUM(A1:B2)'], + [true], + [false], + [123], + [-123.456], + ['123'], + ['-123.456'], + ['#REF!'], + [new \DateTime()], + ]; } /** @@ -66,7 +66,7 @@ class DefaultValueBinderTest extends \PHPUnit_Framework_TestCase public function testDataTypeForValue() { list($args, $expectedResult) = func_get_args(); - $result = call_user_func_array(array(DefaultValueBinder::class,'dataTypeForValue'), $args); + $result = call_user_func_array([DefaultValueBinder::class, 'dataTypeForValue'], $args); $this->assertEquals($expectedResult, $result); } @@ -81,7 +81,7 @@ class DefaultValueBinderTest extends \PHPUnit_Framework_TestCase $objRichText->createText('Hello World'); $expectedResult = DataType::TYPE_INLINE; - $result = call_user_func(array(DefaultValueBinder::class,'dataTypeForValue'), $objRichText); + $result = call_user_func([DefaultValueBinder::class, 'dataTypeForValue'], $objRichText); $this->assertEquals($expectedResult, $result); } } diff --git a/tests/PhpSpreadsheet/Cell/HyperlinkTest.php b/tests/PhpSpreadsheet/Cell/HyperlinkTest.php index 9c812a57..d3b51271 100644 --- a/tests/PhpSpreadsheet/Cell/HyperlinkTest.php +++ b/tests/PhpSpreadsheet/Cell/HyperlinkTest.php @@ -6,13 +6,12 @@ use PhpSpreadsheet\Cell\Hyperlink; class HyperlinkTest extends \PHPUnit_Framework_TestCase { - public function setUp() { if (!defined('PHPSPREADSHEET_ROOT')) { define('PHPSPREADSHEET_ROOT', APPLICATION_PATH . '/'); } - require_once(PHPSPREADSHEET_ROOT . '/Bootstrap.php'); + require_once PHPSPREADSHEET_ROOT . '/Bootstrap.php'; } public function testGetUrl() diff --git a/tests/PhpSpreadsheet/CellTest.php b/tests/PhpSpreadsheet/CellTest.php index a8083715..5f8d1749 100644 --- a/tests/PhpSpreadsheet/CellTest.php +++ b/tests/PhpSpreadsheet/CellTest.php @@ -14,7 +14,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'columnIndexFromString'), $args); + $result = call_user_func_array([Cell::class, 'columnIndexFromString'], $args); $this->assertEquals($expectedResult, $result); } @@ -27,10 +27,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellAddress = 'ABCD'; try { - $result = call_user_func(array(Cell::class,'columnIndexFromString'), $cellAddress); + $result = call_user_func([Cell::class, 'columnIndexFromString'], $cellAddress); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); $this->assertEquals($e->getMessage(), 'Column string index can not be longer than 3 characters'); + return; } $this->fail('An expected exception has not been raised.'); @@ -40,10 +41,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellAddress = ''; try { - $result = call_user_func(array(Cell::class,'columnIndexFromString'), $cellAddress); + $result = call_user_func([Cell::class, 'columnIndexFromString'], $cellAddress); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); $this->assertEquals($e->getMessage(), 'Column string index can not be empty'); + return; } $this->fail('An expected exception has not been raised.'); @@ -56,7 +58,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'stringFromColumnIndex'), $args); + $result = call_user_func_array([Cell::class, 'stringFromColumnIndex'], $args); $this->assertEquals($expectedResult, $result); } @@ -72,7 +74,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'coordinateFromString'), $args); + $result = call_user_func_array([Cell::class, 'coordinateFromString'], $args); $this->assertEquals($expectedResult, $result); } @@ -85,10 +87,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellAddress = 'A1:AI2012'; try { - $result = call_user_func(array(Cell::class,'coordinateFromString'), $cellAddress); + $result = call_user_func([Cell::class, 'coordinateFromString'], $cellAddress); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells'); + return; } $this->fail('An expected exception has not been raised.'); @@ -98,10 +101,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellAddress = ''; try { - $result = call_user_func(array(Cell::class,'coordinateFromString'), $cellAddress); + $result = call_user_func([Cell::class, 'coordinateFromString'], $cellAddress); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); $this->assertEquals($e->getMessage(), 'Cell coordinate can not be zero-length string'); + return; } $this->fail('An expected exception has not been raised.'); @@ -111,10 +115,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellAddress = 'AI'; try { - $result = call_user_func(array(Cell::class,'coordinateFromString'), $cellAddress); + $result = call_user_func([Cell::class, 'coordinateFromString'], $cellAddress); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); - $this->assertEquals($e->getMessage(), 'Invalid cell coordinate '.$cellAddress); + $this->assertEquals($e->getMessage(), 'Invalid cell coordinate ' . $cellAddress); + return; } $this->fail('An expected exception has not been raised.'); @@ -127,7 +132,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'absoluteCoordinate'), $args); + $result = call_user_func_array([Cell::class, 'absoluteCoordinate'], $args); $this->assertEquals($expectedResult, $result); } @@ -140,10 +145,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellAddress = 'A1:AI2012'; try { - $result = call_user_func(array(Cell::class,'absoluteCoordinate'), $cellAddress); + $result = call_user_func([Cell::class, 'absoluteCoordinate'], $cellAddress); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells'); + return; } $this->fail('An expected exception has not been raised.'); @@ -156,7 +162,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'absoluteReference'), $args); + $result = call_user_func_array([Cell::class, 'absoluteReference'], $args); $this->assertEquals($expectedResult, $result); } @@ -169,10 +175,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellAddress = 'A1:AI2012'; try { - $result = call_user_func(array(Cell::class,'absoluteReference'), $cellAddress); + $result = call_user_func([Cell::class, 'absoluteReference'], $cellAddress); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells'); + return; } $this->fail('An expected exception has not been raised.'); @@ -185,7 +192,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'splitRange'), $args); + $result = call_user_func_array([Cell::class, 'splitRange'], $args); foreach ($result as $key => $split) { if (!is_array($expectedResult[$key])) { $this->assertEquals($expectedResult[$key], $split[0]); @@ -207,7 +214,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'buildRange'), $args); + $result = call_user_func_array([Cell::class, 'buildRange'], $args); $this->assertEquals($expectedResult, $result); } @@ -220,10 +227,11 @@ class CellTest extends \PHPUnit_Framework_TestCase { $cellRange = ''; try { - $result = call_user_func(array(Cell::class,'buildRange'), $cellRange); + $result = call_user_func([Cell::class, 'buildRange'], $cellRange); } catch (\Exception $e) { $this->assertInstanceOf(Exception::class, $e); $this->assertEquals($e->getMessage(), 'Range does not contain any information'); + return; } $this->fail('An expected exception has not been raised.'); @@ -236,7 +244,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'rangeBoundaries'), $args); + $result = call_user_func_array([Cell::class, 'rangeBoundaries'], $args); $this->assertEquals($expectedResult, $result); } @@ -252,7 +260,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'rangeDimension'), $args); + $result = call_user_func_array([Cell::class, 'rangeDimension'], $args); $this->assertEquals($expectedResult, $result); } @@ -268,7 +276,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'getRangeBoundaries'), $args); + $result = call_user_func_array([Cell::class, 'getRangeBoundaries'], $args); $this->assertEquals($expectedResult, $result); } @@ -284,7 +292,7 @@ class CellTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Cell::class,'extractAllCellReferencesInRange'), $args); + $result = call_user_func_array([Cell::class, 'extractAllCellReferencesInRange'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Chart/DataSeriesValuesTest.php b/tests/PhpSpreadsheet/Chart/DataSeriesValuesTest.php index b0fbdde1..7765cc86 100644 --- a/tests/PhpSpreadsheet/Chart/DataSeriesValuesTest.php +++ b/tests/PhpSpreadsheet/Chart/DataSeriesValuesTest.php @@ -9,12 +9,12 @@ class DataSeriesValuesTest extends \PHPUnit_Framework_TestCase { public function testSetDataType() { - $dataTypeValues = array( + $dataTypeValues = [ 'Number', - 'String' - ); + 'String', + ]; - $testInstance = new DataSeriesValues; + $testInstance = new DataSeriesValues(); foreach ($dataTypeValues as $dataTypeValue) { $result = $testInstance->setDataType($dataTypeValue); @@ -24,12 +24,13 @@ class DataSeriesValuesTest extends \PHPUnit_Framework_TestCase public function testSetInvalidDataTypeThrowsException() { - $testInstance = new DataSeriesValues; + $testInstance = new DataSeriesValues(); try { $result = $testInstance->setDataType('BOOLEAN'); } catch (Exception $e) { $this->assertEquals($e->getMessage(), 'Invalid datatype for chart data series values'); + return; } $this->fail('An expected exception has not been raised.'); @@ -39,7 +40,7 @@ class DataSeriesValuesTest extends \PHPUnit_Framework_TestCase { $dataTypeValue = 'String'; - $testInstance = new DataSeriesValues; + $testInstance = new DataSeriesValues(); $setValue = $testInstance->setDataType($dataTypeValue); $result = $testInstance->getDataType(); diff --git a/tests/PhpSpreadsheet/Chart/LayoutTest.php b/tests/PhpSpreadsheet/Chart/LayoutTest.php index 1659021f..03432592 100644 --- a/tests/PhpSpreadsheet/Chart/LayoutTest.php +++ b/tests/PhpSpreadsheet/Chart/LayoutTest.php @@ -10,7 +10,7 @@ class LayoutTest extends \PHPUnit_Framework_TestCase { $LayoutTargetValue = 'String'; - $testInstance = new Layout; + $testInstance = new Layout(); $result = $testInstance->setLayoutTarget($LayoutTargetValue); $this->assertTrue($result instanceof Layout); @@ -20,7 +20,7 @@ class LayoutTest extends \PHPUnit_Framework_TestCase { $LayoutTargetValue = 'String'; - $testInstance = new Layout; + $testInstance = new Layout(); $setValue = $testInstance->setLayoutTarget($LayoutTargetValue); $result = $testInstance->getLayoutTarget(); diff --git a/tests/PhpSpreadsheet/Chart/LegendTest.php b/tests/PhpSpreadsheet/Chart/LegendTest.php index d4f64c05..901d8441 100644 --- a/tests/PhpSpreadsheet/Chart/LegendTest.php +++ b/tests/PhpSpreadsheet/Chart/LegendTest.php @@ -8,15 +8,15 @@ class LegendTest extends \PHPUnit_Framework_TestCase { public function testSetPosition() { - $positionValues = array( + $positionValues = [ Legend::POSITION_RIGHT, Legend::POSITION_LEFT, Legend::POSITION_TOP, Legend::POSITION_BOTTOM, Legend::POSITION_TOPRIGHT, - ); + ]; - $testInstance = new Legend; + $testInstance = new Legend(); foreach ($positionValues as $positionValue) { $result = $testInstance->setPosition($positionValue); @@ -26,7 +26,7 @@ class LegendTest extends \PHPUnit_Framework_TestCase public function testSetInvalidPositionReturnsFalse() { - $testInstance = new Legend; + $testInstance = new Legend(); $result = $testInstance->setPosition('BottomLeft'); $this->assertFalse($result); @@ -39,7 +39,7 @@ class LegendTest extends \PHPUnit_Framework_TestCase { $PositionValue = Legend::POSITION_BOTTOM; - $testInstance = new Legend; + $testInstance = new Legend(); $setValue = $testInstance->setPosition($PositionValue); $result = $testInstance->getPosition(); @@ -48,16 +48,16 @@ class LegendTest extends \PHPUnit_Framework_TestCase public function testSetPositionXL() { - $positionValues = array( + $positionValues = [ Legend::XL_LEGEND_POSITION_BOTTOM, Legend::XL_LEGEND_POSITION_CORNER, Legend::XL_LEGEND_POSITION_CUSTOM, Legend::XL_LEGEND_POSITION_LEFT, Legend::XL_LEGEND_POSITION_RIGHT, Legend::XL_LEGEND_POSITION_TOP, - ); + ]; - $testInstance = new Legend; + $testInstance = new Legend(); foreach ($positionValues as $positionValue) { $result = $testInstance->setPositionXL($positionValue); @@ -67,7 +67,7 @@ class LegendTest extends \PHPUnit_Framework_TestCase public function testSetInvalidXLPositionReturnsFalse() { - $testInstance = new Legend; + $testInstance = new Legend(); $result = $testInstance->setPositionXL(999); $this->assertFalse($result); @@ -80,7 +80,7 @@ class LegendTest extends \PHPUnit_Framework_TestCase { $PositionValue = Legend::XL_LEGEND_POSITION_CORNER; - $testInstance = new Legend; + $testInstance = new Legend(); $setValue = $testInstance->setPositionXL($PositionValue); $result = $testInstance->getPositionXL(); @@ -89,12 +89,12 @@ class LegendTest extends \PHPUnit_Framework_TestCase public function testSetOverlay() { - $overlayValues = array( + $overlayValues = [ true, false, - ); + ]; - $testInstance = new Legend; + $testInstance = new Legend(); foreach ($overlayValues as $overlayValue) { $result = $testInstance->setOverlay($overlayValue); @@ -104,7 +104,7 @@ class LegendTest extends \PHPUnit_Framework_TestCase public function testSetInvalidOverlayReturnsFalse() { - $testInstance = new Legend; + $testInstance = new Legend(); $result = $testInstance->setOverlay('INVALID'); $this->assertFalse($result); @@ -117,7 +117,7 @@ class LegendTest extends \PHPUnit_Framework_TestCase { $OverlayValue = true; - $testInstance = new Legend; + $testInstance = new Legend(); $setValue = $testInstance->setOverlay($OverlayValue); $result = $testInstance->getOverlay(); diff --git a/tests/PhpSpreadsheet/Custom/Complex.php b/tests/PhpSpreadsheet/Custom/Complex.php index 63f9f391..52654a79 100644 --- a/tests/PhpSpreadsheet/Custom/Complex.php +++ b/tests/PhpSpreadsheet/Custom/Complex.php @@ -14,7 +14,7 @@ class Complex { // Test for real number, with no imaginary part if (is_numeric($complexNumber)) { - return array($complexNumber, 0, null); + return [$complexNumber, 0, null]; } // Fix silly human errors @@ -42,7 +42,8 @@ class Complex if ($complexParts[1] === '-') { $imaginary = 0 - $imaginary; } - return array(0, $imaginary, $complexParts[2]); + + return [0, $imaginary, $complexParts[2]]; } // If we don't have an imaginary part, identify whether it should be +1 or -1... @@ -60,19 +61,18 @@ class Complex } // Return real and imaginary parts and suffix as an array, and set a default suffix if user input lazily - return array($complexParts[1], $complexParts[4], !empty($complexParts[9]) ? $complexParts[9] : 'i'); + return [$complexParts[1], $complexParts[4], !empty($complexParts[9]) ? $complexParts[9] : 'i']; } // function _parseComplex() - public function __construct($realPart, $imaginaryPart = null, $suffix = 'i') { if ($imaginaryPart === null) { if (is_array($realPart)) { // We have an array of (potentially) real and imaginary parts, and any suffix - list ($realPart, $imaginaryPart, $suffix) = array_values($realPart) + array(0.0, 0.0, 'i'); + list($realPart, $imaginaryPart, $suffix) = array_values($realPart) + [0.0, 0.0, 'i']; } elseif ((is_string($realPart)) || (is_numeric($realPart))) { // We've been given a string to parse to extract the real and imaginary parts, and any suffix - list ($realPart, $imaginaryPart, $suffix) = self::_parseComplex($realPart); + list($realPart, $imaginaryPart, $suffix) = self::_parseComplex($realPart); } } @@ -99,23 +99,24 @@ class Complex public function __toString() { - $str = ""; + $str = ''; if ($this->imaginaryPart != 0.0) { if (abs($this->imaginaryPart) != 1.0) { $str .= $this->imaginaryPart . $this->suffix; } else { - $str .= (($this->imaginaryPart < 0.0) ? '-' : ''). $this->suffix; + $str .= (($this->imaginaryPart < 0.0) ? '-' : '') . $this->suffix; } } if ($this->realPart != 0.0) { if (($str) && ($this->imaginaryPart > 0.0)) { - $str = "+" . $str; + $str = '+' . $str; } $str = $this->realPart . $str; } if (!$str) { - $str = "0.0"; + $str = '0.0'; } + return $str; } } diff --git a/tests/PhpSpreadsheet/Custom/ComplexAssert.php b/tests/PhpSpreadsheet/Custom/ComplexAssert.php index 290838c8..c6ec3ef4 100644 --- a/tests/PhpSpreadsheet/Custom/ComplexAssert.php +++ b/tests/PhpSpreadsheet/Custom/ComplexAssert.php @@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Tests\Custom; class ComplexAssert { - private $_errorMessage = ''; + private $_errorMessage = ''; public function assertComplexEquals($expected, $actual, $delta = 0) { @@ -14,6 +14,7 @@ class ComplexAssert return true; } $this->_errorMessage = 'Expected Error: ' . $actual . ' !== ' . $expected; + return false; } @@ -23,25 +24,30 @@ class ComplexAssert if (!is_numeric($actualComplex->getReal()) || !is_numeric($expectedComplex->getReal())) { if ($actualComplex->getReal() !== $expectedComplex->getReal()) { $this->_errorMessage = 'Mismatched String: ' . $actualComplex->getReal() . ' !== ' . $expectedComplex->getReal(); + return false; } + return true; } if ($actualComplex->getReal() < ($expectedComplex->getReal() - $delta) || $actualComplex->getReal() > ($expectedComplex->getReal() + $delta)) { $this->_errorMessage = 'Mismatched Real part: ' . $actualComplex->getReal() . ' != ' . $expectedComplex->getReal(); + return false; } if ($actualComplex->getImaginary() < ($expectedComplex->getImaginary() - $delta) || $actualComplex->getImaginary() > ($expectedComplex->getImaginary() + $delta)) { $this->_errorMessage = 'Mismatched Imaginary part: ' . $actualComplex->getImaginary() . ' != ' . $expectedComplex->getImaginary(); + return false; } if ($actualComplex->getSuffix() !== $actualComplex->getSuffix()) { $this->_errorMessage = 'Mismatched Suffix: ' . $actualComplex->getSuffix() . ' != ' . $expectedComplex->getSuffix(); + return false; } diff --git a/tests/PhpSpreadsheet/Reader/XEEValidatorTest.php b/tests/PhpSpreadsheet/Reader/XEEValidatorTest.php index 6965d0cc..689c4be7 100644 --- a/tests/PhpSpreadsheet/Reader/XEEValidatorTest.php +++ b/tests/PhpSpreadsheet/Reader/XEEValidatorTest.php @@ -24,6 +24,7 @@ class XEEValidatorTest extends \PHPUnit_Framework_TestCase foreach (glob('data/Reader/XEETestInvalid*.xml') as $file) { $tests[] = [realpath($file), true]; } + return $tests; } @@ -39,10 +40,11 @@ class XEEValidatorTest extends \PHPUnit_Framework_TestCase public function providerValidXML() { - $tests = array(); + $tests = []; foreach (glob('data/Reader/XEETestValid*.xml') as $file) { $tests[] = [realpath($file), file_get_contents($file)]; } + return $tests; } } diff --git a/tests/PhpSpreadsheet/ReferenceHelperTest.php b/tests/PhpSpreadsheet/ReferenceHelperTest.php index d3586d10..1d188301 100644 --- a/tests/PhpSpreadsheet/ReferenceHelperTest.php +++ b/tests/PhpSpreadsheet/ReferenceHelperTest.php @@ -6,7 +6,6 @@ use PhpSpreadsheet\ReferenceHelper; class ReferenceHelperTest extends \PHPUnit_Framework_TestCase { - public function setUp() { } @@ -14,19 +13,19 @@ class ReferenceHelperTest extends \PHPUnit_Framework_TestCase public function testColumnSort() { $columnBase = $columnExpectedResult = [ - 'A','B','Z', - 'AA','AB','AZ', - 'BA','BB','BZ', - 'ZA','ZB','ZZ', - 'AAA','AAB','AAZ', - 'ABA','ABB','ABZ', - 'AZA','AZB','AZZ', - 'BAA','BAB','BAZ', - 'BBA','BBB','BBZ', - 'BZA','BZB','BZZ' + 'A', 'B', 'Z', + 'AA', 'AB', 'AZ', + 'BA', 'BB', 'BZ', + 'ZA', 'ZB', 'ZZ', + 'AAA', 'AAB', 'AAZ', + 'ABA', 'ABB', 'ABZ', + 'AZA', 'AZB', 'AZZ', + 'BAA', 'BAB', 'BAZ', + 'BBA', 'BBB', 'BBZ', + 'BZA', 'BZB', 'BZZ', ]; shuffle($columnBase); - usort($columnBase, array(ReferenceHelper::class,'columnSort')); + usort($columnBase, [ReferenceHelper::class, 'columnSort']); foreach ($columnBase as $key => $value) { $this->assertEquals($columnExpectedResult[$key], $value); } @@ -35,20 +34,20 @@ class ReferenceHelperTest extends \PHPUnit_Framework_TestCase public function testColumnReverseSort() { $columnBase = $columnExpectedResult = [ - 'A','B','Z', - 'AA','AB','AZ', - 'BA','BB','BZ', - 'ZA','ZB','ZZ', - 'AAA','AAB','AAZ', - 'ABA','ABB','ABZ', - 'AZA','AZB','AZZ', - 'BAA','BAB','BAZ', - 'BBA','BBB','BBZ', - 'BZA','BZB','BZZ' + 'A', 'B', 'Z', + 'AA', 'AB', 'AZ', + 'BA', 'BB', 'BZ', + 'ZA', 'ZB', 'ZZ', + 'AAA', 'AAB', 'AAZ', + 'ABA', 'ABB', 'ABZ', + 'AZA', 'AZB', 'AZZ', + 'BAA', 'BAB', 'BAZ', + 'BBA', 'BBB', 'BBZ', + 'BZA', 'BZB', 'BZZ', ]; shuffle($columnBase); $columnExpectedResult = array_reverse($columnExpectedResult); - usort($columnBase, array(ReferenceHelper::class,'columnReverseSort')); + usort($columnBase, [ReferenceHelper::class, 'columnReverseSort']); foreach ($columnBase as $key => $value) { $this->assertEquals($columnExpectedResult[$key], $value); } diff --git a/tests/PhpSpreadsheet/SettingsTest.php b/tests/PhpSpreadsheet/SettingsTest.php index 552ad7dd..1148a59d 100644 --- a/tests/PhpSpreadsheet/SettingsTest.php +++ b/tests/PhpSpreadsheet/SettingsTest.php @@ -4,7 +4,6 @@ namespace PhpSpreadsheet\Tests; class SettingsTest extends \PHPUnit_Framework_TestCase { - public function setUp() { } @@ -13,7 +12,7 @@ class SettingsTest extends \PHPUnit_Framework_TestCase */ public function testGetXMLSettings() { - $result = call_user_func(array(\PhpSpreadsheet\Settings::class,'getLibXmlLoaderOptions')); + $result = call_user_func([\PhpSpreadsheet\Settings::class, 'getLibXmlLoaderOptions']); $this->assertTrue((bool) ((LIBXML_DTDLOAD | LIBXML_DTDATTR) & $result)); } @@ -21,8 +20,8 @@ class SettingsTest extends \PHPUnit_Framework_TestCase */ public function testSetXMLSettings() { - call_user_func_array(array(\PhpSpreadsheet\Settings::class,'setLibXmlLoaderOptions'), [LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_DTDVALID]); - $result = call_user_func(array(\PhpSpreadsheet\Settings::class,'getLibXmlLoaderOptions')); + call_user_func_array([\PhpSpreadsheet\Settings::class, 'setLibXmlLoaderOptions'], [LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_DTDVALID]); + $result = call_user_func([\PhpSpreadsheet\Settings::class, 'getLibXmlLoaderOptions']); $this->assertTrue((bool) ((LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_DTDVALID) & $result)); } } diff --git a/tests/PhpSpreadsheet/Shared/CodePageTest.php b/tests/PhpSpreadsheet/Shared/CodePageTest.php index 4e26c33a..6afea3df 100644 --- a/tests/PhpSpreadsheet/Shared/CodePageTest.php +++ b/tests/PhpSpreadsheet/Shared/CodePageTest.php @@ -2,8 +2,8 @@ namespace PhpSpreadsheet\Tests\Shared; -use PhpSpreadsheet\Shared\CodePage; use PhpSpreadsheet\Exception; +use PhpSpreadsheet\Shared\CodePage; class CodePageTest extends \PHPUnit_Framework_TestCase { @@ -14,7 +14,7 @@ class CodePageTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(CodePage::class,'numberToName'), $args); + $result = call_user_func_array([CodePage::class, 'numberToName'], $args); $this->assertEquals($expectedResult, $result); } @@ -27,9 +27,10 @@ class CodePageTest extends \PHPUnit_Framework_TestCase { $invalidCodePage = 12345; try { - $result = call_user_func(array(CodePage::class,'numberToName'), $invalidCodePage); + $result = call_user_func([CodePage::class, 'numberToName'], $invalidCodePage); } catch (Exception $e) { $this->assertEquals($e->getMessage(), 'Unknown codepage: 12345'); + return; } $this->fail('An expected exception has not been raised.'); @@ -39,9 +40,10 @@ class CodePageTest extends \PHPUnit_Framework_TestCase { $unsupportedCodePage = 720; try { - $result = call_user_func(array(CodePage::class,'numberToName'), $unsupportedCodePage); + $result = call_user_func([CodePage::class, 'numberToName'], $unsupportedCodePage); } catch (Exception $e) { $this->assertEquals($e->getMessage(), 'Code page 720 not supported.'); + return; } $this->fail('An expected exception has not been raised.'); diff --git a/tests/PhpSpreadsheet/Shared/DateTest.php b/tests/PhpSpreadsheet/Shared/DateTest.php index b903c0b5..c7c9cb12 100644 --- a/tests/PhpSpreadsheet/Shared/DateTest.php +++ b/tests/PhpSpreadsheet/Shared/DateTest.php @@ -8,13 +8,13 @@ class DateTest extends \PHPUnit_Framework_TestCase { public function testSetExcelCalendar() { - $calendarValues = array( + $calendarValues = [ Date::CALENDAR_MAC_1904, Date::CALENDAR_WINDOWS_1900, - ); + ]; foreach ($calendarValues as $calendarValue) { - $result = call_user_func(array(Date::class,'setExcelCalendar'), $calendarValue); + $result = call_user_func([Date::class, 'setExcelCalendar'], $calendarValue); $this->assertTrue($result); } } @@ -22,7 +22,7 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testSetExcelCalendarWithInvalidValue() { $unsupportedCalendar = '2012'; - $result = call_user_func(array(Date::class,'setExcelCalendar'), $unsupportedCalendar); + $result = call_user_func([Date::class, 'setExcelCalendar'], $unsupportedCalendar); $this->assertFalse($result); } @@ -32,13 +32,13 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testDateTimeExcelToTimestamp1900() { $result = call_user_func( - array(Date::class,'setExcelCalendar'), + [Date::class, 'setExcelCalendar'], Date::CALENDAR_WINDOWS_1900 ); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class, 'excelToTimestamp'), $args); + $result = call_user_func_array([Date::class, 'excelToTimestamp'], $args); $this->assertEquals($expectedResult, $result); } @@ -53,13 +53,13 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testDateTimeTimestampToExcel1900() { $result = call_user_func( - array(Date::class,'setExcelCalendar'), + [Date::class, 'setExcelCalendar'], Date::CALENDAR_WINDOWS_1900 ); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class,'timestampToExcel'), $args); + $result = call_user_func_array([Date::class, 'timestampToExcel'], $args); $this->assertEquals($expectedResult, $result, null, 1E-5); } @@ -74,13 +74,13 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testDateTimeDateTimeToExcel() { $result = call_user_func( - array(Date::class,'setExcelCalendar'), + [Date::class, 'setExcelCalendar'], Date::CALENDAR_WINDOWS_1900 ); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class,'dateTimeToExcel'), $args); + $result = call_user_func_array([Date::class, 'dateTimeToExcel'], $args); $this->assertEquals($expectedResult, $result, null, 1E-5); } @@ -95,13 +95,13 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testDateTimeFormattedPHPToExcel1900() { $result = call_user_func( - array(Date::class,'setExcelCalendar'), + [Date::class, 'setExcelCalendar'], Date::CALENDAR_WINDOWS_1900 ); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class,'formattedPHPToExcel'), $args); + $result = call_user_func_array([Date::class, 'formattedPHPToExcel'], $args); $this->assertEquals($expectedResult, $result, null, 1E-5); } @@ -116,13 +116,13 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testDateTimeExcelToTimestamp1904() { $result = call_user_func( - array(Date::class,'setExcelCalendar'), + [Date::class, 'setExcelCalendar'], Date::CALENDAR_MAC_1904 ); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class,'excelToTimestamp'), $args); + $result = call_user_func_array([Date::class, 'excelToTimestamp'], $args); $this->assertEquals($expectedResult, $result); } @@ -137,13 +137,13 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testDateTimeTimestampToExcel1904() { $result = call_user_func( - array(Date::class,'setExcelCalendar'), + [Date::class, 'setExcelCalendar'], Date::CALENDAR_MAC_1904 ); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class,'timestampToExcel'), $args); + $result = call_user_func_array([Date::class, 'timestampToExcel'], $args); $this->assertEquals($expectedResult, $result, null, 1E-5); } @@ -159,7 +159,7 @@ class DateTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class,'isDateTimeFormatCode'), $args); + $result = call_user_func_array([Date::class, 'isDateTimeFormatCode'], $args); $this->assertEquals($expectedResult, $result); } @@ -174,13 +174,13 @@ class DateTest extends \PHPUnit_Framework_TestCase public function testDateTimeExcelToTimestamp1900Timezone() { $result = call_user_func( - array(Date::class,'setExcelCalendar'), + [Date::class, 'setExcelCalendar'], Date::CALENDAR_WINDOWS_1900 ); $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Date::class,'excelToTimestamp'), $args); + $result = call_user_func_array([Date::class, 'excelToTimestamp'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Shared/FileTest.php b/tests/PhpSpreadsheet/Shared/FileTest.php index 7d6b86c2..b7272abb 100644 --- a/tests/PhpSpreadsheet/Shared/FileTest.php +++ b/tests/PhpSpreadsheet/Shared/FileTest.php @@ -10,21 +10,21 @@ class FileTest extends \PHPUnit_Framework_TestCase { $expectedResult = false; - $result = call_user_func(array(File::class,'getUseUploadTempDirectory')); + $result = call_user_func([File::class, 'getUseUploadTempDirectory']); $this->assertEquals($expectedResult, $result); } public function testSetUseUploadTempDirectory() { - $useUploadTempDirectoryValues = array( + $useUploadTempDirectoryValues = [ true, false, - ); + ]; foreach ($useUploadTempDirectoryValues as $useUploadTempDirectoryValue) { - call_user_func(array(File::class,'setUseUploadTempDirectory'), $useUploadTempDirectoryValue); + call_user_func([File::class, 'setUseUploadTempDirectory'], $useUploadTempDirectoryValue); - $result = call_user_func(array(File::class,'getUseUploadTempDirectory')); + $result = call_user_func([File::class, 'getUseUploadTempDirectory']); $this->assertEquals($useUploadTempDirectoryValue, $result); } } diff --git a/tests/PhpSpreadsheet/Shared/FontTest.php b/tests/PhpSpreadsheet/Shared/FontTest.php index c9c711c6..18fbd106 100644 --- a/tests/PhpSpreadsheet/Shared/FontTest.php +++ b/tests/PhpSpreadsheet/Shared/FontTest.php @@ -10,19 +10,19 @@ class FontTest extends \PHPUnit_Framework_TestCase { $expectedResult = Font::AUTOSIZE_METHOD_APPROX; - $result = call_user_func(array(Font::class,'getAutoSizeMethod')); + $result = call_user_func([Font::class, 'getAutoSizeMethod']); $this->assertEquals($expectedResult, $result); } public function testSetAutoSizeMethod() { - $autosizeMethodValues = array( + $autosizeMethodValues = [ Font::AUTOSIZE_METHOD_EXACT, Font::AUTOSIZE_METHOD_APPROX, - ); + ]; foreach ($autosizeMethodValues as $autosizeMethodValue) { - $result = call_user_func(array(Font::class,'setAutoSizeMethod'), $autosizeMethodValue); + $result = call_user_func([Font::class, 'setAutoSizeMethod'], $autosizeMethodValue); $this->assertTrue($result); } } @@ -31,7 +31,7 @@ class FontTest extends \PHPUnit_Framework_TestCase { $unsupportedAutosizeMethod = 'guess'; - $result = call_user_func(array(Font::class,'setAutoSizeMethod'), $unsupportedAutosizeMethod); + $result = call_user_func([Font::class, 'setAutoSizeMethod'], $unsupportedAutosizeMethod); $this->assertFalse($result); } @@ -42,7 +42,7 @@ class FontTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Font::class,'fontSizeToPixels'), $args); + $result = call_user_func_array([Font::class, 'fontSizeToPixels'], $args); $this->assertEquals($expectedResult, $result); } @@ -58,7 +58,7 @@ class FontTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Font::class,'inchSizeToPixels'), $args); + $result = call_user_func_array([Font::class, 'inchSizeToPixels'], $args); $this->assertEquals($expectedResult, $result); } @@ -74,7 +74,7 @@ class FontTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Font::class,'centimeterSizeToPixels'), $args); + $result = call_user_func_array([Font::class, 'centimeterSizeToPixels'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Shared/PasswordHasherTest.php b/tests/PhpSpreadsheet/Shared/PasswordHasherTest.php index 41addd76..41ebaa30 100644 --- a/tests/PhpSpreadsheet/Shared/PasswordHasherTest.php +++ b/tests/PhpSpreadsheet/Shared/PasswordHasherTest.php @@ -14,7 +14,7 @@ class PasswordHasherTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(PasswordHasher::class,'hashPassword'), $args); + $result = call_user_func_array([PasswordHasher::class, 'hashPassword'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Shared/StringTest.php b/tests/PhpSpreadsheet/Shared/StringTest.php index 957c078d..21934437 100644 --- a/tests/PhpSpreadsheet/Shared/StringTest.php +++ b/tests/PhpSpreadsheet/Shared/StringTest.php @@ -11,18 +11,18 @@ class StringTest extends \PHPUnit_Framework_TestCase parent::setUp(); // Reset Currency Code - call_user_func(array(StringHelper::class,'setCurrencyCode'), null); + call_user_func([StringHelper::class, 'setCurrencyCode'], null); } public function testGetIsMbStringEnabled() { - $result = call_user_func(array(StringHelper::class,'getIsMbstringEnabled')); + $result = call_user_func([StringHelper::class, 'getIsMbstringEnabled']); $this->assertTrue($result); } public function testGetIsIconvEnabled() { - $result = call_user_func(array(StringHelper::class,'getIsIconvEnabled')); + $result = call_user_func([StringHelper::class, 'getIsIconvEnabled']); $this->assertTrue($result); } @@ -31,16 +31,16 @@ class StringTest extends \PHPUnit_Framework_TestCase $localeconv = localeconv(); $expectedResult = (!empty($localeconv['decimal_point'])) ? $localeconv['decimal_point'] : ','; - $result = call_user_func(array(StringHelper::class,'getDecimalSeparator')); + $result = call_user_func([StringHelper::class, 'getDecimalSeparator']); $this->assertEquals($expectedResult, $result); } public function testSetDecimalSeparator() { $expectedResult = ','; - call_user_func(array(StringHelper::class,'setDecimalSeparator'), $expectedResult); + call_user_func([StringHelper::class, 'setDecimalSeparator'], $expectedResult); - $result = call_user_func(array(StringHelper::class,'getDecimalSeparator')); + $result = call_user_func([StringHelper::class, 'getDecimalSeparator']); $this->assertEquals($expectedResult, $result); } @@ -49,16 +49,16 @@ class StringTest extends \PHPUnit_Framework_TestCase $localeconv = localeconv(); $expectedResult = (!empty($localeconv['thousands_sep'])) ? $localeconv['thousands_sep'] : ','; - $result = call_user_func(array(StringHelper::class,'getThousandsSeparator')); + $result = call_user_func([StringHelper::class, 'getThousandsSeparator']); $this->assertEquals($expectedResult, $result); } public function testSetThousandsSeparator() { $expectedResult = ' '; - call_user_func(array(StringHelper::class,'setThousandsSeparator'), $expectedResult); + call_user_func([StringHelper::class, 'setThousandsSeparator'], $expectedResult); - $result = call_user_func(array(StringHelper::class,'getThousandsSeparator')); + $result = call_user_func([StringHelper::class, 'getThousandsSeparator']); $this->assertEquals($expectedResult, $result); } @@ -66,16 +66,16 @@ class StringTest extends \PHPUnit_Framework_TestCase { $localeconv = localeconv(); $expectedResult = (!empty($localeconv['currency_symbol']) ? $localeconv['currency_symbol'] : (!empty($localeconv['int_curr_symbol']) ? $localeconv['int_curr_symbol']: '$')); - $result = call_user_func(array(StringHelper::class,'getCurrencyCode')); + $result = call_user_func([StringHelper::class, 'getCurrencyCode']); $this->assertEquals($expectedResult, $result); } public function testSetCurrencyCode() { $expectedResult = '£'; - call_user_func(array(StringHelper::class,'setCurrencyCode'), $expectedResult); + call_user_func([StringHelper::class, 'setCurrencyCode'], $expectedResult); - $result = call_user_func(array(StringHelper::class,'getCurrencyCode')); + $result = call_user_func([StringHelper::class, 'getCurrencyCode']); $this->assertEquals($expectedResult, $result); } } diff --git a/tests/PhpSpreadsheet/Shared/TimeZoneTest.php b/tests/PhpSpreadsheet/Shared/TimeZoneTest.php index 5c7a99e1..410ea32e 100644 --- a/tests/PhpSpreadsheet/Shared/TimeZoneTest.php +++ b/tests/PhpSpreadsheet/Shared/TimeZoneTest.php @@ -8,16 +8,16 @@ class TimeZoneTest extends \PHPUnit_Framework_TestCase { public function testSetTimezone() { - $timezoneValues = array( + $timezoneValues = [ 'Europe/Prague', 'Asia/Tokyo', 'America/Indiana/Indianapolis', 'Pacific/Honolulu', 'Atlantic/St_Helena', - ); + ]; foreach ($timezoneValues as $timezoneValue) { - $result = call_user_func(array(TimeZone::class,'setTimezone'), $timezoneValue); + $result = call_user_func([TimeZone::class, 'setTimezone'], $timezoneValue); $this->assertTrue($result); } } @@ -25,7 +25,7 @@ class TimeZoneTest extends \PHPUnit_Framework_TestCase public function testSetTimezoneWithInvalidValue() { $unsupportedTimezone = 'Etc/GMT+10'; - $result = call_user_func(array(TimeZone::class,'setTimezone'), $unsupportedTimezone); + $result = call_user_func([TimeZone::class, 'setTimezone'], $unsupportedTimezone); $this->assertFalse($result); } } diff --git a/tests/PhpSpreadsheet/Style/ColorTest.php b/tests/PhpSpreadsheet/Style/ColorTest.php index 928d5234..626ec7f0 100644 --- a/tests/PhpSpreadsheet/Style/ColorTest.php +++ b/tests/PhpSpreadsheet/Style/ColorTest.php @@ -13,7 +13,7 @@ class ColorTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Color::class,'getRed'), $args); + $result = call_user_func_array([Color::class, 'getRed'], $args); $this->assertEquals($expectedResult, $result); } @@ -29,7 +29,7 @@ class ColorTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Color::class,'getGreen'), $args); + $result = call_user_func_array([Color::class, 'getGreen'], $args); $this->assertEquals($expectedResult, $result); } @@ -45,7 +45,7 @@ class ColorTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(Color::class,'getBlue'), $args); + $result = call_user_func_array([Color::class, 'getBlue'], $args); $this->assertEquals($expectedResult, $result); } @@ -60,7 +60,7 @@ class ColorTest extends \PHPUnit_Framework_TestCase public function testChangeBrightness() { list($args, $expectedResult) = func_get_args(); - $result = call_user_func_array(array(Color::class,'changeBrightness'), $args); + $result = call_user_func_array([Color::class, 'changeBrightness'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Style/NumberFormatDateTest.php b/tests/PhpSpreadsheet/Style/NumberFormatDateTest.php index 9833f7df..a6263997 100644 --- a/tests/PhpSpreadsheet/Style/NumberFormatDateTest.php +++ b/tests/PhpSpreadsheet/Style/NumberFormatDateTest.php @@ -7,7 +7,6 @@ use PhpSpreadsheet\Style\NumberFormat; class NumberFormatDateTest extends \PHPUnit_Framework_TestCase { - public function setUp() { StringHelper::setDecimalSeparator('.'); @@ -23,7 +22,7 @@ class NumberFormatDateTest extends \PHPUnit_Framework_TestCase $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(NumberFormat::class,'toFormattedString'), $args); + $result = call_user_func_array([NumberFormat::class, 'toFormattedString'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Style/NumberFormatTest.php b/tests/PhpSpreadsheet/Style/NumberFormatTest.php index 1949667c..a9ec082c 100644 --- a/tests/PhpSpreadsheet/Style/NumberFormatTest.php +++ b/tests/PhpSpreadsheet/Style/NumberFormatTest.php @@ -7,7 +7,6 @@ use PhpSpreadsheet\Style\NumberFormat; class NumberFormatTest extends \PHPUnit_Framework_TestCase { - public function setUp() { StringHelper::setDecimalSeparator('.'); @@ -21,7 +20,7 @@ class NumberFormatTest extends \PHPUnit_Framework_TestCase { $args = func_get_args(); $expectedResult = array_pop($args); - $result = call_user_func_array(array(NumberFormat::class,'toFormattedString'), $args); + $result = call_user_func_array([NumberFormat::class, 'toFormattedString'], $args); $this->assertEquals($expectedResult, $result); } diff --git a/tests/PhpSpreadsheet/Worksheet/AutoFilter/ColumnTest.php b/tests/PhpSpreadsheet/Worksheet/AutoFilter/ColumnTest.php index 44ffa637..601048b7 100644 --- a/tests/PhpSpreadsheet/Worksheet/AutoFilter/ColumnTest.php +++ b/tests/PhpSpreadsheet/Worksheet/AutoFilter/ColumnTest.php @@ -4,7 +4,7 @@ namespace PhpSpreadsheet\Tests\Worksheet\AutoFilter; use PhpSpreadsheet\Worksheet\AutoFilter; -class AutofilterColumnTest extends \PHPUnit_Framework_TestCase +class ColumnTest extends \PHPUnit_Framework_TestCase { private $testInitialColumn = 'H'; @@ -111,9 +111,9 @@ class AutofilterColumnTest extends \PHPUnit_Framework_TestCase public function testSetAttributes() { - $attributeSet = array( 'val' => 100, - 'maxVal' => 200 - ); + $attributeSet = ['val' => 100, + 'maxVal' => 200, + ]; // Setters return the instance to implement the fluent interface $result = $this->testAutoFilterColumnObject->setAttributes($attributeSet); @@ -122,9 +122,9 @@ class AutofilterColumnTest extends \PHPUnit_Framework_TestCase public function testGetAttributes() { - $attributeSet = array( 'val' => 100, - 'maxVal' => 200 - ); + $attributeSet = ['val' => 100, + 'maxVal' => 200, + ]; $this->testAutoFilterColumnObject->setAttributes($attributeSet); @@ -135,9 +135,9 @@ class AutofilterColumnTest extends \PHPUnit_Framework_TestCase public function testSetAttribute() { - $attributeSet = array( 'val' => 100, - 'maxVal' => 200 - ); + $attributeSet = ['val' => 100, + 'maxVal' => 200, + ]; foreach ($attributeSet as $attributeName => $attributeValue) { // Setters return the instance to implement the fluent interface @@ -148,9 +148,9 @@ class AutofilterColumnTest extends \PHPUnit_Framework_TestCase public function testGetAttribute() { - $attributeSet = array( 'val' => 100, - 'maxVal' => 200 - ); + $attributeSet = ['val' => 100, + 'maxVal' => 200, + ]; $this->testAutoFilterColumnObject->setAttributes($attributeSet); diff --git a/tests/PhpSpreadsheet/Worksheet/AutoFilterTest.php b/tests/PhpSpreadsheet/Worksheet/AutoFilterTest.php index a96b3fb8..6259e0a1 100644 --- a/tests/PhpSpreadsheet/Worksheet/AutoFilterTest.php +++ b/tests/PhpSpreadsheet/Worksheet/AutoFilterTest.php @@ -2,10 +2,10 @@ namespace PhpSpreadsheet\Tests\Worksheet; +use PhpSpreadsheet\CachedObjectStorage\Memory; +use PhpSpreadsheet\Worksheet; use PhpSpreadsheet\Worksheet\AutoFilter; use PhpSpreadsheet\Worksheet\AutoFilter\Column; -use PhpSpreadsheet\Worksheet; -use PhpSpreadsheet\CachedObjectStorage\Memory; class AutoFilterTest extends \PHPUnit_Framework_TestCase { @@ -70,7 +70,7 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase { $ranges = [ 'G1:J512' => 'Worksheet1!G1:J512', - 'K1:N20' => 'K1:N20' + 'K1:N20' => 'K1:N20', ]; foreach ($ranges as $actualRange => $fullRange) { @@ -120,7 +120,7 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase $columnIndexes = [ 'H' => 0, 'K' => 3, - 'M' => 5 + 'M' => 5, ]; // If we request a specific column by its column ID, we should get an @@ -210,7 +210,7 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase public function testGetColumns() { - $columnIndexes = ['L','M']; + $columnIndexes = ['L', 'M']; foreach ($columnIndexes as $columnIndex) { $this->testAutoFilterObject->setColumn($columnIndex); @@ -229,7 +229,7 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase public function testGetColumn() { - $columnIndexes = array('L','M'); + $columnIndexes = ['L', 'M']; foreach ($columnIndexes as $columnIndex) { $this->testAutoFilterObject->setColumn($columnIndex); @@ -248,7 +248,7 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase $columnIndexes = [ 0 => 'H', 3 => 'K', - 5 => 'M' + 5 => 'M', ]; // If we request a specific column by its offset, we should @@ -282,7 +282,7 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase { $expectedResult = ''; - $columnIndexes = ['L','M','N']; + $columnIndexes = ['L', 'M', 'N']; foreach ($columnIndexes as $columnIndex) { $this->testAutoFilterObject->setColumn($columnIndex); } @@ -306,12 +306,12 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase $expectedResult = 'G1:J512'; // These columns should be retained - $columnIndexes1 = ['I','J']; + $columnIndexes1 = ['I', 'J']; foreach ($columnIndexes1 as $columnIndex) { $this->testAutoFilterObject->setColumn($columnIndex); } // These columns should be discarded - $columnIndexes2 = ['K','L','M']; + $columnIndexes2 = ['K', 'L', 'M']; foreach ($columnIndexes2 as $columnIndex) { $this->testAutoFilterObject->setColumn($columnIndex); } @@ -333,7 +333,7 @@ class AutoFilterTest extends \PHPUnit_Framework_TestCase public function testClone() { - $columnIndexes = ['L','M']; + $columnIndexes = ['L', 'M']; foreach ($columnIndexes as $columnIndex) { $this->testAutoFilterObject->setColumn($columnIndex); diff --git a/tests/PhpSpreadsheet/Worksheet/ColumnCellIteratorTest.php b/tests/PhpSpreadsheet/Worksheet/ColumnCellIteratorTest.php index 8484f71a..e81fd17c 100644 --- a/tests/PhpSpreadsheet/Worksheet/ColumnCellIteratorTest.php +++ b/tests/PhpSpreadsheet/Worksheet/ColumnCellIteratorTest.php @@ -2,9 +2,9 @@ namespace PhpSpreadsheet\Tests\Worksheet; -use PhpSpreadsheet\Worksheet\ColumnCellIterator; use PhpSpreadsheet\Cell; use PhpSpreadsheet\Worksheet; +use PhpSpreadsheet\Worksheet\ColumnCellIterator; class ColumnCellIteratorTest extends \PHPUnit_Framework_TestCase { @@ -29,7 +29,6 @@ class ColumnCellIteratorTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue($this->mockCell)); } - public function testIteratorFullRange() { $iterator = new ColumnCellIterator($this->mockWorksheet, 'A'); @@ -61,7 +60,7 @@ class ColumnCellIteratorTest extends \PHPUnit_Framework_TestCase $iterator->seek(4); $this->assertEquals($columnIndexResult, $iterator->key()); - for ($i = 1; $i < $columnIndexResult-1; $i++) { + for ($i = 1; $i < $columnIndexResult - 1; ++$i) { $iterator->prev(); $this->assertEquals($columnIndexResult - $i, $iterator->key()); } diff --git a/tests/PhpSpreadsheet/Worksheet/ColumnIteratorTest.php b/tests/PhpSpreadsheet/Worksheet/ColumnIteratorTest.php index 1fb77381..3ff0c922 100644 --- a/tests/PhpSpreadsheet/Worksheet/ColumnIteratorTest.php +++ b/tests/PhpSpreadsheet/Worksheet/ColumnIteratorTest.php @@ -3,8 +3,8 @@ namespace PhpSpreadsheet\Tests\Worksheet; use PhpSpreadsheet\Worksheet; -use PhpSpreadsheet\Worksheet\ColumnIterator; use PhpSpreadsheet\Worksheet\Column; +use PhpSpreadsheet\Worksheet\ColumnIterator; class ColumnIteratorTest extends \PHPUnit_Framework_TestCase { @@ -29,7 +29,6 @@ class ColumnIteratorTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue($this->mockColumn)); } - public function testIteratorFullRange() { $iterator = new ColumnIterator($this->mockWorksheet); @@ -62,7 +61,7 @@ class ColumnIteratorTest extends \PHPUnit_Framework_TestCase $iterator->seek('D'); $this->assertEquals($columnIndexResult, $iterator->key()); - for ($i = 1; $i < array_search($columnIndexResult, $ranges); $i++) { + for ($i = 1; $i < array_search($columnIndexResult, $ranges); ++$i) { $iterator->prev(); $expectedResult = $ranges[array_search($columnIndexResult, $ranges) - $i]; $this->assertEquals($expectedResult, $iterator->key()); diff --git a/tests/PhpSpreadsheet/Worksheet/RowCellIteratorTest.php b/tests/PhpSpreadsheet/Worksheet/RowCellIteratorTest.php index c199fc10..450045bf 100644 --- a/tests/PhpSpreadsheet/Worksheet/RowCellIteratorTest.php +++ b/tests/PhpSpreadsheet/Worksheet/RowCellIteratorTest.php @@ -2,8 +2,8 @@ namespace PhpSpreadsheet\Tests\Worksheet; -use PhpSpreadsheet\Worksheet; use PhpSpreadsheet\Cell; +use PhpSpreadsheet\Worksheet; use PhpSpreadsheet\Worksheet\RowCellIterator; class RowCellIteratorTest extends \PHPUnit_Framework_TestCase @@ -29,7 +29,6 @@ class RowCellIteratorTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue($this->mockCell)); } - public function testIteratorFullRange() { $iterator = new RowCellIterator($this->mockWorksheet); @@ -62,7 +61,7 @@ class RowCellIteratorTest extends \PHPUnit_Framework_TestCase $iterator->seek('D'); $this->assertEquals($RowCellIndexResult, $iterator->key()); - for ($i = 1; $i < array_search($RowCellIndexResult, $ranges); $i++) { + for ($i = 1; $i < array_search($RowCellIndexResult, $ranges); ++$i) { $iterator->prev(); $expectedResult = $ranges[array_search($RowCellIndexResult, $ranges) - $i]; $this->assertEquals($expectedResult, $iterator->key()); diff --git a/tests/PhpSpreadsheet/Worksheet/RowIteratorTest.php b/tests/PhpSpreadsheet/Worksheet/RowIteratorTest.php index ceb9a414..a19204a1 100644 --- a/tests/PhpSpreadsheet/Worksheet/RowIteratorTest.php +++ b/tests/PhpSpreadsheet/Worksheet/RowIteratorTest.php @@ -2,9 +2,9 @@ namespace PhpSpreadsheet\Tests\Worksheet; -use PhpSpreadsheet\Worksheet\RowIterator; use PhpSpreadsheet\Worksheet; use PhpSpreadsheet\Worksheet\Row; +use PhpSpreadsheet\Worksheet\RowIterator; class RowIteratorTest extends \PHPUnit_Framework_TestCase { @@ -29,7 +29,6 @@ class RowIteratorTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue($this->mockRow)); } - public function testIteratorFullRange() { $iterator = new RowIterator($this->mockWorksheet); @@ -61,7 +60,7 @@ class RowIteratorTest extends \PHPUnit_Framework_TestCase $iterator->seek(4); $this->assertEquals($columnIndexResult, $iterator->key()); - for ($i = 1; $i < $columnIndexResult-1; $i++) { + for ($i = 1; $i < $columnIndexResult - 1; ++$i) { $iterator->prev(); $this->assertEquals($columnIndexResult - $i, $iterator->key()); } diff --git a/tests/PhpSpreadsheet/Worksheet/WorksheetColumnTest.php b/tests/PhpSpreadsheet/Worksheet/WorksheetColumnTest.php index 0da62fae..7d11fef1 100644 --- a/tests/PhpSpreadsheet/Worksheet/WorksheetColumnTest.php +++ b/tests/PhpSpreadsheet/Worksheet/WorksheetColumnTest.php @@ -21,7 +21,6 @@ class WorksheetColumnTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue(5)); } - public function testInstantiateColumnDefault() { $column = new Column($this->mockWorksheet); diff --git a/tests/PhpSpreadsheet/Worksheet/WorksheetRowTest.php b/tests/PhpSpreadsheet/Worksheet/WorksheetRowTest.php index 48c07d24..2ed9b921 100644 --- a/tests/PhpSpreadsheet/Worksheet/WorksheetRowTest.php +++ b/tests/PhpSpreadsheet/Worksheet/WorksheetRowTest.php @@ -21,7 +21,6 @@ class WorksheetRowTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue('E')); } - public function testInstantiateRowDefault() { $row = new Row($this->mockWorksheet); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 31f081cd..1b2011b9 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,10 +1,8 @@ 19-Dec-1960 05:00:00 UTC - [ 25569, 'America/New_York', 18000 ], // 01-Jan-1970 00:00:00 EST => 01-Jan-1970 05:00:00 UTC PHP Base Date - [ 30292, 'America/New_York', 408085200 ], // 07-Dec-1982 00:00:00 EST => 07-Dec-1982 05:00:00 UTC - [ 39611, 'America/New_York', 1213243200 ], // 12-Jun-2008 00:00:00 EDT => 12-Jun-2008 04:00:00 UTC - [ 50424, 'America/New_York', 2147490000 ], // 19-Jan-2038 00:00:00 EST => 19-Jan-2038 05:00:00 UTC PHP 32-bit Latest Date - [ 22345.56789, 'America/New_York', -278486534 ], // 05-Mar-1961 13:37:46 EST => 05-Mar-1961 18:37:46 UTC - [ 22345.6789, 'America/New_York', -278476943 ], // 05-Mar-1961 16:17:37 EST => 05-Mar-1961 21:17:37 UTC - [ 0.5, 'America/New_York', 61200 ], // 12:00:00 EST => 17:00:00 UTC - [ 0.75, 'America/New_York', 82800 ], // 18:00.00 EST => 23:00:00 UTC - [ 0.12345, 'America/New_York', 28666 ], // 02:57:46 EST => 07:57:46 UTC - [ 41215, 'America/New_York', 1351828800 ], // 02-Nov-2012 00:00:00 EDT => 02-Nov-2012 04:00:00 UTC - [ 22269, 'Pacific/Auckland', -285163200 ], // 19-Dec-1960 00:00:00 NZST => 18-Dec-1960 12:00:00 UTC - [ 25569, 'Pacific/Auckland', -43200 ], // 01-Jan-1970 00:00:00 NZST => 31-Dec-1969 12:00:00 UTC PHP Base Date - [ 30292, 'Pacific/Auckland', 408020400 ], // 07-Dec-1982 00:00:00 NZDT => 06-Dec-1982 11:00:00 UTC - [ 39611, 'Pacific/Auckland', 1213185600 ], // 12-Jun-2008 00:00:00 NZST => 11-Jun-2008 12:00:00 UTC - [ 50423.5, 'Pacific/Auckland', 2147382000 ], // 18-Jan-2038 12:00:00 NZDT => 17-Jan-2038 23:00:00 UTC PHP 32-bit Latest Date - [ 22345.56789, 'Pacific/Auckland', -278547734 ], // 05-Mar-1961 13:37:46 NZST => 05-Mar-1961 01:37:46 UTC - [ 22345.6789, 'Pacific/Auckland', -278538143 ], // 05-Mar-1961 16:17:37 NZST => 05-Mar-1961 04:17:37 UTC - [ 0.5, 'Pacific/Auckland', 0 ], // 12:00:00 NZST => 00:00:00 UTC - [ 0.75, 'Pacific/Auckland', 21600 ], // 18:00.00 NZST => 06:00:00 UTC - [ 0.12345, 'Pacific/Auckland', -32534 ], // 02:57:46 NZST => 14:57:46 UTC - [ 41215, 'Pacific/Auckland', 1351767600 ], // 02-Nov-2012 00:00:00 NZDT => 01-Nov-2012 11:00:00 UTC + [22269, 'America/New_York', -285102000], // 19-Dec-1960 00:00:00 EST => 19-Dec-1960 05:00:00 UTC + [25569, 'America/New_York', 18000], // 01-Jan-1970 00:00:00 EST => 01-Jan-1970 05:00:00 UTC PHP Base Date + [30292, 'America/New_York', 408085200], // 07-Dec-1982 00:00:00 EST => 07-Dec-1982 05:00:00 UTC + [39611, 'America/New_York', 1213243200], // 12-Jun-2008 00:00:00 EDT => 12-Jun-2008 04:00:00 UTC + [50424, 'America/New_York', 2147490000], // 19-Jan-2038 00:00:00 EST => 19-Jan-2038 05:00:00 UTC PHP 32-bit Latest Date + [22345.56789, 'America/New_York', -278486534], // 05-Mar-1961 13:37:46 EST => 05-Mar-1961 18:37:46 UTC + [22345.6789, 'America/New_York', -278476943], // 05-Mar-1961 16:17:37 EST => 05-Mar-1961 21:17:37 UTC + [0.5, 'America/New_York', 61200], // 12:00:00 EST => 17:00:00 UTC + [0.75, 'America/New_York', 82800], // 18:00.00 EST => 23:00:00 UTC + [0.12345, 'America/New_York', 28666], // 02:57:46 EST => 07:57:46 UTC + [41215, 'America/New_York', 1351828800], // 02-Nov-2012 00:00:00 EDT => 02-Nov-2012 04:00:00 UTC + [22269, 'Pacific/Auckland', -285163200], // 19-Dec-1960 00:00:00 NZST => 18-Dec-1960 12:00:00 UTC + [25569, 'Pacific/Auckland', -43200], // 01-Jan-1970 00:00:00 NZST => 31-Dec-1969 12:00:00 UTC PHP Base Date + [30292, 'Pacific/Auckland', 408020400], // 07-Dec-1982 00:00:00 NZDT => 06-Dec-1982 11:00:00 UTC + [39611, 'Pacific/Auckland', 1213185600], // 12-Jun-2008 00:00:00 NZST => 11-Jun-2008 12:00:00 UTC + [50423.5, 'Pacific/Auckland', 2147382000], // 18-Jan-2038 12:00:00 NZDT => 17-Jan-2038 23:00:00 UTC PHP 32-bit Latest Date + [22345.56789, 'Pacific/Auckland', -278547734], // 05-Mar-1961 13:37:46 NZST => 05-Mar-1961 01:37:46 UTC + [22345.6789, 'Pacific/Auckland', -278538143], // 05-Mar-1961 16:17:37 NZST => 05-Mar-1961 04:17:37 UTC + [0.5, 'Pacific/Auckland', 0], // 12:00:00 NZST => 00:00:00 UTC + [0.75, 'Pacific/Auckland', 21600], // 18:00.00 NZST => 06:00:00 UTC + [0.12345, 'Pacific/Auckland', -32534], // 02:57:46 NZST => 14:57:46 UTC + [41215, 'Pacific/Auckland', 1351767600], // 02-Nov-2012 00:00:00 NZDT => 01-Nov-2012 11:00:00 UTC ]; diff --git a/tests/data/Shared/Date/ExcelToTimestamp1904.php b/tests/data/Shared/Date/ExcelToTimestamp1904.php index 7716e66b..c7967ba2 100644 --- a/tests/data/Shared/Date/ExcelToTimestamp1904.php +++ b/tests/data/Shared/Date/ExcelToTimestamp1904.php @@ -2,13 +2,13 @@ // Excel DateTimeStamp Result Comments return [ - [ 1462, -1956528000 ], - [ 1463, -1956441600 ], - [ 22269, -158803200 ], - [ 25569, 126316800 ], - [ 30292, 534384000 ], - [ 39611, 1339545600 ], - [ 0.25, 21600 ], // 06:00:00 - [ 0.3333333333333333333, 28800 ], // 08:00.00 - [ 0.54321, 46933 ], // 02:57:46 + [1462, -1956528000], + [1463, -1956441600], + [22269, -158803200], + [25569, 126316800], + [30292, 534384000], + [39611, 1339545600], + [0.25, 21600], // 06:00:00 + [0.3333333333333333333, 28800], // 08:00.00 + [0.54321, 46933], // 02:57:46 ]; diff --git a/tests/data/Shared/Date/FormatCodes.php b/tests/data/Shared/Date/FormatCodes.php index c4be5210..69252ec1 100644 --- a/tests/data/Shared/Date/FormatCodes.php +++ b/tests/data/Shared/Date/FormatCodes.php @@ -2,40 +2,40 @@ // Excel Format Code Result return [ - [ 'General', false ], - [ '@', false ], - [ '0', false ], - [ '0.00', false ], - [ '#,##0.00', false ], - [ '#,##0.00_-', false ], - [ '0%', false ], - [ '0.00%', false ], - [ 'yyyy-mm-dd', true ], - [ 'yy-mm-dd', true ], - [ 'dd/mm/yy', true ], - [ 'd/m/y', true ], - [ 'd-m-y', true ], - [ 'd-m', true ], - [ 'm-y', true ], - [ 'mm-dd-yy', true ], - [ 'd-mmm-yy', true ], - [ 'd-mmm', true ], - [ 'mmm-yy', true ], - [ 'm/d/yy h:mm', true ], - [ 'd/m/y h:mm', true ], - [ 'h:mm AM/PM', true ], - [ 'h:mm:ss AM/PM', true ], - [ 'h:mm', true ], - [ 'h:mm:ss', true ], - [ 'mm:ss', true ], - [ 'h:mm:ss', true ], - [ 'i:s.S', true ], - [ 'h:mm:ss;@', true ], - [ 'yy/mm/dd;@', true ], - [ '"$" #,##0.00_-', false ], - [ '$#,##0_-', false ], - [ '[$EUR ]#,##0.00_-', false ], - [ '_[$EUR ]#,##0.00_-', false ], - [ '[Green]#,##0.00;[Red]#,##0.00_-', false ], - [ '#,##0.00 "dollars"', false ], + ['General', false], + ['@', false], + ['0', false], + ['0.00', false], + ['#,##0.00', false], + ['#,##0.00_-', false], + ['0%', false], + ['0.00%', false], + ['yyyy-mm-dd', true], + ['yy-mm-dd', true], + ['dd/mm/yy', true], + ['d/m/y', true], + ['d-m-y', true], + ['d-m', true], + ['m-y', true], + ['mm-dd-yy', true], + ['d-mmm-yy', true], + ['d-mmm', true], + ['mmm-yy', true], + ['m/d/yy h:mm', true], + ['d/m/y h:mm', true], + ['h:mm AM/PM', true], + ['h:mm:ss AM/PM', true], + ['h:mm', true], + ['h:mm:ss', true], + ['mm:ss', true], + ['h:mm:ss', true], + ['i:s.S', true], + ['h:mm:ss;@', true], + ['yy/mm/dd;@', true], + ['"$" #,##0.00_-', false], + ['$#,##0_-', false], + ['[$EUR ]#,##0.00_-', false], + ['_[$EUR ]#,##0.00_-', false], + ['[Green]#,##0.00;[Red]#,##0.00_-', false], + ['#,##0.00 "dollars"', false], ]; diff --git a/tests/data/Shared/Date/FormattedPHPToExcel1900.php b/tests/data/Shared/Date/FormattedPHPToExcel1900.php index f84c7323..6eafc3cc 100644 --- a/tests/data/Shared/Date/FormattedPHPToExcel1900.php +++ b/tests/data/Shared/Date/FormattedPHPToExcel1900.php @@ -2,15 +2,15 @@ // Year Month Day Hours Minutes Seconds Result Comments return [ - [ 1901, 12, 14, 714 ], // PHP 32-bit Earliest Date 14-Dec-1901 - [ 1903, 12, 31, 1461 ], // 31-Dec-1903 - [ 1904, 1, 1, 1462 ], // Excel 1904 Calendar Base Date 01-Jan-1904 - [ 1904, 1, 2, 1463 ], // 02-Jan-1904 - [ 1960, 12, 19, 22269 ], // 19-Dec-1960 - [ 1970, 1, 1, 25569 ], // PHP Base Date 01-Jan-1970 - [ 1982, 12, 7, 30292 ], // 07-Dec-1982 - [ 2008, 6, 12, 39611 ], // 12-Jun-2008 - [ 2038, 1, 19, 50424 ], // PHP 32-bit Latest Date 19-Jan-2038 - [ 1903, 5, 18, 13, 37, 46, 1234.56789 ], // 18-May-1903 13:37:46 - [ 1933, 10, 18, 16, 17, 37, 12345.6789 ], // 18-Oct-1933 16:17:37 + [1901, 12, 14, 714], // PHP 32-bit Earliest Date 14-Dec-1901 + [1903, 12, 31, 1461], // 31-Dec-1903 + [1904, 1, 1, 1462], // Excel 1904 Calendar Base Date 01-Jan-1904 + [1904, 1, 2, 1463], // 02-Jan-1904 + [1960, 12, 19, 22269], // 19-Dec-1960 + [1970, 1, 1, 25569], // PHP Base Date 01-Jan-1970 + [1982, 12, 7, 30292], // 07-Dec-1982 + [2008, 6, 12, 39611], // 12-Jun-2008 + [2038, 1, 19, 50424], // PHP 32-bit Latest Date 19-Jan-2038 + [1903, 5, 18, 13, 37, 46, 1234.56789], // 18-May-1903 13:37:46 + [1933, 10, 18, 16, 17, 37, 12345.6789], // 18-Oct-1933 16:17:37 ]; diff --git a/tests/data/Shared/Date/TimestampToExcel1900.php b/tests/data/Shared/Date/TimestampToExcel1900.php index 395c4c36..22acbb6f 100644 --- a/tests/data/Shared/Date/TimestampToExcel1900.php +++ b/tests/data/Shared/Date/TimestampToExcel1900.php @@ -2,15 +2,15 @@ // Unix TimeStamp Result Comments return [ - [ -2147472000, 714 ], // PHP 32-bit Earliest Date 14-Dec-1901 - [ -2082931200, 1461 ], // 31-Dec-1903 - [ -2082844800, 1462 ], // Excel 1904 Calendar Base Date 01-Jan-1904 - [ -2082758400, 1463 ], // 02-Jan-1904 - [ -285120000, 22269 ], // 19-Dec-1960 - [ 0, 25569 ], // PHP Base Date 01-Jan-1970 - [ 408067200, 30292 ], // 07-Dec-1982 - [ 1213228800, 39611 ], // 12-Jun-2008 - [ 2147472000, 50424 ], // PHP 32-bit Latest Date 19-Jan-2038 - [ -2102494934, 1234.56789 ], // 18-May-1903 13:37:46 - [ -1142494943, 12345.6789 ], // 18-Oct-1933 16:17:37 + [-2147472000, 714], // PHP 32-bit Earliest Date 14-Dec-1901 + [-2082931200, 1461], // 31-Dec-1903 + [-2082844800, 1462], // Excel 1904 Calendar Base Date 01-Jan-1904 + [-2082758400, 1463], // 02-Jan-1904 + [-285120000, 22269], // 19-Dec-1960 + [0, 25569], // PHP Base Date 01-Jan-1970 + [408067200, 30292], // 07-Dec-1982 + [1213228800, 39611], // 12-Jun-2008 + [2147472000, 50424], // PHP 32-bit Latest Date 19-Jan-2038 + [-2102494934, 1234.56789], // 18-May-1903 13:37:46 + [-1142494943, 12345.6789], // 18-Oct-1933 16:17:37 ]; diff --git a/tests/data/Shared/Date/TimestampToExcel1904.php b/tests/data/Shared/Date/TimestampToExcel1904.php index 4a08ecbf..93f5b700 100644 --- a/tests/data/Shared/Date/TimestampToExcel1904.php +++ b/tests/data/Shared/Date/TimestampToExcel1904.php @@ -2,10 +2,10 @@ // Excel DateTimeStamp Result return [ - [ -1956528000, 1462 ], - [ -1956441600, 1463 ], - [ -158803200, 22269 ], - [ 126316800, 25569 ], - [ 534384000, 30292 ], - [ 1339545600, 39611 ], + [-1956528000, 1462], + [-1956441600, 1463], + [-158803200, 22269], + [126316800, 25569], + [534384000, 30292], + [1339545600, 39611], ]; diff --git a/tests/data/Style/ColorChangeBrightness.php b/tests/data/Style/ColorChangeBrightness.php index a0a99f32..9585b06d 100644 --- a/tests/data/Style/ColorChangeBrightness.php +++ b/tests/data/Style/ColorChangeBrightness.php @@ -1,18 +1,18 @@