Merge pull request #1694 from PHPOffice/PHP8-Sane-Property-Names

Final stage of preparation for PHP8
This commit is contained in:
Adrien Crivelli 2021-10-31 23:28:05 +09:00 committed by GitHub
commit 69fc9349ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
102 changed files with 2361 additions and 2297 deletions

View File

@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
- Allow Row height and Column Width to be set using different units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`), rather than only in points or MS Excel column width units. [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145) - Allow Row height and Column Width to be set using different units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`), rather than only in points or MS Excel column width units. [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145)
- Ability to stream to an Amazon S3 bucket - Ability to stream to an Amazon S3 bucket
[Issue #2249](https://github.com/PHPOffice/PhpSpreadsheet/issues/2249) [Issue #2249](https://github.com/PHPOffice/PhpSpreadsheet/issues/2249)
- Provided a Size Helper class to validate size values (pt, px, em)
### Changed ### Changed

View File

@ -124,7 +124,7 @@ the Excel file:
```php ```php
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Read title row and rows 20 - 30 // Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) { if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true; return true;
@ -249,7 +249,7 @@ in the Excel file:
```php ```php
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Read title row and rows 20 - 30 // Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) { if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true; return true;
@ -308,7 +308,7 @@ in the Excel file:
```php ```php
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Read title row and rows 20 - 30 // Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) { if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true; return true;
@ -359,7 +359,7 @@ in the SYLK file:
```php ```php
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Read title row and rows 20 - 30 // Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) { if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true; return true;
@ -404,7 +404,7 @@ in the Calc file:
```php ```php
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Read title row and rows 20 - 30 // Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) { if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true; return true;

View File

@ -256,7 +256,7 @@ $sheetname = 'Data Sheet #3';
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */ /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
{ {
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Read rows 1 to 7 and columns A to E only // Read rows 1 to 7 and columns A to E only
if ($row >= 1 && $row <= 7) { if ($row >= 1 && $row <= 7) {
if (in_array($column,range('A','E'))) { if (in_array($column,range('A','E'))) {
@ -301,7 +301,7 @@ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
$this->columns = $columns; $this->columns = $columns;
} }
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Only read the rows and columns that were configured // Only read the rows and columns that were configured
if ($row >= $this->startRow && $row <= $this->endRow) { if ($row >= $this->startRow && $row <= $this->endRow) {
if (in_array($column,$this->columns)) { if (in_array($column,$this->columns)) {
@ -344,7 +344,7 @@ class ChunkReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
$this->endRow = $startRow + $chunkSize; $this->endRow = $startRow + $chunkSize;
} }
public function readCell($column, $row, $worksheetName = '') { public function readCell($columnAddress, $row, $worksheetName = '') {
// Only read the heading row, and the configured rows // Only read the heading row, and the configured rows
if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) {
return true; return true;

View File

@ -211,7 +211,7 @@ parameters:
path: src/PhpSpreadsheet/Calculation/Calculation.php path: src/PhpSpreadsheet/Calculation/Calculation.php
- -
message: "#^Parameter \\#1 \\$pValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:strCaseReverse\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:strCaseReverse\\(\\) expects string, string\\|null given\\.$#"
count: 2 count: 2
path: src/PhpSpreadsheet/Calculation/Calculation.php path: src/PhpSpreadsheet/Calculation/Calculation.php
@ -231,7 +231,7 @@ parameters:
path: src/PhpSpreadsheet/Calculation/Calculation.php path: src/PhpSpreadsheet/Calculation/Calculation.php
- -
message: "#^Parameter \\#2 \\$pSheet of static method PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:resolveName\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#" message: "#^Parameter \\#2 \\$worksheet of static method PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:resolveName\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Calculation/Calculation.php path: src/PhpSpreadsheet/Calculation/Calculation.php
@ -816,7 +816,7 @@ parameters:
path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php
- -
message: "#^Parameter \\#1 \\$pString of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:columnIndexFromString\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$columnAddress of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:columnIndexFromString\\(\\) expects string, string\\|null given\\.$#"
count: 3 count: 3
path: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php path: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php
@ -1246,7 +1246,7 @@ parameters:
path: src/PhpSpreadsheet/Cell/Coordinate.php path: src/PhpSpreadsheet/Cell/Coordinate.php
- -
message: "#^Parameter \\#1 \\$pValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:substring\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:substring\\(\\) expects string, string\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Cell/DataType.php path: src/PhpSpreadsheet/Cell/DataType.php
@ -1451,12 +1451,7 @@ parameters:
path: src/PhpSpreadsheet/Chart/GridLines.php path: src/PhpSpreadsheet/Chart/GridLines.php
- -
message: "#^Parameter \\#3 \\$type of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#3 \\$colorType of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects string, string\\|null given\\.$#"
count: 1
path: src/PhpSpreadsheet/Chart/GridLines.php
-
message: "#^Parameter \\#1 \\$blur of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setShadowBlur\\(\\) expects float, string\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Chart/GridLines.php path: src/PhpSpreadsheet/Chart/GridLines.php
@ -1511,7 +1506,7 @@ parameters:
path: src/PhpSpreadsheet/Chart/Properties.php path: src/PhpSpreadsheet/Chart/Properties.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$type with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$colorType with no typehint specified\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Chart/Properties.php path: src/PhpSpreadsheet/Chart/Properties.php
@ -1521,12 +1516,12 @@ parameters:
path: src/PhpSpreadsheet/Chart/Properties.php path: src/PhpSpreadsheet/Chart/Properties.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$array_kay_selector with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$arrayKaySelector with no typehint specified\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Chart/Properties.php path: src/PhpSpreadsheet/Chart/Properties.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$array_selector with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$arraySelector with no typehint specified\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Chart/Properties.php path: src/PhpSpreadsheet/Chart/Properties.php
@ -1536,7 +1531,7 @@ parameters:
path: src/PhpSpreadsheet/Chart/Properties.php path: src/PhpSpreadsheet/Chart/Properties.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getShadowPresetsMap\\(\\) has parameter \\$shadow_presets_option with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getShadowPresetsMap\\(\\) has parameter \\$presetsOption with no typehint specified\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Chart/Properties.php path: src/PhpSpreadsheet/Chart/Properties.php
@ -1895,11 +1890,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/DefinedName.php path: src/PhpSpreadsheet/DefinedName.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\HashTable\\:\\:getIndexForHashCode\\(\\) should return int but returns int\\|string\\|false\\.$#"
count: 1
path: src/PhpSpreadsheet/HashTable.php
- -
message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$colourMap has no typehint specified\\.$#" message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$colourMap has no typehint specified\\.$#"
count: 1 count: 1
@ -2020,16 +2010,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Helper/Html.php path: src/PhpSpreadsheet/Helper/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:rgbToColour\\(\\) has no return typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Helper/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:rgbToColour\\(\\) has parameter \\$rgb with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Helper/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:startFontTag\\(\\) has parameter \\$tag with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:startFontTag\\(\\) has parameter \\$tag with no typehint specified\\.$#"
count: 1 count: 1
@ -2381,17 +2361,17 @@ parameters:
path: src/PhpSpreadsheet/Reader/Xls.php path: src/PhpSpreadsheet/Reader/Xls.php
- -
message: "#^Parameter \\#1 \\$value of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setType\\(\\) expects string, int\\|string given\\.$#" message: "#^Parameter \\#1 \\$type of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setType\\(\\) expects string, int\\|string given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Reader/Xls.php path: src/PhpSpreadsheet/Reader/Xls.php
- -
message: "#^Parameter \\#1 \\$value of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setErrorStyle\\(\\) expects string, int\\|string given\\.$#" message: "#^Parameter \\#1 \\$errorStyle of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setErrorStyle\\(\\) expects string, int\\|string given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Reader/Xls.php path: src/PhpSpreadsheet/Reader/Xls.php
- -
message: "#^Parameter \\#1 \\$value of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setOperator\\(\\) expects string, int\\|string given\\.$#" message: "#^Parameter \\#1 \\$operator of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setOperator\\(\\) expects string, int\\|string given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Reader/Xls.php path: src/PhpSpreadsheet/Reader/Xls.php
@ -2566,7 +2546,7 @@ parameters:
path: src/PhpSpreadsheet/Reader/Xlsx.php path: src/PhpSpreadsheet/Reader/Xlsx.php
- -
message: "#^Parameter \\#1 \\$pName of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getSheetByName\\(\\) expects string, array\\|string given\\.$#" message: "#^Parameter \\#1 \\$worksheetName of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getSheetByName\\(\\) expects string, array\\|string given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Reader/Xlsx.php path: src/PhpSpreadsheet/Reader/Xlsx.php
@ -3221,7 +3201,7 @@ parameters:
path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php
- -
message: "#^Parameter \\#1 \\$hex of static method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\:\\:changeBrightness\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$hexColourValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\:\\:changeBrightness\\(\\) expects string, string\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php
@ -3271,7 +3251,7 @@ parameters:
path: src/PhpSpreadsheet/Reader/Xml.php path: src/PhpSpreadsheet/Reader/Xml.php
- -
message: "#^Parameter \\#1 \\$value of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:convertEncoding\\(\\) expects string, string\\|false given\\.$#" message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:convertEncoding\\(\\) expects string, string\\|false given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Reader/Xml.php path: src/PhpSpreadsheet/Reader/Xml.php
@ -3326,7 +3306,7 @@ parameters:
path: src/PhpSpreadsheet/Settings.php path: src/PhpSpreadsheet/Settings.php
- -
message: "#^Parameter \\#1 \\$dateValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:timestampToExcel\\(\\) expects int, float\\|int\\|string given\\.$#" message: "#^Parameter \\#1 \\$unixTimestamp of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:timestampToExcel\\(\\) expects int, float\\|int\\|string given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Shared/Date.php path: src/PhpSpreadsheet/Shared/Date.php
@ -3336,7 +3316,7 @@ parameters:
path: src/PhpSpreadsheet/Shared/Date.php path: src/PhpSpreadsheet/Shared/Date.php
- -
message: "#^Parameter \\#1 \\$pFormatCode of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:isDateTimeFormatCode\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$excelFormatCode of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:isDateTimeFormatCode\\(\\) expects string, string\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Shared/Date.php path: src/PhpSpreadsheet/Shared/Date.php
@ -3466,7 +3446,7 @@ parameters:
path: src/PhpSpreadsheet/Shared/Font.php path: src/PhpSpreadsheet/Shared/Font.php
- -
message: "#^Parameter \\#2 \\$pDefaultFont of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Drawing\\:\\:pixelsToCellDimension\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" message: "#^Parameter \\#2 \\$defaultFont of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Drawing\\:\\:pixelsToCellDimension\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Shared/Font.php path: src/PhpSpreadsheet/Shared/Font.php
@ -3866,7 +3846,7 @@ parameters:
path: src/PhpSpreadsheet/Shared/StringHelper.php path: src/PhpSpreadsheet/Shared/StringHelper.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbIsUpper\\(\\) has parameter \\$char with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbIsUpper\\(\\) has parameter \\$character with no typehint specified\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Shared/StringHelper.php path: src/PhpSpreadsheet/Shared/StringHelper.php
@ -4096,7 +4076,7 @@ parameters:
path: src/PhpSpreadsheet/Spreadsheet.php path: src/PhpSpreadsheet/Spreadsheet.php
- -
message: "#^Parameter \\#1 \\$pSheet of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getIndex\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#" message: "#^Parameter \\#1 \\$worksheet of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getIndex\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Spreadsheet.php path: src/PhpSpreadsheet/Spreadsheet.php
@ -4140,11 +4120,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Style/Border.php path: src/PhpSpreadsheet/Style/Border.php
-
message: "#^Right side of && is always true\\.$#"
count: 1
path: src/PhpSpreadsheet/Style/Border.php
- -
message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Supervisor\\:\\:bindParent\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Borders\\) given\\.$#" message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Supervisor\\:\\:bindParent\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Borders\\) given\\.$#"
count: 10 count: 10
@ -4681,7 +4656,7 @@ parameters:
path: src/PhpSpreadsheet/Worksheet/Worksheet.php path: src/PhpSpreadsheet/Worksheet/Worksheet.php
- -
message: "#^Parameter \\#1 \\$pRange of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:rangeDimension\\(\\) expects string, string\\|false given\\.$#" message: "#^Parameter \\#1 \\$range of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:rangeDimension\\(\\) expects string, string\\|false given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Worksheet/Worksheet.php path: src/PhpSpreadsheet/Worksheet/Worksheet.php
@ -4915,11 +4890,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Html.php path: src/PhpSpreadsheet/Writer/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTagInline\\(\\) has parameter \\$pSheet with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$html with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$html with no typehint specified\\.$#"
count: 1 count: 1
@ -4930,11 +4900,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Html.php path: src/PhpSpreadsheet/Writer/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$pSheet with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$sheetIndex with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$sheetIndex with no typehint specified\\.$#"
count: 1 count: 1
@ -4965,11 +4930,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Html.php path: src/PhpSpreadsheet/Writer/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has parameter \\$pSheet with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValueRich\\(\\) has parameter \\$cell with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValueRich\\(\\) has parameter \\$cell with no typehint specified\\.$#"
count: 1 count: 1
@ -5005,11 +4965,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Html.php path: src/PhpSpreadsheet/Writer/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValue\\(\\) has parameter \\$pSheet with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has no return typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has no return typehint specified\\.$#"
count: 1 count: 1
@ -5030,11 +4985,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Html.php path: src/PhpSpreadsheet/Writer/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has parameter \\$pSheet with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowIncludeCharts\\(\\) has no return typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowIncludeCharts\\(\\) has no return typehint specified\\.$#"
count: 1 count: 1
@ -5045,11 +4995,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Html.php path: src/PhpSpreadsheet/Writer/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowIncludeCharts\\(\\) has parameter \\$pSheet with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has no return typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has no return typehint specified\\.$#"
count: 1 count: 1
@ -5110,11 +5055,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Html.php path: src/PhpSpreadsheet/Writer/Html.php
-
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$pSheet with no typehint specified\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Html.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$rowSpan with no typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$rowSpan with no typehint specified\\.$#"
count: 1 count: 1
@ -5171,7 +5111,7 @@ parameters:
path: src/PhpSpreadsheet/Writer/Ods/Content.php path: src/PhpSpreadsheet/Writer/Ods/Content.php
- -
message: "#^Parameter \\#1 \\$pRange of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:splitRange\\(\\) expects string, string\\|false given\\.$#" message: "#^Parameter \\#1 \\$range of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:splitRange\\(\\) expects string, string\\|false given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Ods/Content.php path: src/PhpSpreadsheet/Writer/Ods/Content.php
@ -5291,7 +5231,7 @@ parameters:
path: src/PhpSpreadsheet/Writer/Xls/Escher.php path: src/PhpSpreadsheet/Writer/Xls/Escher.php
- -
message: "#^Parameter \\#1 \\$name of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:getCharsetFromFontName\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$fontName of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:getCharsetFromFontName\\(\\) expects string, string\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Xls/Font.php path: src/PhpSpreadsheet/Writer/Xls/Font.php
@ -5311,7 +5251,7 @@ parameters:
path: src/PhpSpreadsheet/Writer/Xls/Font.php path: src/PhpSpreadsheet/Writer/Xls/Font.php
- -
message: "#^Parameter \\#1 \\$value of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:UTF8toBIFF8UnicodeShort\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:UTF8toBIFF8UnicodeShort\\(\\) expects string, string\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Xls/Font.php path: src/PhpSpreadsheet/Writer/Xls/Font.php
@ -5370,11 +5310,6 @@ parameters:
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Xls/Workbook.php path: src/PhpSpreadsheet/Writer/Xls/Workbook.php
-
message: "#^Parameter \\#1 \\$pSheet of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getIndex\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Xls/Workbook.php
- -
message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeSupbookInternal\\(\\) has no return typehint specified\\.$#" message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeSupbookInternal\\(\\) has no return typehint specified\\.$#"
count: 1 count: 1
@ -5701,7 +5636,7 @@ parameters:
path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php
- -
message: "#^Parameter \\#1 \\$text of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:writeRawData\\(\\) expects array\\<string\\>\\|string, int given\\.$#" message: "#^Parameter \\#1 \\$rawTextData of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:writeRawData\\(\\) expects array\\<string\\>\\|string\\|null, int given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php
@ -5822,7 +5757,7 @@ parameters:
- -
message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#"
count: 4 count: 5
path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php
- -
@ -5871,7 +5806,7 @@ parameters:
path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php
- -
message: "#^Parameter \\#1 \\$pText of method PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText\\:\\:createTextRun\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#1 \\$text of method PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText\\:\\:createTextRun\\(\\) expects string, string\\|null given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php
@ -5917,9 +5852,14 @@ parameters:
- -
message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#"
count: 4 count: 9
path: src/PhpSpreadsheet/Writer/Xlsx/Style.php path: src/PhpSpreadsheet/Writer/Xlsx/Style.php
-
message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#"
count: 1
path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php
- -
message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float given\\.$#" message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float given\\.$#"
count: 1 count: 1
@ -6002,16 +5942,11 @@ parameters:
- -
message: "#^Parameter \\#4 \\$val of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeAttributeIf\\(\\) expects string, int given\\.$#" message: "#^Parameter \\#4 \\$val of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeAttributeIf\\(\\) expects string, int given\\.$#"
count: 2
path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php
-
message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int\\|string given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php
- -
message: "#^Right side of && is always true\\.$#" message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int\\|string given\\.$#"
count: 1 count: 1
path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php
@ -6056,7 +5991,7 @@ parameters:
path: tests/PhpSpreadsheetTests/Functional/CommentsTest.php path: tests/PhpSpreadsheetTests/Functional/CommentsTest.php
- -
message: "#^Parameter \\#1 \\$pValue of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:addCondition\\(\\) expects string, float given\\.$#" message: "#^Parameter \\#1 \\$condition of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:addCondition\\(\\) expects string, float given\\.$#"
count: 2 count: 2
path: tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php path: tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php
@ -6101,7 +6036,7 @@ parameters:
path: tests/PhpSpreadsheetTests/Functional/StreamTest.php path: tests/PhpSpreadsheetTests/Functional/StreamTest.php
- -
message: "#^Parameter \\#1 \\$pFilename of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\IWriter\\:\\:save\\(\\) expects resource\\|string, resource\\|false given\\.$#" message: "#^Parameter \\#1 \\$filename of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\IWriter\\:\\:save\\(\\) expects resource\\|string, resource\\|false given\\.$#"
count: 1 count: 1
path: tests/PhpSpreadsheetTests/Functional/StreamTest.php path: tests/PhpSpreadsheetTests/Functional/StreamTest.php
@ -6201,7 +6136,7 @@ parameters:
path: tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php path: tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php
- -
message: "#^Parameter \\#1 \\$pValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:setCurrencyCode\\(\\) expects string, null given\\.$#" message: "#^Parameter \\#1 \\$currencyCode of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:setCurrencyCode\\(\\) expects string, null given\\.$#"
count: 1 count: 1
path: tests/PhpSpreadsheetTests/Shared/StringHelperTest.php path: tests/PhpSpreadsheetTests/Shared/StringHelperTest.php
@ -6216,12 +6151,12 @@ parameters:
path: tests/PhpSpreadsheetTests/SpreadsheetTest.php path: tests/PhpSpreadsheetTests/SpreadsheetTest.php
- -
message: "#^Parameter \\#1 \\$pValue of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:addCondition\\(\\) expects string, float given\\.$#" message: "#^Parameter \\#1 \\$condition of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:addCondition\\(\\) expects string, float given\\.$#"
count: 2 count: 2
path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php
- -
message: "#^Parameter \\#1 \\$pValue of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:setConditions\\(\\) expects array\\<string\\>\\|bool\\|float\\|int\\|string, array\\<int, float\\> given\\.$#" message: "#^Parameter \\#1 \\$conditions of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:setConditions\\(\\) expects array\\<string\\>\\|bool\\|float\\|int\\|string, array\\<int, float\\> given\\.$#"
count: 1 count: 1
path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php

View File

@ -18,7 +18,7 @@ $helper->logWrite($writer, $filename, $callStartTime);
class MyReadFilter implements IReadFilter class MyReadFilter implements IReadFilter
{ {
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
// Read title row and rows 20 - 30 // Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) { if ($row == 1 || ($row >= 20 && $row <= 30)) {

View File

@ -13,11 +13,11 @@ $sheetname = 'Data Sheet #3';
class MyReadFilter implements IReadFilter class MyReadFilter implements IReadFilter
{ {
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
// Read rows 1 to 7 and columns A to E only // Read rows 1 to 7 and columns A to E only
if ($row >= 1 && $row <= 7) { if ($row >= 1 && $row <= 7) {
if (in_array($column, range('A', 'E'))) { if (in_array($columnAddress, range('A', 'E'))) {
return true; return true;
} }
} }

View File

@ -26,10 +26,10 @@ class MyReadFilter implements IReadFilter
$this->columns = $columns; $this->columns = $columns;
} }
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
if ($row >= $this->startRow && $row <= $this->endRow) { if ($row >= $this->startRow && $row <= $this->endRow) {
if (in_array($column, $this->columns)) { if (in_array($columnAddress, $this->columns)) {
return true; return true;
} }
} }

View File

@ -29,7 +29,7 @@ class ChunkReadFilter implements IReadFilter
$this->endRow = $startRow + $chunkSize; $this->endRow = $startRow + $chunkSize;
} }
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
// Only read the heading row, and the rows that were configured in the constructor // Only read the heading row, and the rows that were configured in the constructor
if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) {

View File

@ -29,7 +29,7 @@ class ChunkReadFilter implements IReadFilter
$this->endRow = $startRow + $chunkSize; $this->endRow = $startRow + $chunkSize;
} }
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
// Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow // Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow
if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) {

View File

@ -30,7 +30,7 @@ class ChunkReadFilter implements IReadFilter
$this->endRow = $startRow + $chunkSize; $this->endRow = $startRow + $chunkSize;
} }
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
// Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow // Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow
if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) {

View File

@ -5242,34 +5242,34 @@ class Calculation
* Extract range values. * Extract range values.
* *
* @param string $pRange String based range representation * @param string $pRange String based range representation
* @param Worksheet $pSheet Worksheet * @param Worksheet $worksheet Worksheet
* @param bool $resetLog Flag indicating whether calculation log should be reset or not * @param bool $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. * @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) public function extractCellRange(&$pRange = 'A1', ?Worksheet $worksheet = null, $resetLog = true)
{ {
// Return value // Return value
$returnValue = []; $returnValue = [];
if ($pSheet !== null) { if ($worksheet !== null) {
$pSheetName = $pSheet->getTitle(); $worksheetName = $worksheet->getTitle();
if (strpos($pRange, '!') !== false) { if (strpos($pRange, '!') !== false) {
[$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); [$worksheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true);
$pSheet = $this->spreadsheet->getSheetByName($pSheetName); $worksheet = $this->spreadsheet->getSheetByName($worksheetName);
} }
// Extract range // Extract range
$aReferences = Coordinate::extractAllCellReferencesInRange($pRange); $aReferences = Coordinate::extractAllCellReferencesInRange($pRange);
$pRange = "'" . $pSheetName . "'" . '!' . $pRange; $pRange = "'" . $worksheetName . "'" . '!' . $pRange;
if (!isset($aReferences[1])) { if (!isset($aReferences[1])) {
$currentCol = ''; $currentCol = '';
$currentRow = 0; $currentRow = 0;
// Single cell in range // Single cell in range
sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
if ($pSheet->cellExists($aReferences[0])) { if ($worksheet->cellExists($aReferences[0])) {
$returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
} else { } else {
$returnValue[$currentRow][$currentCol] = null; $returnValue[$currentRow][$currentCol] = null;
} }
@ -5280,8 +5280,8 @@ class Calculation
$currentRow = 0; $currentRow = 0;
// Extract range // Extract range
sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
if ($pSheet->cellExists($reference)) { if ($worksheet->cellExists($reference)) {
$returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
} else { } else {
$returnValue[$currentRow][$currentCol] = null; $returnValue[$currentRow][$currentCol] = null;
} }
@ -5295,47 +5295,46 @@ class Calculation
/** /**
* Extract range values. * Extract range values.
* *
* @param string $pRange String based range representation * @param string $range String based range representation
* @param Worksheet $pSheet Worksheet * @param null|Worksheet $worksheet Worksheet
* @param bool $resetLog Flag indicating whether calculation log should be reset or not * @param bool $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. * @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) public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true)
{ {
// Return value // Return value
$returnValue = []; $returnValue = [];
if ($pSheet !== null) { if ($worksheet !== null) {
$pSheetName = $pSheet->getTitle(); if (strpos($range, '!') !== false) {
if (strpos($pRange, '!') !== false) { [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true);
[$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); $worksheet = $this->spreadsheet->getSheetByName($worksheetName);
$pSheet = $this->spreadsheet->getSheetByName($pSheetName);
} }
// Named range? // Named range?
$namedRange = DefinedName::resolveName($pRange, $pSheet); $namedRange = DefinedName::resolveName($range, $worksheet);
if ($namedRange === null) { if ($namedRange === null) {
return Functions::REF(); return Functions::REF();
} }
$pSheet = $namedRange->getWorksheet(); $worksheet = $namedRange->getWorksheet();
$pRange = $namedRange->getValue(); $range = $namedRange->getValue();
$splitRange = Coordinate::splitRange($pRange); $splitRange = Coordinate::splitRange($range);
// Convert row and column references // Convert row and column references
if (ctype_alpha($splitRange[0][0])) { if (ctype_alpha($splitRange[0][0])) {
$pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow(); $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
} elseif (ctype_digit($splitRange[0][0])) { } elseif (ctype_digit($splitRange[0][0])) {
$pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1]; $range = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
} }
// Extract range // Extract range
$aReferences = Coordinate::extractAllCellReferencesInRange($pRange); $aReferences = Coordinate::extractAllCellReferencesInRange($range);
if (!isset($aReferences[1])) { if (!isset($aReferences[1])) {
// Single cell (or single column or row) in range // Single cell (or single column or row) in range
[$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]); [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
if ($pSheet->cellExists($aReferences[0])) { if ($worksheet->cellExists($aReferences[0])) {
$returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
} else { } else {
$returnValue[$currentRow][$currentCol] = null; $returnValue[$currentRow][$currentCol] = null;
} }
@ -5344,8 +5343,8 @@ class Calculation
foreach ($aReferences as $reference) { foreach ($aReferences as $reference) {
// Extract range // Extract range
[$currentCol, $currentRow] = Coordinate::coordinateFromString($reference); [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference);
if ($pSheet->cellExists($reference)) { if ($worksheet->cellExists($reference)) {
$returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
} else { } else {
$returnValue[$currentRow][$currentCol] = null; $returnValue[$currentRow][$currentCol] = null;
} }

View File

@ -65,10 +65,10 @@ class Helpers
$sheetName = trim($sheetName, "'"); $sheetName = trim($sheetName, "'");
} }
$pSheet = ($sheetName !== '') $worksheet = ($sheetName !== '')
? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName) ? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName)
: $pCell->getWorksheet(); : $pCell->getWorksheet();
return [$cellAddress, $pSheet, $sheetName]; return [$cellAddress, $worksheet, $sheetName];
} }
} }

View File

@ -69,7 +69,7 @@ class Indirect
return $e->getMessage(); return $e->getMessage();
} }
[$cellAddress, $pSheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $pCell); [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $pCell);
[$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $pCell->getWorkSheet(), $sheetName); [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $pCell->getWorkSheet(), $sheetName);
@ -80,7 +80,7 @@ class Indirect
return Functions::REF(); return Functions::REF();
} }
return self::extractRequiredCells($pSheet, $cellAddress); return self::extractRequiredCells($worksheet, $cellAddress);
} }
/** /**
@ -89,9 +89,9 @@ class Indirect
* @return mixed Array of values in range if range contains more than one element. * @return mixed Array of values in range if range contains more than one element.
* Otherwise, a single value is returned. * Otherwise, a single value is returned.
*/ */
private static function extractRequiredCells(?Worksheet $pSheet, string $cellAddress) private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress)
{ {
return Calculation::getInstance($pSheet !== null ? $pSheet->getParent() : null) return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null)
->extractCellRange($cellAddress, $pSheet, false); ->extractCellRange($cellAddress, $worksheet, false);
} }
} }

View File

@ -55,7 +55,7 @@ class Offset
return Functions::REF(); return Functions::REF();
} }
[$cellAddress, $pSheet] = self::extractWorksheet($cellAddress, $pCell); [$cellAddress, $worksheet] = self::extractWorksheet($cellAddress, $pCell);
$startCell = $endCell = $cellAddress; $startCell = $endCell = $cellAddress;
if (strpos($cellAddress, ':')) { if (strpos($cellAddress, ':')) {
@ -87,13 +87,13 @@ class Offset
$cellAddress .= ":{$endCellColumn}{$endCellRow}"; $cellAddress .= ":{$endCellColumn}{$endCellRow}";
} }
return self::extractRequiredCells($pSheet, $cellAddress); return self::extractRequiredCells($worksheet, $cellAddress);
} }
private static function extractRequiredCells(?Worksheet $pSheet, string $cellAddress) private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress)
{ {
return Calculation::getInstance($pSheet !== null ? $pSheet->getParent() : null) return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null)
->extractCellRange($cellAddress, $pSheet, false); ->extractCellRange($cellAddress, $worksheet, false);
} }
private static function extractWorksheet($cellAddress, Cell $pCell): array private static function extractWorksheet($cellAddress, Cell $pCell): array
@ -104,11 +104,11 @@ class Offset
$sheetName = trim($sheetName, "'"); $sheetName = trim($sheetName, "'");
} }
$pSheet = ($sheetName !== '') $worksheet = ($sheetName !== '')
? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName) ? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName)
: $pCell->getWorksheet(); : $pCell->getWorksheet();
return [$cellAddress, $pSheet]; return [$cellAddress, $worksheet];
} }
private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns) private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns)

View File

@ -90,24 +90,24 @@ class Cell
/** /**
* Create a new Cell. * Create a new Cell.
* *
* @param mixed $pValue * @param mixed $value
* @param string $pDataType * @param string $dataType
*/ */
public function __construct($pValue, $pDataType, Worksheet $pSheet) public function __construct($value, $dataType, Worksheet $worksheet)
{ {
// Initialise cell value // Initialise cell value
$this->value = $pValue; $this->value = $value;
// Set worksheet cache // Set worksheet cache
$this->parent = $pSheet->getCellCollection(); $this->parent = $worksheet->getCellCollection();
// Set datatype? // Set datatype?
if ($pDataType !== null) { if ($dataType !== null) {
if ($pDataType == DataType::TYPE_STRING2) { if ($dataType == DataType::TYPE_STRING2) {
$pDataType = DataType::TYPE_STRING; $dataType = DataType::TYPE_STRING;
} }
$this->dataType = $pDataType; $this->dataType = $dataType;
} elseif (!self::getValueBinder()->bindValue($this, $pValue)) { } elseif (!self::getValueBinder()->bindValue($this, $value)) {
throw new Exception('Value could not be bound to cell.'); throw new Exception('Value could not be bound to cell.');
} }
} }
@ -171,13 +171,13 @@ class Cell
* *
* Sets the value for a cell, automatically determining the datatype using the value binder * Sets the value for a cell, automatically determining the datatype using the value binder
* *
* @param mixed $pValue Value * @param mixed $value Value
* *
* @return $this * @return $this
*/ */
public function setValue($pValue) public function setValue($value)
{ {
if (!self::getValueBinder()->bindValue($this, $pValue)) { if (!self::getValueBinder()->bindValue($this, $value)) {
throw new Exception('Value could not be bound to cell.'); throw new Exception('Value could not be bound to cell.');
} }
@ -187,56 +187,56 @@ class Cell
/** /**
* Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder). * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder).
* *
* @param mixed $pValue Value * @param mixed $value Value
* @param string $pDataType Explicit data type, see DataType::TYPE_* * @param string $dataType Explicit data type, see DataType::TYPE_*
* *
* @return Cell * @return Cell
*/ */
public function setValueExplicit($pValue, $pDataType) public function setValueExplicit($value, $dataType)
{ {
// set the value according to data type // set the value according to data type
switch ($pDataType) { switch ($dataType) {
case DataType::TYPE_NULL: case DataType::TYPE_NULL:
$this->value = $pValue; $this->value = $value;
break; break;
case DataType::TYPE_STRING2: case DataType::TYPE_STRING2:
$pDataType = DataType::TYPE_STRING; $dataType = DataType::TYPE_STRING;
// no break // no break
case DataType::TYPE_STRING: case DataType::TYPE_STRING:
// Synonym for string // Synonym for string
case DataType::TYPE_INLINE: case DataType::TYPE_INLINE:
// Rich text // Rich text
$this->value = DataType::checkString($pValue); $this->value = DataType::checkString($value);
break; break;
case DataType::TYPE_NUMERIC: case DataType::TYPE_NUMERIC:
if (is_string($pValue) && !is_numeric($pValue)) { if (is_string($value) && !is_numeric($value)) {
throw new Exception('Invalid numeric value for datatype Numeric'); throw new Exception('Invalid numeric value for datatype Numeric');
} }
$this->value = 0 + $pValue; $this->value = 0 + $value;
break; break;
case DataType::TYPE_FORMULA: case DataType::TYPE_FORMULA:
$this->value = (string) $pValue; $this->value = (string) $value;
break; break;
case DataType::TYPE_BOOL: case DataType::TYPE_BOOL:
$this->value = (bool) $pValue; $this->value = (bool) $value;
break; break;
case DataType::TYPE_ERROR: case DataType::TYPE_ERROR:
$this->value = DataType::checkErrorCode($pValue); $this->value = DataType::checkErrorCode($value);
break; break;
default: default:
throw new Exception('Invalid datatype: ' . $pDataType); throw new Exception('Invalid datatype: ' . $dataType);
break; break;
} }
// set the datatype // set the datatype
$this->dataType = $pDataType; $this->dataType = $dataType;
return $this->updateInCollection(); return $this->updateInCollection();
} }
@ -292,14 +292,14 @@ class Cell
/** /**
* Set old calculated value (cached). * Set old calculated value (cached).
* *
* @param mixed $pValue Value * @param mixed $originalValue Value
* *
* @return Cell * @return Cell
*/ */
public function setCalculatedValue($pValue) public function setCalculatedValue($originalValue)
{ {
if ($pValue !== null) { if ($originalValue !== null) {
$this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; $this->calculatedValue = (is_numeric($originalValue)) ? (float) $originalValue : $originalValue;
} }
return $this->updateInCollection(); return $this->updateInCollection();
@ -333,16 +333,16 @@ class Cell
/** /**
* Set cell data type. * Set cell data type.
* *
* @param string $pDataType see DataType::TYPE_* * @param string $dataType see DataType::TYPE_*
* *
* @return Cell * @return Cell
*/ */
public function setDataType($pDataType) public function setDataType($dataType)
{ {
if ($pDataType == DataType::TYPE_STRING2) { if ($dataType == DataType::TYPE_STRING2) {
$pDataType = DataType::TYPE_STRING; $dataType = DataType::TYPE_STRING;
} }
$this->dataType = $pDataType; $this->dataType = $dataType;
return $this->updateInCollection(); return $this->updateInCollection();
} }
@ -388,17 +388,17 @@ class Cell
/** /**
* Set Data validation rules. * Set Data validation rules.
* *
* @param DataValidation $pDataValidation * @param DataValidation $dataValidation
* *
* @return Cell * @return Cell
*/ */
public function setDataValidation(?DataValidation $pDataValidation = null) public function setDataValidation(?DataValidation $dataValidation = null)
{ {
if (!isset($this->parent)) { if (!isset($this->parent)) {
throw new Exception('Cannot set data validation for cell that is not bound to a worksheet'); throw new Exception('Cannot set data validation for cell that is not bound to a worksheet');
} }
$this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation); $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation);
return $this->updateInCollection(); return $this->updateInCollection();
} }
@ -446,17 +446,17 @@ class Cell
/** /**
* Set Hyperlink. * Set Hyperlink.
* *
* @param Hyperlink $pHyperlink * @param Hyperlink $hyperlink
* *
* @return Cell * @return Cell
*/ */
public function setHyperlink(?Hyperlink $pHyperlink = null) public function setHyperlink(?Hyperlink $hyperlink = null)
{ {
if (!isset($this->parent)) { if (!isset($this->parent)) {
throw new Exception('Cannot set hyperlink for cell that is not bound to a worksheet'); throw new Exception('Cannot set hyperlink for cell that is not bound to a worksheet');
} }
$this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink); $this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink);
return $this->updateInCollection(); return $this->updateInCollection();
} }
@ -550,13 +550,13 @@ class Cell
/** /**
* Is cell in a specific range? * Is cell in a specific range?
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $range Cell range (e.g. A1:A1)
* *
* @return bool * @return bool
*/ */
public function isInRange($pRange) public function isInRange($range)
{ {
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
// Translate properties // Translate properties
$myColumn = Coordinate::columnIndexFromString($this->getColumn()); $myColumn = Coordinate::columnIndexFromString($this->getColumn());
@ -638,13 +638,13 @@ class Cell
/** /**
* Set index to cellXf. * Set index to cellXf.
* *
* @param int $pValue * @param int $indexValue
* *
* @return Cell * @return Cell
*/ */
public function setXfIndex($pValue) public function setXfIndex($indexValue)
{ {
$this->xfIndex = $pValue; $this->xfIndex = $indexValue;
return $this->updateInCollection(); return $this->updateInCollection();
} }
@ -652,13 +652,13 @@ class Cell
/** /**
* Set the formula attributes. * Set the formula attributes.
* *
* @param mixed $pAttributes * @param mixed $attributes
* *
* @return $this * @return $this
*/ */
public function setFormulaAttributes($pAttributes) public function setFormulaAttributes($attributes)
{ {
$this->formulaAttributes = $pAttributes; $this->formulaAttributes = $attributes;
return $this; return $this;
} }

View File

@ -25,21 +25,21 @@ abstract class Coordinate
/** /**
* Coordinate from string. * Coordinate from string.
* *
* @param string $pCoordinateString eg: 'A1' * @param string $cellAddress eg: 'A1'
* *
* @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1) * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1)
*/ */
public static function coordinateFromString($pCoordinateString) public static function coordinateFromString($cellAddress)
{ {
if (preg_match(self::A1_COORDINATE_REGEX, $pCoordinateString, $matches)) { if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) {
return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']]; return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']];
} elseif (self::coordinateIsRange($pCoordinateString)) { } elseif (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells'); throw new Exception('Cell coordinate string can not be a range of cells');
} elseif ($pCoordinateString == '') { } elseif ($cellAddress == '') {
throw new Exception('Cell coordinate can not be zero-length string'); throw new Exception('Cell coordinate can not be zero-length string');
} }
throw new Exception('Invalid cell coordinate ' . $pCoordinateString); throw new Exception('Invalid cell coordinate ' . $cellAddress);
} }
/** /**
@ -60,68 +60,68 @@ abstract class Coordinate
} }
/** /**
* Checks if a coordinate represents a range of cells. * Checks if a Cell Address represents a range of cells.
* *
* @param string $coord eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2' * @param string $cellAddress eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2'
* *
* @return bool Whether the coordinate represents a range of cells * @return bool Whether the coordinate represents a range of cells
*/ */
public static function coordinateIsRange($coord) public static function coordinateIsRange($cellAddress)
{ {
return (strpos($coord, ':') !== false) || (strpos($coord, ',') !== false); return (strpos($cellAddress, ':') !== false) || (strpos($cellAddress, ',') !== false);
} }
/** /**
* Make string row, column or cell coordinate absolute. * Make string row, column or cell coordinate absolute.
* *
* @param string $pCoordinateString e.g. 'A' or '1' or 'A1' * @param string $cellAddress e.g. 'A' or '1' or 'A1'
* Note that this value can be a row or column reference as well as a cell reference * Note that this value can be a row or column reference as well as a cell reference
* *
* @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
*/ */
public static function absoluteReference($pCoordinateString) public static function absoluteReference($cellAddress)
{ {
if (self::coordinateIsRange($pCoordinateString)) { if (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells'); throw new Exception('Cell coordinate string can not be a range of cells');
} }
// Split out any worksheet name from the reference // Split out any worksheet name from the reference
[$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true); [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
if ($worksheet > '') { if ($worksheet > '') {
$worksheet .= '!'; $worksheet .= '!';
} }
// Create absolute coordinate // Create absolute coordinate
if (ctype_digit($pCoordinateString)) { if (ctype_digit($cellAddress)) {
return $worksheet . '$' . $pCoordinateString; return $worksheet . '$' . $cellAddress;
} elseif (ctype_alpha($pCoordinateString)) { } elseif (ctype_alpha($cellAddress)) {
return $worksheet . '$' . strtoupper($pCoordinateString); return $worksheet . '$' . strtoupper($cellAddress);
} }
return $worksheet . self::absoluteCoordinate($pCoordinateString); return $worksheet . self::absoluteCoordinate($cellAddress);
} }
/** /**
* Make string coordinate absolute. * Make string coordinate absolute.
* *
* @param string $pCoordinateString e.g. 'A1' * @param string $cellAddress e.g. 'A1'
* *
* @return string Absolute coordinate e.g. '$A$1' * @return string Absolute coordinate e.g. '$A$1'
*/ */
public static function absoluteCoordinate($pCoordinateString) public static function absoluteCoordinate($cellAddress)
{ {
if (self::coordinateIsRange($pCoordinateString)) { if (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells'); throw new Exception('Cell coordinate string can not be a range of cells');
} }
// Split out any worksheet name from the coordinate // Split out any worksheet name from the coordinate
[$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true); [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
if ($worksheet > '') { if ($worksheet > '') {
$worksheet .= '!'; $worksheet .= '!';
} }
// Create absolute coordinate // Create absolute coordinate
[$column, $row] = self::coordinateFromString($pCoordinateString); [$column, $row] = self::coordinateFromString($cellAddress);
$column = ltrim($column, '$'); $column = ltrim($column, '$');
$row = ltrim($row, '$'); $row = ltrim($row, '$');
@ -131,20 +131,20 @@ abstract class Coordinate
/** /**
* Split range into coordinate strings. * Split range into coordinate strings.
* *
* @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' * @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
* *
* @return array Array containing one or more arrays containing one or two coordinate strings * @return array Array containing one or more arrays containing one or two coordinate strings
* e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']] * e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']]
* or ['B4'] * or ['B4']
*/ */
public static function splitRange($pRange) public static function splitRange($range)
{ {
// Ensure $pRange is a valid range // Ensure $pRange is a valid range
if (empty($pRange)) { if (empty($range)) {
$pRange = self::DEFAULT_RANGE; $range = self::DEFAULT_RANGE;
} }
$exploded = explode(',', $pRange); $exploded = explode(',', $range);
$counter = count($exploded); $counter = count($exploded);
for ($i = 0; $i < $counter; ++$i) { for ($i = 0; $i < $counter; ++$i) {
$exploded[$i] = explode(':', $exploded[$i]); $exploded[$i] = explode(':', $exploded[$i]);
@ -156,49 +156,49 @@ abstract class Coordinate
/** /**
* Build range from coordinate strings. * Build range from coordinate strings.
* *
* @param array $pRange Array containg one or more arrays containing one or two coordinate strings * @param array $range Array containing one or more arrays containing one or two coordinate strings
* *
* @return string String representation of $pRange * @return string String representation of $pRange
*/ */
public static function buildRange(array $pRange) public static function buildRange(array $range)
{ {
// Verify range // Verify range
if (empty($pRange) || !is_array($pRange[0])) { if (empty($range) || !is_array($range[0])) {
throw new Exception('Range does not contain any information'); throw new Exception('Range does not contain any information');
} }
// Build range // Build range
$counter = count($pRange); $counter = count($range);
for ($i = 0; $i < $counter; ++$i) { for ($i = 0; $i < $counter; ++$i) {
$pRange[$i] = implode(':', $pRange[$i]); $range[$i] = implode(':', $range[$i]);
} }
return implode(',', $pRange); return implode(',', $range);
} }
/** /**
* Calculate range boundaries. * Calculate range boundaries.
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $range Cell range (e.g. A1:A1)
* *
* @return array Range coordinates [Start Cell, End Cell] * @return array Range coordinates [Start Cell, End Cell]
* where Start Cell and End Cell are arrays (Column Number, Row Number) * where Start Cell and End Cell are arrays (Column Number, Row Number)
*/ */
public static function rangeBoundaries($pRange) public static function rangeBoundaries($range)
{ {
// Ensure $pRange is a valid range // Ensure $pRange is a valid range
if (empty($pRange)) { if (empty($range)) {
$pRange = self::DEFAULT_RANGE; $range = self::DEFAULT_RANGE;
} }
// Uppercase coordinate // Uppercase coordinate
$pRange = strtoupper($pRange); $range = strtoupper($range);
// Extract range // Extract range
if (strpos($pRange, ':') === false) { if (strpos($range, ':') === false) {
$rangeA = $rangeB = $pRange; $rangeA = $rangeB = $range;
} else { } else {
[$rangeA, $rangeB] = explode(':', $pRange); [$rangeA, $rangeB] = explode(':', $range);
} }
// Calculate range outer borders // Calculate range outer borders
@ -215,14 +215,14 @@ abstract class Coordinate
/** /**
* Calculate range dimension. * Calculate range dimension.
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $range Cell range (e.g. A1:A1)
* *
* @return array Range dimension (width, height) * @return array Range dimension (width, height)
*/ */
public static function rangeDimension($pRange) public static function rangeDimension($range)
{ {
// Calculate range outer borders // Calculate range outer borders
[$rangeStart, $rangeEnd] = self::rangeBoundaries($pRange); [$rangeStart, $rangeEnd] = self::rangeBoundaries($range);
return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)]; return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)];
} }
@ -230,26 +230,26 @@ abstract class Coordinate
/** /**
* Calculate range boundaries. * Calculate range boundaries.
* *
* @param string $pRange Cell range (e.g. A1:A1) * @param string $range Cell range (e.g. A1:A1)
* *
* @return array Range coordinates [Start Cell, End Cell] * @return array Range coordinates [Start Cell, End Cell]
* where Start Cell and End Cell are arrays [Column ID, Row Number] * where Start Cell and End Cell are arrays [Column ID, Row Number]
*/ */
public static function getRangeBoundaries($pRange) public static function getRangeBoundaries($range)
{ {
// Ensure $pRange is a valid range // Ensure $pRange is a valid range
if (empty($pRange)) { if (empty($range)) {
$pRange = self::DEFAULT_RANGE; $range = self::DEFAULT_RANGE;
} }
// Uppercase coordinate // Uppercase coordinate
$pRange = strtoupper($pRange); $range = strtoupper($range);
// Extract range // Extract range
if (strpos($pRange, ':') === false) { if (strpos($range, ':') === false) {
$rangeA = $rangeB = $pRange; $rangeA = $rangeB = $range;
} else { } else {
[$rangeA, $rangeB] = explode(':', $pRange); [$rangeA, $rangeB] = explode(':', $range);
} }
return [self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)]; return [self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)];
@ -258,19 +258,19 @@ abstract class Coordinate
/** /**
* Column index from string. * Column index from string.
* *
* @param string $pString eg 'A' * @param string $columnAddress eg 'A'
* *
* @return int Column index (A = 1) * @return int Column index (A = 1)
*/ */
public static function columnIndexFromString($pString) public static function columnIndexFromString($columnAddress)
{ {
// Using a lookup cache adds a slight memory overhead, but boosts speed // Using a lookup cache adds a slight memory overhead, but boosts speed
// caching using a static within the method is faster than a class static, // caching using a static within the method is faster than a class static,
// though it's additional memory overhead // though it's additional memory overhead
static $indexCache = []; static $indexCache = [];
if (isset($indexCache[$pString])) { if (isset($indexCache[$columnAddress])) {
return $indexCache[$pString]; return $indexCache[$columnAddress];
} }
// It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord() // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord()
// and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant
@ -284,23 +284,23 @@ abstract class Coordinate
// We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString
// for improved performance // for improved performance
if (isset($pString[0])) { if (isset($columnAddress[0])) {
if (!isset($pString[1])) { if (!isset($columnAddress[1])) {
$indexCache[$pString] = $columnLookup[$pString]; $indexCache[$columnAddress] = $columnLookup[$columnAddress];
return $indexCache[$pString]; return $indexCache[$columnAddress];
} elseif (!isset($pString[2])) { } elseif (!isset($columnAddress[2])) {
$indexCache[$pString] = $columnLookup[$pString[0]] * 26 + $columnLookup[$pString[1]]; $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26 + $columnLookup[$columnAddress[1]];
return $indexCache[$pString]; return $indexCache[$columnAddress];
} elseif (!isset($pString[3])) { } elseif (!isset($columnAddress[3])) {
$indexCache[$pString] = $columnLookup[$pString[0]] * 676 + $columnLookup[$pString[1]] * 26 + $columnLookup[$pString[2]]; $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 676 + $columnLookup[$columnAddress[1]] * 26 + $columnLookup[$columnAddress[2]];
return $indexCache[$pString]; return $indexCache[$columnAddress];
} }
} }
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($columnAddress[0])) ? 'longer than 3 characters' : 'empty'));
} }
/** /**
@ -456,16 +456,16 @@ abstract class Coordinate
* *
* [ 'A1:A3' => 'x', 'A4' => 'y' ] * [ 'A1:A3' => 'x', 'A4' => 'y' ]
* *
* @param array $pCoordCollection associative array mapping coordinates to values * @param array $coordinateCollection associative array mapping coordinates to values
* *
* @return array associative array mapping coordinate ranges to valuea * @return array associative array mapping coordinate ranges to valuea
*/ */
public static function mergeRangesInCollection(array $pCoordCollection) public static function mergeRangesInCollection(array $coordinateCollection)
{ {
$hashedValues = []; $hashedValues = [];
$mergedCoordCollection = []; $mergedCoordCollection = [];
foreach ($pCoordCollection as $coord => $value) { foreach ($coordinateCollection as $coord => $value) {
if (self::coordinateIsRange($coord)) { if (self::coordinateIsRange($coord)) {
$mergedCoordCollection[$coord] = $value; $mergedCoordCollection[$coord] = $value;

View File

@ -45,41 +45,41 @@ class DataType
/** /**
* Check a string that it satisfies Excel requirements. * Check a string that it satisfies Excel requirements.
* *
* @param null|RichText|string $pValue Value to sanitize to an Excel string * @param null|RichText|string $textValue Value to sanitize to an Excel string
* *
* @return null|RichText|string Sanitized value * @return null|RichText|string Sanitized value
*/ */
public static function checkString($pValue) public static function checkString($textValue)
{ {
if ($pValue instanceof RichText) { if ($textValue instanceof RichText) {
// TODO: Sanitize Rich-Text string (max. character count is 32,767) // TODO: Sanitize Rich-Text string (max. character count is 32,767)
return $pValue; return $textValue;
} }
// string must never be longer than 32,767 characters, truncate if necessary // string must never be longer than 32,767 characters, truncate if necessary
$pValue = StringHelper::substring($pValue, 0, 32767); $textValue = StringHelper::substring($textValue, 0, 32767);
// we require that newline is represented as "\n" in core, not as "\r\n" or "\r" // we require that newline is represented as "\n" in core, not as "\r\n" or "\r"
$pValue = str_replace(["\r\n", "\r"], "\n", $pValue); $textValue = str_replace(["\r\n", "\r"], "\n", $textValue);
return $pValue; return $textValue;
} }
/** /**
* Check a value that it is a valid error code. * Check a value that it is a valid error code.
* *
* @param mixed $pValue Value to sanitize to an Excel error code * @param mixed $value Value to sanitize to an Excel error code
* *
* @return string Sanitized value * @return string Sanitized value
*/ */
public static function checkErrorCode($pValue) public static function checkErrorCode($value)
{ {
$pValue = (string) $pValue; $value = (string) $value;
if (!isset(self::$errorCodes[$pValue])) { if (!isset(self::$errorCodes[$value])) {
$pValue = '#NULL!'; $value = '#NULL!';
} }
return $pValue; return $value;
} }
} }

View File

@ -140,13 +140,13 @@ class DataValidation
/** /**
* Set Formula 1. * Set Formula 1.
* *
* @param string $value * @param string $formula
* *
* @return $this * @return $this
*/ */
public function setFormula1($value) public function setFormula1($formula)
{ {
$this->formula1 = $value; $this->formula1 = $formula;
return $this; return $this;
} }
@ -164,13 +164,13 @@ class DataValidation
/** /**
* Set Formula 2. * Set Formula 2.
* *
* @param string $value * @param string $formula
* *
* @return $this * @return $this
*/ */
public function setFormula2($value) public function setFormula2($formula)
{ {
$this->formula2 = $value; $this->formula2 = $formula;
return $this; return $this;
} }
@ -188,13 +188,13 @@ class DataValidation
/** /**
* Set Type. * Set Type.
* *
* @param string $value * @param string $type
* *
* @return $this * @return $this
*/ */
public function setType($value) public function setType($type)
{ {
$this->type = $value; $this->type = $type;
return $this; return $this;
} }
@ -212,13 +212,13 @@ class DataValidation
/** /**
* Set Error style. * Set Error style.
* *
* @param string $value see self::STYLE_* * @param string $errorStyle see self::STYLE_*
* *
* @return $this * @return $this
*/ */
public function setErrorStyle($value) public function setErrorStyle($errorStyle)
{ {
$this->errorStyle = $value; $this->errorStyle = $errorStyle;
return $this; return $this;
} }
@ -236,13 +236,13 @@ class DataValidation
/** /**
* Set Operator. * Set Operator.
* *
* @param string $value * @param string $operator
* *
* @return $this * @return $this
*/ */
public function setOperator($value) public function setOperator($operator)
{ {
$this->operator = $value; $this->operator = $operator;
return $this; return $this;
} }
@ -260,13 +260,13 @@ class DataValidation
/** /**
* Set Allow Blank. * Set Allow Blank.
* *
* @param bool $value * @param bool $allowBlank
* *
* @return $this * @return $this
*/ */
public function setAllowBlank($value) public function setAllowBlank($allowBlank)
{ {
$this->allowBlank = $value; $this->allowBlank = $allowBlank;
return $this; return $this;
} }
@ -284,13 +284,13 @@ class DataValidation
/** /**
* Set Show DropDown. * Set Show DropDown.
* *
* @param bool $value * @param bool $showDropDown
* *
* @return $this * @return $this
*/ */
public function setShowDropDown($value) public function setShowDropDown($showDropDown)
{ {
$this->showDropDown = $value; $this->showDropDown = $showDropDown;
return $this; return $this;
} }
@ -308,13 +308,13 @@ class DataValidation
/** /**
* Set Show InputMessage. * Set Show InputMessage.
* *
* @param bool $value * @param bool $showInputMessage
* *
* @return $this * @return $this
*/ */
public function setShowInputMessage($value) public function setShowInputMessage($showInputMessage)
{ {
$this->showInputMessage = $value; $this->showInputMessage = $showInputMessage;
return $this; return $this;
} }
@ -332,13 +332,13 @@ class DataValidation
/** /**
* Set Show ErrorMessage. * Set Show ErrorMessage.
* *
* @param bool $value * @param bool $showErrorMessage
* *
* @return $this * @return $this
*/ */
public function setShowErrorMessage($value) public function setShowErrorMessage($showErrorMessage)
{ {
$this->showErrorMessage = $value; $this->showErrorMessage = $showErrorMessage;
return $this; return $this;
} }
@ -356,13 +356,13 @@ class DataValidation
/** /**
* Set Error title. * Set Error title.
* *
* @param string $value * @param string $errorTitle
* *
* @return $this * @return $this
*/ */
public function setErrorTitle($value) public function setErrorTitle($errorTitle)
{ {
$this->errorTitle = $value; $this->errorTitle = $errorTitle;
return $this; return $this;
} }
@ -380,13 +380,13 @@ class DataValidation
/** /**
* Set Error. * Set Error.
* *
* @param string $value * @param string $error
* *
* @return $this * @return $this
*/ */
public function setError($value) public function setError($error)
{ {
$this->error = $value; $this->error = $error;
return $this; return $this;
} }
@ -404,13 +404,13 @@ class DataValidation
/** /**
* Set Prompt title. * Set Prompt title.
* *
* @param string $value * @param string $promptTitle
* *
* @return $this * @return $this
*/ */
public function setPromptTitle($value) public function setPromptTitle($promptTitle)
{ {
$this->promptTitle = $value; $this->promptTitle = $promptTitle;
return $this; return $this;
} }
@ -428,13 +428,13 @@ class DataValidation
/** /**
* Set Prompt. * Set Prompt.
* *
* @param string $value * @param string $prompt
* *
* @return $this * @return $this
*/ */
public function setPrompt($value) public function setPrompt($prompt)
{ {
$this->prompt = $value; $this->prompt = $prompt;
return $this; return $this;
} }

View File

@ -21,14 +21,14 @@ class Hyperlink
/** /**
* Create a new Hyperlink. * Create a new Hyperlink.
* *
* @param string $pUrl Url to link the cell to * @param string $url Url to link the cell to
* @param string $pTooltip Tooltip to display on the hyperlink * @param string $tooltip Tooltip to display on the hyperlink
*/ */
public function __construct($pUrl = '', $pTooltip = '') public function __construct($url = '', $tooltip = '')
{ {
// Initialise member variables // Initialise member variables
$this->url = $pUrl; $this->url = $url;
$this->tooltip = $pTooltip; $this->tooltip = $tooltip;
} }
/** /**
@ -44,13 +44,13 @@ class Hyperlink
/** /**
* Set URL. * Set URL.
* *
* @param string $value * @param string $url
* *
* @return $this * @return $this
*/ */
public function setUrl($value) public function setUrl($url)
{ {
$this->url = $value; $this->url = $url;
return $this; return $this;
} }
@ -68,13 +68,13 @@ class Hyperlink
/** /**
* Set tooltip. * Set tooltip.
* *
* @param string $value * @param string $tooltip
* *
* @return $this * @return $this
*/ */
public function setTooltip($value) public function setTooltip($tooltip)
{ {
$this->tooltip = $value; $this->tooltip = $tooltip;
return $this; return $this;
} }

View File

@ -165,30 +165,30 @@ class Axis extends Properties
/** /**
* Set Axis Options Properties. * Set Axis Options Properties.
* *
* @param string $axis_labels * @param string $axisLabels
* @param string $horizontal_crosses_value * @param string $horizontalCrossesValue
* @param string $horizontal_crosses * @param string $horizontalCrosses
* @param string $axis_orientation * @param string $axisOrientation
* @param string $major_tmt * @param string $majorTmt
* @param string $minor_tmt * @param string $minorTmt
* @param string $minimum * @param string $minimum
* @param string $maximum * @param string $maximum
* @param string $major_unit * @param string $majorUnit
* @param string $minor_unit * @param string $minorUnit
*/ */
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): void public function setAxisOptionsProperties($axisLabels, $horizontalCrossesValue = null, $horizontalCrosses = null, $axisOrientation = null, $majorTmt = null, $minorTmt = null, $minimum = null, $maximum = null, $majorUnit = null, $minorUnit = null): void
{ {
$this->axisOptions['axis_labels'] = (string) $axis_labels; $this->axisOptions['axis_labels'] = (string) $axisLabels;
($horizontal_crosses_value !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null; ($horizontalCrossesValue !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontalCrossesValue : null;
($horizontal_crosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontal_crosses : null; ($horizontalCrosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontalCrosses : null;
($axis_orientation !== null) ? $this->axisOptions['orientation'] = (string) $axis_orientation : null; ($axisOrientation !== null) ? $this->axisOptions['orientation'] = (string) $axisOrientation : null;
($major_tmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $major_tmt : null; ($majorTmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $majorTmt : null;
($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null;
($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null;
($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null; ($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null;
($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null; ($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null;
($major_unit !== null) ? $this->axisOptions['major_unit'] = (string) $major_unit : null; ($majorUnit !== null) ? $this->axisOptions['major_unit'] = (string) $majorUnit : null;
($minor_unit !== null) ? $this->axisOptions['minor_unit'] = (string) $minor_unit : null; ($minorUnit !== null) ? $this->axisOptions['minor_unit'] = (string) $minorUnit : null;
} }
/** /**
@ -218,11 +218,11 @@ class Axis extends Properties
* *
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $AlphaType
*/ */
public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB): void public function setFillParameters($color, $alpha = 0, $AlphaType = self::EXCEL_COLOR_TYPE_ARGB): void
{ {
$this->fillProperties = $this->setColorProperties($color, $alpha, $type); $this->fillProperties = $this->setColorProperties($color, $alpha, $AlphaType);
} }
/** /**
@ -230,11 +230,11 @@ class Axis extends Properties
* *
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $alphaType
*/ */
public function setLineParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB): void public function setLineParameters($color, $alpha = 0, $alphaType = self::EXCEL_COLOR_TYPE_ARGB): void
{ {
$this->lineProperties = $this->setColorProperties($color, $alpha, $type); $this->lineProperties = $this->setColorProperties($color, $alpha, $alphaType);
} }
/** /**
@ -264,27 +264,27 @@ class Axis extends Properties
/** /**
* Set Line Style Properties. * Set Line Style Properties.
* *
* @param float $line_width * @param float $lineWidth
* @param string $compound_type * @param string $compoundType
* @param string $dash_type * @param string $dashType
* @param string $cap_type * @param string $capType
* @param string $join_type * @param string $joinType
* @param string $head_arrow_type * @param string $headArrowType
* @param string $head_arrow_size * @param string $headArrowSize
* @param string $end_arrow_type * @param string $endArrowType
* @param string $end_arrow_size * @param string $endArrowSize
*/ */
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): void public function setLineStyleProperties($lineWidth = null, $compoundType = null, $dashType = null, $capType = null, $joinType = null, $headArrowType = null, $headArrowSize = null, $endArrowType = null, $endArrowSize = null): void
{ {
($line_width !== null) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $line_width) : null; ($lineWidth !== null) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $lineWidth) : null;
($compound_type !== null) ? $this->lineStyleProperties['compound'] = (string) $compound_type : null; ($compoundType !== null) ? $this->lineStyleProperties['compound'] = (string) $compoundType : null;
($dash_type !== null) ? $this->lineStyleProperties['dash'] = (string) $dash_type : null; ($dashType !== null) ? $this->lineStyleProperties['dash'] = (string) $dashType : null;
($cap_type !== null) ? $this->lineStyleProperties['cap'] = (string) $cap_type : null; ($capType !== null) ? $this->lineStyleProperties['cap'] = (string) $capType : null;
($join_type !== null) ? $this->lineStyleProperties['join'] = (string) $join_type : null; ($joinType !== null) ? $this->lineStyleProperties['join'] = (string) $joinType : null;
($head_arrow_type !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $head_arrow_type : null; ($headArrowType !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $headArrowType : null;
($head_arrow_size !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $head_arrow_size : null; ($headArrowSize !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $headArrowSize : null;
($end_arrow_type !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $end_arrow_type : null; ($endArrowType !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $endArrowType : null;
($end_arrow_size !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $end_arrow_size : null; ($endArrowSize !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $endArrowSize : null;
} }
/** /**
@ -326,38 +326,38 @@ class Axis extends Properties
/** /**
* Set Shadow Properties. * Set Shadow Properties.
* *
* @param int $sh_presets * @param int $shadowPresets
* @param string $sh_color_value * @param string $colorValue
* @param string $sh_color_type * @param string $colorType
* @param string $sh_color_alpha * @param string $colorAlpha
* @param float $sh_blur * @param float $blur
* @param int $sh_angle * @param int $angle
* @param float $sh_distance * @param float $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): void public function setShadowProperties($shadowPresets, $colorValue = null, $colorType = null, $colorAlpha = null, $blur = null, $angle = null, $distance = null): void
{ {
$this->setShadowPresetsProperties((int) $sh_presets) $this->setShadowPresetsProperties((int) $shadowPresets)
->setShadowColor( ->setShadowColor(
$sh_color_value ?? $this->shadowProperties['color']['value'], $colorValue ?? $this->shadowProperties['color']['value'],
$sh_color_alpha ?? (int) $this->shadowProperties['color']['alpha'], $colorAlpha ?? (int) $this->shadowProperties['color']['alpha'],
$sh_color_type ?? $this->shadowProperties['color']['type'] $colorType ?? $this->shadowProperties['color']['type']
) )
->setShadowBlur($sh_blur) ->setShadowBlur($blur)
->setShadowAngle($sh_angle) ->setShadowAngle($angle)
->setShadowDistance($sh_distance); ->setShadowDistance($distance);
} }
/** /**
* Set Shadow Color. * Set Shadow Color.
* *
* @param int $shadow_presets * @param int $presets
* *
* @return $this * @return $this
*/ */
private function setShadowPresetsProperties($shadow_presets) private function setShadowPresetsProperties($presets)
{ {
$this->shadowProperties['presets'] = $shadow_presets; $this->shadowProperties['presets'] = $presets;
$this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets));
return $this; return $this;
} }
@ -369,17 +369,17 @@ class Axis extends Properties
* *
* @return $this * @return $this
*/ */
private function setShadowProperiesMapValues(array $properties_map, &$reference = null) private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null)
{ {
$base_reference = $reference; $base_reference = $reference;
foreach ($properties_map as $property_key => $property_val) { foreach ($propertiesMap as $property_key => $property_val) {
if (is_array($property_val)) { if (is_array($property_val)) {
if ($reference === null) { if ($reference === null) {
$reference = &$this->shadowProperties[$property_key]; $reference = &$this->shadowProperties[$property_key];
} else { } else {
$reference = &$reference[$property_key]; $reference = &$reference[$property_key];
} }
$this->setShadowProperiesMapValues($property_val, $reference); $this->setShadowPropertiesMapValues($property_val, $reference);
} else { } else {
if ($base_reference === null) { if ($base_reference === null) {
$this->shadowProperties[$property_key] = $property_val; $this->shadowProperties[$property_key] = $property_val;
@ -397,13 +397,13 @@ class Axis extends Properties
* *
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $alphaType
* *
* @return $this * @return $this
*/ */
private function setShadowColor($color, $alpha, $type) private function setShadowColor($color, $alpha, $alphaType)
{ {
$this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $type); $this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $alphaType);
return $this; return $this;
} }
@ -472,17 +472,17 @@ class Axis extends Properties
* Set Glow Properties. * Set Glow Properties.
* *
* @param float $size * @param float $size
* @param string $color_value * @param string $colorValue
* @param int $color_alpha * @param int $colorAlpha
* @param string $color_type * @param string $colorType
*/ */
public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null): void public function setGlowProperties($size, $colorValue = null, $colorAlpha = null, $colorType = null): void
{ {
$this->setGlowSize($size) $this->setGlowSize($size)
->setGlowColor( ->setGlowColor(
$color_value ?? $this->glowProperties['color']['value'], $colorValue ?? $this->glowProperties['color']['value'],
$color_alpha ?? (int) $this->glowProperties['color']['alpha'], $colorAlpha ?? (int) $this->glowProperties['color']['alpha'],
$color_type ?? $this->glowProperties['color']['type'] $colorType ?? $this->glowProperties['color']['type']
); );
} }
@ -519,13 +519,13 @@ class Axis extends Properties
* *
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $colorType
* *
* @return $this * @return $this
*/ */
private function setGlowColor($color, $alpha, $type) private function setGlowColor($color, $alpha, $colorType)
{ {
$this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $type); $this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $colorType);
return $this; return $this;
} }

View File

@ -186,13 +186,13 @@ class Chart
/** /**
* Set Worksheet. * Set Worksheet.
* *
* @param Worksheet $pValue * @param Worksheet $worksheet
* *
* @return $this * @return $this
*/ */
public function setWorksheet(?Worksheet $pValue = null) public function setWorksheet(?Worksheet $worksheet = null)
{ {
$this->worksheet = $pValue; $this->worksheet = $worksheet;
return $this; return $this;
} }

View File

@ -105,73 +105,73 @@ class GridLines extends Properties
* *
* @param string $value * @param string $value
* @param int $alpha * @param int $alpha
* @param string $type * @param string $colorType
*/ */
public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD): void public function setLineColorProperties($value, $alpha = 0, $colorType = self::EXCEL_COLOR_TYPE_STANDARD): void
{ {
$this->activateObject() $this->activateObject()
->lineProperties['color'] = $this->setColorProperties( ->lineProperties['color'] = $this->setColorProperties(
$value, $value,
$alpha, $alpha,
$type $colorType
); );
} }
/** /**
* Set Line Color Properties. * Set Line Color Properties.
* *
* @param float $line_width * @param float $lineWidth
* @param string $compound_type * @param string $compoundType
* @param string $dash_type * @param string $dashType
* @param string $cap_type * @param string $capType
* @param string $join_type * @param string $joinType
* @param string $head_arrow_type * @param string $headArrowType
* @param string $head_arrow_size * @param string $headArrowSize
* @param string $end_arrow_type * @param string $endArrowType
* @param string $end_arrow_size * @param string $endArrowSize
*/ */
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): void public function setLineStyleProperties($lineWidth = null, $compoundType = null, $dashType = null, $capType = null, $joinType = null, $headArrowType = null, $headArrowSize = null, $endArrowType = null, $endArrowSize = null): void
{ {
$this->activateObject(); $this->activateObject();
($line_width !== null) ($lineWidth !== null)
? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $line_width) ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $lineWidth)
: null; : null;
($compound_type !== null) ($compoundType !== null)
? $this->lineProperties['style']['compound'] = (string) $compound_type ? $this->lineProperties['style']['compound'] = (string) $compoundType
: null; : null;
($dash_type !== null) ($dashType !== null)
? $this->lineProperties['style']['dash'] = (string) $dash_type ? $this->lineProperties['style']['dash'] = (string) $dashType
: null; : null;
($cap_type !== null) ($capType !== null)
? $this->lineProperties['style']['cap'] = (string) $cap_type ? $this->lineProperties['style']['cap'] = (string) $capType
: null; : null;
($join_type !== null) ($joinType !== null)
? $this->lineProperties['style']['join'] = (string) $join_type ? $this->lineProperties['style']['join'] = (string) $joinType
: null; : null;
($head_arrow_type !== null) ($headArrowType !== null)
? $this->lineProperties['style']['arrow']['head']['type'] = (string) $head_arrow_type ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $headArrowType
: null; : null;
($head_arrow_size !== null) ($headArrowSize !== null)
? $this->lineProperties['style']['arrow']['head']['size'] = (string) $head_arrow_size ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $headArrowSize
: null; : null;
($end_arrow_type !== null) ($endArrowType !== null)
? $this->lineProperties['style']['arrow']['end']['type'] = (string) $end_arrow_type ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $endArrowType
: null; : null;
($end_arrow_size !== null) ($endArrowSize !== null)
? $this->lineProperties['style']['arrow']['end']['size'] = (string) $end_arrow_size ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $endArrowSize
: null; : null;
} }
/** /**
* Get Line Color Property. * Get Line Color Property.
* *
* @param string $parameter * @param string $propertyName
* *
* @return string * @return string
*/ */
public function getLineColorProperty($parameter) public function getLineColorProperty($propertyName)
{ {
return $this->lineProperties['color'][$parameter]; return $this->lineProperties['color'][$propertyName];
} }
/** /**
@ -190,28 +190,28 @@ class GridLines extends Properties
* Set Glow Properties. * Set Glow Properties.
* *
* @param float $size * @param float $size
* @param string $color_value * @param string $colorValue
* @param int $color_alpha * @param int $colorAlpha
* @param string $color_type * @param string $colorType
*/ */
public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null): void public function setGlowProperties($size, $colorValue = null, $colorAlpha = null, $colorType = null): void
{ {
$this $this
->activateObject() ->activateObject()
->setGlowSize($size) ->setGlowSize($size)
->setGlowColor($color_value, $color_alpha, $color_type); ->setGlowColor($colorValue, $colorAlpha, $colorType);
} }
/** /**
* Get Glow Color Property. * Get Glow Color Property.
* *
* @param string $property * @param string $propertyName
* *
* @return string * @return string
*/ */
public function getGlowColor($property) public function getGlowColor($propertyName)
{ {
return $this->glowProperties['color'][$property]; return $this->glowProperties['color'][$propertyName];
} }
/** /**
@ -243,11 +243,11 @@ class GridLines extends Properties
* *
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $colorType
* *
* @return $this * @return $this
*/ */
private function setGlowColor($color, $alpha, $type) private function setGlowColor($color, $alpha, $colorType)
{ {
if ($color !== null) { if ($color !== null) {
$this->glowProperties['color']['value'] = (string) $color; $this->glowProperties['color']['value'] = (string) $color;
@ -255,8 +255,8 @@ class GridLines extends Properties
if ($alpha !== null) { if ($alpha !== null) {
$this->glowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); $this->glowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha);
} }
if ($type !== null) { if ($colorType !== null) {
$this->glowProperties['color']['type'] = (string) $type; $this->glowProperties['color']['type'] = (string) $colorType;
} }
return $this; return $this;
@ -265,52 +265,52 @@ class GridLines extends Properties
/** /**
* Get Line Style Arrow Parameters. * Get Line Style Arrow Parameters.
* *
* @param string $arrow_selector * @param string $arrowSelector
* @param string $property_selector * @param string $propertySelector
* *
* @return string * @return string
*/ */
public function getLineStyleArrowParameters($arrow_selector, $property_selector) public function getLineStyleArrowParameters($arrowSelector, $propertySelector)
{ {
return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrow_selector]['size'], $property_selector); return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrowSelector]['size'], $propertySelector);
} }
/** /**
* Set Shadow Properties. * Set Shadow Properties.
* *
* @param int $sh_presets * @param int $presets
* @param string $sh_color_value * @param string $colorValue
* @param string $sh_color_type * @param string $colorType
* @param int $sh_color_alpha * @param string $colorAlpha
* @param string $sh_blur * @param string $blur
* @param int $sh_angle * @param int $angle
* @param float $sh_distance * @param float $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): void public function setShadowProperties($presets, $colorValue = null, $colorType = null, $colorAlpha = null, $blur = null, $angle = null, $distance = null): void
{ {
$this->activateObject() $this->activateObject()
->setShadowPresetsProperties((int) $sh_presets) ->setShadowPresetsProperties((int) $presets)
->setShadowColor( ->setShadowColor(
$sh_color_value ?? $this->shadowProperties['color']['value'], $colorValue ?? $this->shadowProperties['color']['value'],
$sh_color_alpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($sh_color_alpha), $colorAlpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($colorAlpha),
$sh_color_type ?? $this->shadowProperties['color']['type'] $colorType ?? $this->shadowProperties['color']['type']
) )
->setShadowBlur($sh_blur) ->setShadowBlur((float) $blur)
->setShadowAngle($sh_angle) ->setShadowAngle($angle)
->setShadowDistance($sh_distance); ->setShadowDistance($distance);
} }
/** /**
* Set Shadow Presets Properties. * Set Shadow Presets Properties.
* *
* @param int $shadow_presets * @param int $presets
* *
* @return $this * @return $this
*/ */
private function setShadowPresetsProperties($shadow_presets) private function setShadowPresetsProperties($presets)
{ {
$this->shadowProperties['presets'] = $shadow_presets; $this->shadowProperties['presets'] = $presets;
$this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets));
return $this; return $this;
} }
@ -322,17 +322,17 @@ class GridLines extends Properties
* *
* @return $this * @return $this
*/ */
private function setShadowProperiesMapValues(array $properties_map, &$reference = null) private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null)
{ {
$base_reference = $reference; $base_reference = $reference;
foreach ($properties_map as $property_key => $property_val) { foreach ($propertiesMap as $property_key => $property_val) {
if (is_array($property_val)) { if (is_array($property_val)) {
if ($reference === null) { if ($reference === null) {
$reference = &$this->shadowProperties[$property_key]; $reference = &$this->shadowProperties[$property_key];
} else { } else {
$reference = &$reference[$property_key]; $reference = &$reference[$property_key];
} }
$this->setShadowProperiesMapValues($property_val, $reference); $this->setShadowPropertiesMapValues($property_val, $reference);
} else { } else {
if ($base_reference === null) { if ($base_reference === null) {
$this->shadowProperties[$property_key] = $property_val; $this->shadowProperties[$property_key] = $property_val;
@ -350,11 +350,11 @@ class GridLines extends Properties
* *
* @param string $color * @param string $color
* @param int $alpha * @param int $alpha
* @param string $type * @param string $colorType
* *
* @return $this * @return $this
*/ */
private function setShadowColor($color, $alpha, $type) private function setShadowColor($color, $alpha, $colorType)
{ {
if ($color !== null) { if ($color !== null) {
$this->shadowProperties['color']['value'] = (string) $color; $this->shadowProperties['color']['value'] = (string) $color;
@ -362,8 +362,8 @@ class GridLines extends Properties
if ($alpha !== null) { if ($alpha !== null) {
$this->shadowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); $this->shadowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha);
} }
if ($type !== null) { if ($colorType !== null) {
$this->shadowProperties['color']['type'] = (string) $type; $this->shadowProperties['color']['type'] = (string) $colorType;
} }
return $this; return $this;

View File

@ -149,13 +149,13 @@ class Layout
/** /**
* Set Layout Target. * Set Layout Target.
* *
* @param string $value * @param string $target
* *
* @return $this * @return $this
*/ */
public function setLayoutTarget($value) public function setLayoutTarget($target)
{ {
$this->layoutTarget = $value; $this->layoutTarget = $target;
return $this; return $this;
} }
@ -173,13 +173,13 @@ class Layout
/** /**
* Set X-Mode. * Set X-Mode.
* *
* @param string $value * @param string $mode
* *
* @return $this * @return $this
*/ */
public function setXMode($value) public function setXMode($mode)
{ {
$this->xMode = (string) $value; $this->xMode = (string) $mode;
return $this; return $this;
} }
@ -197,13 +197,13 @@ class Layout
/** /**
* Set Y-Mode. * Set Y-Mode.
* *
* @param string $value * @param string $mode
* *
* @return $this * @return $this
*/ */
public function setYMode($value) public function setYMode($mode)
{ {
$this->yMode = (string) $value; $this->yMode = (string) $mode;
return $this; return $this;
} }
@ -221,13 +221,13 @@ class Layout
/** /**
* Set X-Position. * Set X-Position.
* *
* @param float $value * @param float $position
* *
* @return $this * @return $this
*/ */
public function setXPosition($value) public function setXPosition($position)
{ {
$this->xPos = (float) $value; $this->xPos = (float) $position;
return $this; return $this;
} }
@ -245,13 +245,13 @@ class Layout
/** /**
* Set Y-Position. * Set Y-Position.
* *
* @param float $value * @param float $position
* *
* @return $this * @return $this
*/ */
public function setYPosition($value) public function setYPosition($position)
{ {
$this->yPos = (float) $value; $this->yPos = (float) $position;
return $this; return $this;
} }
@ -269,13 +269,13 @@ class Layout
/** /**
* Set Width. * Set Width.
* *
* @param float $value * @param float $width
* *
* @return $this * @return $this
*/ */
public function setWidth($value) public function setWidth($width)
{ {
$this->width = $value; $this->width = $width;
return $this; return $this;
} }
@ -293,13 +293,13 @@ class Layout
/** /**
* Set Height. * Set Height.
* *
* @param float $value * @param float $height
* *
* @return $this * @return $this
*/ */
public function setHeight($value) public function setHeight($height)
{ {
$this->height = $value; $this->height = $height;
return $this; return $this;
} }
@ -318,13 +318,13 @@ class Layout
* Set show legend key * Set show legend key
* Specifies that legend keys should be shown in data labels. * Specifies that legend keys should be shown in data labels.
* *
* @param bool $value Show legend key * @param bool $showLegendKey Show legend key
* *
* @return $this * @return $this
*/ */
public function setShowLegendKey($value) public function setShowLegendKey($showLegendKey)
{ {
$this->showLegendKey = $value; $this->showLegendKey = $showLegendKey;
return $this; return $this;
} }
@ -343,13 +343,13 @@ class Layout
* Set show val * Set show val
* Specifies that the value should be shown in data labels. * Specifies that the value should be shown in data labels.
* *
* @param bool $value Show val * @param bool $showDataLabelValues Show val
* *
* @return $this * @return $this
*/ */
public function setShowVal($value) public function setShowVal($showDataLabelValues)
{ {
$this->showVal = $value; $this->showVal = $showDataLabelValues;
return $this; return $this;
} }
@ -368,13 +368,13 @@ class Layout
* Set show cat name * Set show cat name
* Specifies that the category name should be shown in data labels. * Specifies that the category name should be shown in data labels.
* *
* @param bool $value Show cat name * @param bool $showCategoryName Show cat name
* *
* @return $this * @return $this
*/ */
public function setShowCatName($value) public function setShowCatName($showCategoryName)
{ {
$this->showCatName = $value; $this->showCatName = $showCategoryName;
return $this; return $this;
} }
@ -393,13 +393,13 @@ class Layout
* Set show ser name * Set show ser name
* Specifies that the series name should be shown in data labels. * Specifies that the series name should be shown in data labels.
* *
* @param bool $value Show series name * @param bool $showSeriesName Show series name
* *
* @return $this * @return $this
*/ */
public function setShowSerName($value) public function setShowSerName($showSeriesName)
{ {
$this->showSerName = $value; $this->showSerName = $showSeriesName;
return $this; return $this;
} }
@ -418,13 +418,13 @@ class Layout
* Set show percentage * Set show percentage
* Specifies that the percentage should be shown in data labels. * Specifies that the percentage should be shown in data labels.
* *
* @param bool $value Show percentage * @param bool $showPercentage Show percentage
* *
* @return $this * @return $this
*/ */
public function setShowPercent($value) public function setShowPercent($showPercentage)
{ {
$this->showPercent = $value; $this->showPercent = $showPercentage;
return $this; return $this;
} }
@ -443,13 +443,13 @@ class Layout
* Set show bubble size * Set show bubble size
* Specifies that the bubble size should be shown in data labels. * Specifies that the bubble size should be shown in data labels.
* *
* @param bool $value Show bubble size * @param bool $showBubbleSize Show bubble size
* *
* @return $this * @return $this
*/ */
public function setShowBubbleSize($value) public function setShowBubbleSize($showBubbleSize)
{ {
$this->showBubbleSize = $value; $this->showBubbleSize = $showBubbleSize;
return $this; return $this;
} }
@ -468,13 +468,13 @@ class Layout
* Set show leader lines * Set show leader lines
* Specifies that leader lines should be shown in data labels. * Specifies that leader lines should be shown in data labels.
* *
* @param bool $value Show leader lines * @param bool $showLeaderLines Show leader lines
* *
* @return $this * @return $this
*/ */
public function setShowLeaderLines($value) public function setShowLeaderLines($showLeaderLines)
{ {
$this->showLeaderLines = $value; $this->showLeaderLines = $showLeaderLines;
return $this; return $this;
} }

View File

@ -135,16 +135,16 @@ abstract class Properties
return (string) 100 - $alpha . '000'; return (string) 100 - $alpha . '000';
} }
protected function setColorProperties($color, $alpha, $type) protected function setColorProperties($color, $alpha, $colorType)
{ {
return [ return [
'type' => (string) $type, 'type' => (string) $colorType,
'value' => (string) $color, 'value' => (string) $color,
'alpha' => (string) $this->getTrueAlpha($alpha), 'alpha' => (string) $this->getTrueAlpha($alpha),
]; ];
} }
protected function getLineStyleArrowSize($array_selector, $array_kay_selector) protected function getLineStyleArrowSize($arraySelector, $arrayKaySelector)
{ {
$sizes = [ $sizes = [
1 => ['w' => 'sm', 'len' => 'sm'], 1 => ['w' => 'sm', 'len' => 'sm'],
@ -158,10 +158,10 @@ abstract class Properties
9 => ['w' => 'lg', 'len' => 'lg'], 9 => ['w' => 'lg', 'len' => 'lg'],
]; ];
return $sizes[$array_selector][$array_kay_selector]; return $sizes[$arraySelector][$arrayKaySelector];
} }
protected function getShadowPresetsMap($shadow_presets_option) protected function getShadowPresetsMap($presetsOption)
{ {
$presets_options = [ $presets_options = [
//OUTER //OUTER
@ -350,7 +350,7 @@ abstract class Properties
], ],
]; ];
return $presets_options[$shadow_presets_option]; return $presets_options[$presetsOption];
} }
protected function getArrayElementsValue($properties, $elements) protected function getArrayElementsValue($properties, $elements)

View File

@ -86,18 +86,18 @@ class Cells
/** /**
* Whether the collection holds a cell for the given coordinate. * Whether the collection holds a cell for the given coordinate.
* *
* @param string $pCoord Coordinate of the cell to check * @param string $cellCoordinate Coordinate of the cell to check
* *
* @return bool * @return bool
*/ */
public function has($pCoord) public function has($cellCoordinate)
{ {
if ($pCoord === $this->currentCoordinate) { if ($cellCoordinate === $this->currentCoordinate) {
return true; return true;
} }
// Check if the requested entry exists in the index // Check if the requested entry exists in the index
return isset($this->index[$pCoord]); return isset($this->index[$cellCoordinate]);
} }
/** /**
@ -115,21 +115,21 @@ class Cells
/** /**
* Delete a cell in cache identified by coordinate. * Delete a cell in cache identified by coordinate.
* *
* @param string $pCoord Coordinate of the cell to delete * @param string $cellCoordinate Coordinate of the cell to delete
*/ */
public function delete($pCoord): void public function delete($cellCoordinate): void
{ {
if ($pCoord === $this->currentCoordinate && $this->currentCell !== null) { if ($cellCoordinate === $this->currentCoordinate && $this->currentCell !== null) {
$this->currentCell->detach(); $this->currentCell->detach();
$this->currentCoordinate = null; $this->currentCoordinate = null;
$this->currentCell = null; $this->currentCell = null;
$this->currentCellIsDirty = false; $this->currentCellIsDirty = false;
} }
unset($this->index[$pCoord]); unset($this->index[$cellCoordinate]);
// Delete the entry from cache // Delete the entry from cache
$this->cache->delete($this->cachePrefix . $pCoord); $this->cache->delete($this->cachePrefix . $cellCoordinate);
} }
/** /**
@ -304,16 +304,16 @@ class Cells
/** /**
* Clone the cell collection. * Clone the cell collection.
* *
* @param Worksheet $parent The new worksheet that we're copying to * @param Worksheet $worksheet The new worksheet that we're copying to
* *
* @return self * @return self
*/ */
public function cloneCellCollection(Worksheet $parent) public function cloneCellCollection(Worksheet $worksheet)
{ {
$this->storeCurrentCell(); $this->storeCurrentCell();
$newCollection = clone $this; $newCollection = clone $this;
$newCollection->parent = $parent; $newCollection->parent = $worksheet;
if (($newCollection->currentCell !== null) && (is_object($newCollection->currentCell))) { if (($newCollection->currentCell !== null) && (is_object($newCollection->currentCell))) {
$newCollection->currentCell->attach($this); $newCollection->currentCell->attach($this);
} }
@ -402,19 +402,19 @@ class Cells
/** /**
* Add or update a cell identified by its coordinate into the collection. * Add or update a cell identified by its coordinate into the collection.
* *
* @param string $pCoord Coordinate of the cell to update * @param string $cellCoordinate Coordinate of the cell to update
* @param Cell $cell Cell to update * @param Cell $cell Cell to update
* *
* @return Cell * @return Cell
*/ */
public function add($pCoord, Cell $cell) public function add($cellCoordinate, Cell $cell)
{ {
if ($pCoord !== $this->currentCoordinate) { if ($cellCoordinate !== $this->currentCoordinate) {
$this->storeCurrentCell(); $this->storeCurrentCell();
} }
$this->index[$pCoord] = true; $this->index[$cellCoordinate] = true;
$this->currentCoordinate = $pCoord; $this->currentCoordinate = $cellCoordinate;
$this->currentCell = $cell; $this->currentCell = $cell;
$this->currentCellIsDirty = true; $this->currentCellIsDirty = true;
@ -424,30 +424,30 @@ class Cells
/** /**
* Get cell at a specific coordinate. * Get cell at a specific coordinate.
* *
* @param string $pCoord Coordinate of the cell * @param string $cellCoordinate Coordinate of the cell
* *
* @return null|Cell Cell that was found, or null if not found * @return null|Cell Cell that was found, or null if not found
*/ */
public function get($pCoord) public function get($cellCoordinate)
{ {
if ($pCoord === $this->currentCoordinate) { if ($cellCoordinate === $this->currentCoordinate) {
return $this->currentCell; return $this->currentCell;
} }
$this->storeCurrentCell(); $this->storeCurrentCell();
// Return null if requested entry doesn't exist in collection // Return null if requested entry doesn't exist in collection
if (!$this->has($pCoord)) { if (!$this->has($cellCoordinate)) {
return null; return null;
} }
// Check if the entry that has been requested actually exists // Check if the entry that has been requested actually exists
$cell = $this->cache->get($this->cachePrefix . $pCoord); $cell = $this->cache->get($this->cachePrefix . $cellCoordinate);
if ($cell === null) { if ($cell === null) {
throw new PhpSpreadsheetException("Cell entry {$pCoord} no longer exists in cache. This probably means that the cache was cleared by someone else."); throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else.");
} }
// Set current entry to the requested entry // Set current entry to the requested entry
$this->currentCoordinate = $pCoord; $this->currentCoordinate = $cellCoordinate;
$this->currentCell = $cell; $this->currentCell = $cell;
// Re-attach this as the cell's parent // Re-attach this as the cell's parent
$this->currentCell->attach($this); $this->currentCell->attach($this);

View File

@ -10,12 +10,12 @@ abstract class CellsFactory
/** /**
* Initialise the cache storage. * Initialise the cache storage.
* *
* @param Worksheet $parent Enable cell caching for this worksheet * @param Worksheet $worksheet Enable cell caching for this worksheet
* *
* @return Cells * @return Cells
* */ * */
public static function getInstance(Worksheet $parent) public static function getInstance(Worksheet $worksheet)
{ {
return new Cells($parent, Settings::getCache()); return new Cells($worksheet, Settings::getCache());
} }
} }

View File

@ -2,7 +2,10 @@
namespace PhpOffice\PhpSpreadsheet; namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Helper\Size;
use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
class Comment implements IComparable class Comment implements IComparable
{ {
@ -58,7 +61,7 @@ class Comment implements IComparable
/** /**
* Comment fill color. * Comment fill color.
* *
* @var Style\Color * @var Color
*/ */
private $fillColor; private $fillColor;
@ -77,28 +80,22 @@ class Comment implements IComparable
// Initialise variables // Initialise variables
$this->author = 'Author'; $this->author = 'Author';
$this->text = new RichText(); $this->text = new RichText();
$this->fillColor = new Style\Color('FFFFFFE1'); $this->fillColor = new Color('FFFFFFE1');
$this->alignment = Style\Alignment::HORIZONTAL_GENERAL; $this->alignment = Alignment::HORIZONTAL_GENERAL;
} }
/** /**
* Get Author. * Get Author.
*
* @return string
*/ */
public function getAuthor() public function getAuthor(): string
{ {
return $this->author; return $this->author;
} }
/** /**
* Set Author. * Set Author.
*
* @param string $author
*
* @return $this
*/ */
public function setAuthor($author) public function setAuthor(string $author): self
{ {
$this->author = $author; $this->author = $author;
@ -107,164 +104,146 @@ class Comment implements IComparable
/** /**
* Get Rich text comment. * Get Rich text comment.
*
* @return RichText
*/ */
public function getText() public function getText(): RichText
{ {
return $this->text; return $this->text;
} }
/** /**
* Set Rich text comment. * Set Rich text comment.
*
* @return $this
*/ */
public function setText(RichText $pValue) public function setText(RichText $text): self
{ {
$this->text = $pValue; $this->text = $text;
return $this; return $this;
} }
/** /**
* Get comment width (CSS style, i.e. XXpx or YYpt). * Get comment width (CSS style, i.e. XXpx or YYpt).
*
* @return string
*/ */
public function getWidth() public function getWidth(): string
{ {
return $this->width; return $this->width;
} }
/** /**
* Set comment width (CSS style, i.e. XXpx or YYpt). * Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*
* @param string $width
*
* @return $this
*/ */
public function setWidth($width) public function setWidth(string $width): self
{ {
$this->width = $width; $width = new Size($width);
if ($width->valid()) {
$this->width = (string) $width;
}
return $this; return $this;
} }
/** /**
* Get comment height (CSS style, i.e. XXpx or YYpt). * Get comment height (CSS style, i.e. XXpx or YYpt).
*
* @return string
*/ */
public function getHeight() public function getHeight(): string
{ {
return $this->height; return $this->height;
} }
/** /**
* Set comment height (CSS style, i.e. XXpx or YYpt). * Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*
* @param string $value
*
* @return $this
*/ */
public function setHeight($value) public function setHeight(string $height): self
{ {
$this->height = $value; $height = new Size($height);
if ($height->valid()) {
$this->height = (string) $height;
}
return $this; return $this;
} }
/** /**
* Get left margin (CSS style, i.e. XXpx or YYpt). * Get left margin (CSS style, i.e. XXpx or YYpt).
*
* @return string
*/ */
public function getMarginLeft() public function getMarginLeft(): string
{ {
return $this->marginLeft; return $this->marginLeft;
} }
/** /**
* Set left margin (CSS style, i.e. XXpx or YYpt). * Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*
* @param string $value
*
* @return $this
*/ */
public function setMarginLeft($value) public function setMarginLeft(string $margin): self
{ {
$this->marginLeft = $value; $margin = new Size($margin);
if ($margin->valid()) {
$this->marginLeft = (string) $margin;
}
return $this; return $this;
} }
/** /**
* Get top margin (CSS style, i.e. XXpx or YYpt). * Get top margin (CSS style, i.e. XXpx or YYpt).
*
* @return string
*/ */
public function getMarginTop() public function getMarginTop(): string
{ {
return $this->marginTop; return $this->marginTop;
} }
/** /**
* Set top margin (CSS style, i.e. XXpx or YYpt). * Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*
* @param string $value
*
* @return $this
*/ */
public function setMarginTop($value) public function setMarginTop(string $margin): self
{ {
$this->marginTop = $value; $margin = new Size($margin);
if ($margin->valid()) {
$this->marginTop = (string) $margin;
}
return $this; return $this;
} }
/** /**
* Is the comment visible by default? * Is the comment visible by default?
*
* @return bool
*/ */
public function getVisible() public function getVisible(): bool
{ {
return $this->visible; return $this->visible;
} }
/** /**
* Set comment default visibility. * Set comment default visibility.
*
* @param bool $value
*
* @return $this
*/ */
public function setVisible($value) public function setVisible(bool $visibility): self
{ {
$this->visible = $value; $this->visible = $visibility;
return $this;
}
/**
* Set fill color.
*/
public function setFillColor(Color $color): self
{
$this->fillColor = $color;
return $this; return $this;
} }
/** /**
* Get fill color. * Get fill color.
*
* @return Style\Color
*/ */
public function getFillColor() public function getFillColor(): Color
{ {
return $this->fillColor; return $this->fillColor;
} }
/** /**
* Set Alignment. * Set Alignment.
*
* @param string $alignment see Style\Alignment::HORIZONTAL_*
*
* @return $this
*/ */
public function setAlignment($alignment) public function setAlignment(string $alignment): self
{ {
$this->alignment = $alignment; $this->alignment = $alignment;
@ -273,20 +252,16 @@ class Comment implements IComparable
/** /**
* Get Alignment. * Get Alignment.
*
* @return string
*/ */
public function getAlignment() public function getAlignment(): string
{ {
return $this->alignment; return $this->alignment;
} }
/** /**
* Get hash code. * Get hash code.
*
* @return string Hash code
*/ */
public function getHashCode() public function getHashCode(): string
{ {
return md5( return md5(
$this->author . $this->author .
@ -319,10 +294,8 @@ class Comment implements IComparable
/** /**
* Convert to string. * Convert to string.
*
* @return string
*/ */
public function __toString() public function __toString(): string
{ {
return $this->text->getPlainText(); return $this->text->getPlainText();
} }

View File

@ -167,9 +167,9 @@ abstract class DefinedName
/** /**
* Set worksheet. * Set worksheet.
*/ */
public function setWorksheet(?Worksheet $value): self public function setWorksheet(?Worksheet $worksheet): self
{ {
$this->worksheet = $value; $this->worksheet = $worksheet;
return $this; return $this;
} }
@ -203,10 +203,10 @@ abstract class DefinedName
/** /**
* Set localOnly. * Set localOnly.
*/ */
public function setLocalOnly(bool $value): self public function setLocalOnly(bool $localScope): self
{ {
$this->localOnly = $value; $this->localOnly = $localScope;
$this->scope = $value ? $this->worksheet : null; $this->scope = $localScope ? $this->worksheet : null;
return $this; return $this;
} }
@ -222,10 +222,10 @@ abstract class DefinedName
/** /**
* Set scope. * Set scope.
*/ */
public function setScope(?Worksheet $value): self public function setScope(?Worksheet $worksheet): self
{ {
$this->scope = $value; $this->scope = $worksheet;
$this->localOnly = $value !== null; $this->localOnly = $worksheet !== null;
return $this; return $this;
} }
@ -241,18 +241,18 @@ abstract class DefinedName
/** /**
* Resolve a named range to a regular cell range or formula. * Resolve a named range to a regular cell range or formula.
*/ */
public static function resolveName(string $pDefinedName, Worksheet $pSheet, string $sheetName = ''): ?self public static function resolveName(string $definedName, Worksheet $worksheet, string $sheetName = ''): ?self
{ {
if ($sheetName === '') { if ($sheetName === '') {
$pSheet2 = $pSheet; $worksheet2 = $worksheet;
} else { } else {
$pSheet2 = $pSheet->getParent()->getSheetByName($sheetName); $worksheet2 = $worksheet->getParent()->getSheetByName($sheetName);
if ($pSheet2 === null) { if ($worksheet2 === null) {
return null; return null;
} }
} }
return $pSheet->getParent()->getDefinedName($pDefinedName, $pSheet2); return $worksheet->getParent()->getDefinedName($definedName, $worksheet2);
} }
/** /**

View File

@ -151,9 +151,9 @@ class Properties
* *
* @return $this * @return $this
*/ */
public function setLastModifiedBy(string $modifier): self public function setLastModifiedBy(string $modifiedBy): self
{ {
$this->lastModifiedBy = $modifier; $this->lastModifiedBy = $modifiedBy;
return $this; return $this;
} }

View File

@ -63,10 +63,10 @@ class Security
return $this->lockRevision; return $this->lockRevision;
} }
public function setLockRevision(?bool $pValue): self public function setLockRevision(?bool $locked): self
{ {
if ($pValue !== null) { if ($locked !== null) {
$this->lockRevision = $pValue; $this->lockRevision = $locked;
} }
return $this; return $this;
@ -77,10 +77,10 @@ class Security
return $this->lockStructure; return $this->lockStructure;
} }
public function setLockStructure(?bool $pValue): self public function setLockStructure(?bool $locked): self
{ {
if ($pValue !== null) { if ($locked !== null) {
$this->lockStructure = $pValue; $this->lockStructure = $locked;
} }
return $this; return $this;
@ -91,10 +91,10 @@ class Security
return $this->lockWindows; return $this->lockWindows;
} }
public function setLockWindows(?bool $pValue): self public function setLockWindows(?bool $locked): self
{ {
if ($pValue !== null) { if ($locked !== null) {
$this->lockWindows = $pValue; $this->lockWindows = $locked;
} }
return $this; return $this;
@ -105,13 +105,21 @@ class Security
return $this->revisionsPassword; return $this->revisionsPassword;
} }
public function setRevisionsPassword(?string $pValue, bool $pAlreadyHashed = false): self /**
* Set RevisionsPassword.
*
* @param string $password
* @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
public function setRevisionsPassword(?string $password, bool $alreadyHashed = false)
{ {
if ($pValue !== null) { if ($password !== null) {
if (!$pAlreadyHashed) { if (!$alreadyHashed) {
$pValue = PasswordHasher::hashPassword($pValue); $password = PasswordHasher::hashPassword($password);
} }
$this->revisionsPassword = $pValue; $this->revisionsPassword = $password;
} }
return $this; return $this;
@ -122,13 +130,21 @@ class Security
return $this->workbookPassword; return $this->workbookPassword;
} }
public function setWorkbookPassword(?string $pValue, bool $pAlreadyHashed = false): self /**
* Set WorkbookPassword.
*
* @param string $password
* @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
public function setWorkbookPassword(?string $password, bool $alreadyHashed = false)
{ {
if ($pValue !== null) { if ($password !== null) {
if (!$pAlreadyHashed) { if (!$alreadyHashed) {
$pValue = PasswordHasher::hashPassword($pValue); $password = PasswordHasher::hashPassword($password);
} }
$this->workbookPassword = $pValue; $this->workbookPassword = $password;
} }
return $this; return $this;

View File

@ -10,43 +10,43 @@ class HashTable
/** /**
* HashTable elements. * HashTable elements.
* *
* @var T[] * @var array<string, T>
*/ */
protected $items = []; protected $items = [];
/** /**
* HashTable key map. * HashTable key map.
* *
* @var string[] * @var array<int, string>
*/ */
protected $keyMap = []; protected $keyMap = [];
/** /**
* Create a new \PhpOffice\PhpSpreadsheet\HashTable. * Create a new HashTable.
* *
* @param T[] $pSource Optional source array to create HashTable from * @param T[] $source Optional source array to create HashTable from
*/ */
public function __construct($pSource = null) public function __construct($source = null)
{ {
if ($pSource !== null) { if ($source !== null) {
// Create HashTable // Create HashTable
$this->addFromSource($pSource); $this->addFromSource($source);
} }
} }
/** /**
* Add HashTable items from source. * Add HashTable items from source.
* *
* @param T[] $pSource Source array to create HashTable from * @param T[] $source Source array to create HashTable from
*/ */
public function addFromSource(?array $pSource = null): void public function addFromSource(?array $source = null): void
{ {
// Check if an array was passed // Check if an array was passed
if ($pSource == null) { if ($source === null) {
return; return;
} }
foreach ($pSource as $item) { foreach ($source as $item) {
$this->add($item); $this->add($item);
} }
} }
@ -54,13 +54,13 @@ class HashTable
/** /**
* Add HashTable item. * Add HashTable item.
* *
* @param T $pSource Item to add * @param T $source Item to add
*/ */
public function add(IComparable $pSource): void public function add(IComparable $source): void
{ {
$hash = $pSource->getHashCode(); $hash = $source->getHashCode();
if (!isset($this->items[$hash])) { if (!isset($this->items[$hash])) {
$this->items[$hash] = $pSource; $this->items[$hash] = $source;
$this->keyMap[count($this->items) - 1] = $hash; $this->keyMap[count($this->items) - 1] = $hash;
} }
} }
@ -68,11 +68,11 @@ class HashTable
/** /**
* Remove HashTable item. * Remove HashTable item.
* *
* @param T $pSource Item to remove * @param T $source Item to remove
*/ */
public function remove(IComparable $pSource): void public function remove(IComparable $source): void
{ {
$hash = $pSource->getHashCode(); $hash = $source->getHashCode();
if (isset($this->items[$hash])) { if (isset($this->items[$hash])) {
unset($this->items[$hash]); unset($this->items[$hash]);
@ -112,26 +112,22 @@ class HashTable
/** /**
* Get index for hash code. * Get index for hash code.
* *
* @param string $pHashCode * @return false|int Index
*
* @return int Index
*/ */
public function getIndexForHashCode($pHashCode) public function getIndexForHashCode(string $hashCode)
{ {
return array_search($pHashCode, $this->keyMap); return array_search($hashCode, $this->keyMap, true);
} }
/** /**
* Get by index. * Get by index.
* *
* @param int $pIndex
*
* @return null|T * @return null|T
*/ */
public function getByIndex($pIndex) public function getByIndex(int $index)
{ {
if (isset($this->keyMap[$pIndex])) { if (isset($this->keyMap[$index])) {
return $this->getByHashCode($this->keyMap[$pIndex]); return $this->getByHashCode($this->keyMap[$index]);
} }
return null; return null;
@ -140,14 +136,12 @@ class HashTable
/** /**
* Get by hashcode. * Get by hashcode.
* *
* @param string $pHashCode
*
* @return null|T * @return null|T
*/ */
public function getByHashCode($pHashCode) public function getByHashCode(string $hashCode)
{ {
if (isset($this->items[$pHashCode])) { if (isset($this->items[$hashCode])) {
return $this->items[$pHashCode]; return $this->items[$hashCode];
} }
return null; return null;

View File

@ -684,9 +684,9 @@ class Html
$this->stringData = ''; $this->stringData = '';
} }
protected function rgbToColour($rgb) protected function rgbToColour(string $rgbValue): string
{ {
preg_match_all('/\d+/', $rgb, $values); preg_match_all('/\d+/', $rgbValue, $values);
foreach ($values[0] as &$value) { foreach ($values[0] as &$value) {
$value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
} }
@ -694,9 +694,9 @@ class Html
return implode('', $values[0]); return implode('', $values[0]);
} }
public static function colourNameLookup(string $rgb): string public static function colourNameLookup(string $colorName): string
{ {
return self::$colourMap[$rgb] ?? ''; return self::$colourMap[$colorName] ?? '';
} }
protected function startFontTag($tag): void protected function startFontTag($tag): void

View File

@ -0,0 +1,52 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Helper;
class Size
{
const REGEXP_SIZE_VALIDATION = '/^(?P<size>\d*\.?\d+)(?P<unit>pt|px|em)?$/i';
/**
* @var bool
*/
protected $valid;
/**
* @var string
*/
protected $size = '';
/**
* @var string
*/
protected $unit = '';
public function __construct(string $size)
{
$this->valid = (bool) preg_match(self::REGEXP_SIZE_VALIDATION, $size, $matches);
if ($this->valid) {
$this->size = $matches['size'];
$this->unit = $matches['unit'] ?? 'pt';
}
}
public function valid(): bool
{
return $this->valid;
}
public function size(): string
{
return $this->size;
}
public function unit(): string
{
return $this->unit;
}
public function __toString()
{
return $this->size . $this->unit;
}
}

View File

@ -2,7 +2,9 @@
namespace PhpOffice\PhpSpreadsheet; namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
/** /**
* Factory to create readers and writers easily. * Factory to create readers and writers easily.
@ -36,12 +38,8 @@ abstract class IOFactory
/** /**
* Create Writer\IWriter. * Create Writer\IWriter.
*
* @param string $writerType Example: Xlsx
*
* @return Writer\IWriter
*/ */
public static function createWriter(Spreadsheet $spreadsheet, $writerType) public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter
{ {
if (!isset(self::$writers[$writerType])) { if (!isset(self::$writers[$writerType])) {
throw new Writer\Exception("No writer found for type $writerType"); throw new Writer\Exception("No writer found for type $writerType");
@ -54,13 +52,9 @@ abstract class IOFactory
} }
/** /**
* Create Reader\IReader. * Create IReader.
*
* @param string $readerType Example: Xlsx
*
* @return Reader\IReader
*/ */
public static function createReader($readerType) public static function createReader(string $readerType): IReader
{ {
if (!isset(self::$readers[$readerType])) { if (!isset(self::$readers[$readerType])) {
throw new Reader\Exception("No reader found for type $readerType"); throw new Reader\Exception("No reader found for type $readerType");
@ -76,10 +70,8 @@ abstract class IOFactory
* Loads Spreadsheet from file using automatic Reader\IReader resolution. * Loads Spreadsheet from file using automatic Reader\IReader resolution.
* *
* @param string $filename The name of the spreadsheet file * @param string $filename The name of the spreadsheet file
*
* @return Spreadsheet
*/ */
public static function load(string $filename, int $flags = 0) public static function load(string $filename, int $flags = 0): Spreadsheet
{ {
$reader = self::createReaderForFile($filename); $reader = self::createReaderForFile($filename);
@ -87,15 +79,11 @@ abstract class IOFactory
} }
/** /**
* Identify file type using automatic Reader\IReader resolution. * Identify file type using automatic IReader resolution.
*
* @param string $pFilename The name of the spreadsheet file to identify
*
* @return string
*/ */
public static function identify($pFilename) public static function identify(string $filename): string
{ {
$reader = self::createReaderForFile($pFilename); $reader = self::createReaderForFile($filename);
$className = get_class($reader); $className = get_class($reader);
$classType = explode('\\', $className); $classType = explode('\\', $className);
unset($reader); unset($reader);
@ -104,13 +92,9 @@ abstract class IOFactory
} }
/** /**
* Create Reader\IReader for file using automatic Reader\IReader resolution. * Create Reader\IReader for file using automatic IReader resolution.
*
* @param string $filename The name of the spreadsheet file
*
* @return Reader\IReader
*/ */
public static function createReaderForFile($filename) public static function createReaderForFile(string $filename): IReader
{ {
File::assertFile($filename); File::assertFile($filename);
@ -142,12 +126,8 @@ abstract class IOFactory
/** /**
* Guess a reader type from the file extension, if any. * Guess a reader type from the file extension, if any.
*
* @param string $filename
*
* @return null|string
*/ */
private static function getReaderTypeFromExtension($filename) private static function getReaderTypeFromExtension(string $filename): ?string
{ {
$pathinfo = pathinfo($filename); $pathinfo = pathinfo($filename);
if (!isset($pathinfo['extension'])) { if (!isset($pathinfo['extension'])) {
@ -187,14 +167,11 @@ abstract class IOFactory
/** /**
* Register a writer with its type and class name. * Register a writer with its type and class name.
*
* @param string $writerType
* @param string $writerClass
*/ */
public static function registerWriter($writerType, $writerClass): void public static function registerWriter(string $writerType, string $writerClass): void
{ {
if (!is_a($writerClass, Writer\IWriter::class, true)) { if (!is_a($writerClass, IWriter::class, true)) {
throw new Writer\Exception('Registered writers must implement ' . Writer\IWriter::class); throw new Writer\Exception('Registered writers must implement ' . IWriter::class);
} }
self::$writers[$writerType] = $writerClass; self::$writers[$writerType] = $writerClass;
@ -202,14 +179,11 @@ abstract class IOFactory
/** /**
* Register a reader with its type and class name. * Register a reader with its type and class name.
*
* @param string $readerType
* @param string $readerClass
*/ */
public static function registerReader($readerType, $readerClass): void public static function registerReader(string $readerType, string $readerClass): void
{ {
if (!is_a($readerClass, Reader\IReader::class, true)) { if (!is_a($readerClass, IReader::class, true)) {
throw new Reader\Exception('Registered readers must implement ' . Reader\IReader::class); throw new Reader\Exception('Registered readers must implement ' . IReader::class);
} }
self::$readers[$readerType] = $readerClass; self::$readers[$readerType] = $readerClass;

View File

@ -66,9 +66,9 @@ abstract class BaseReader implements IReader
return $this->readDataOnly; return $this->readDataOnly;
} }
public function setReadDataOnly($pValue) public function setReadDataOnly($readCellValuesOnly)
{ {
$this->readDataOnly = (bool) $pValue; $this->readDataOnly = (bool) $readCellValuesOnly;
return $this; return $this;
} }
@ -78,9 +78,9 @@ abstract class BaseReader implements IReader
return $this->readEmptyCells; return $this->readEmptyCells;
} }
public function setReadEmptyCells($pValue) public function setReadEmptyCells($readEmptyCells)
{ {
$this->readEmptyCells = (bool) $pValue; $this->readEmptyCells = (bool) $readEmptyCells;
return $this; return $this;
} }
@ -90,9 +90,9 @@ abstract class BaseReader implements IReader
return $this->includeCharts; return $this->includeCharts;
} }
public function setIncludeCharts($pValue) public function setIncludeCharts($includeCharts)
{ {
$this->includeCharts = (bool) $pValue; $this->includeCharts = (bool) $includeCharts;
return $this; return $this;
} }
@ -102,13 +102,13 @@ abstract class BaseReader implements IReader
return $this->loadSheetsOnly; return $this->loadSheetsOnly;
} }
public function setLoadSheetsOnly($value) public function setLoadSheetsOnly($sheetList)
{ {
if ($value === null) { if ($sheetList === null) {
return $this->setLoadAllSheets(); return $this->setLoadAllSheets();
} }
$this->loadSheetsOnly = is_array($value) ? $value : [$value]; $this->loadSheetsOnly = is_array($sheetList) ? $sheetList : [$sheetList];
return $this; return $this;
} }
@ -125,9 +125,9 @@ abstract class BaseReader implements IReader
return $this->readFilter; return $this->readFilter;
} }
public function setReadFilter(IReadFilter $pValue) public function setReadFilter(IReadFilter $readFilter)
{ {
$this->readFilter = $pValue; $this->readFilter = $readFilter;
return $this; return $this;
} }
@ -147,22 +147,22 @@ abstract class BaseReader implements IReader
/** /**
* Open file for reading. * Open file for reading.
* *
* @param string $pFilename * @param string $filename
*/ */
protected function openFile($pFilename): void protected function openFile($filename): void
{ {
if ($pFilename) { if ($filename) {
File::assertFile($pFilename); File::assertFile($filename);
// Open file // Open file
$fileHandle = fopen($pFilename, 'rb'); $fileHandle = fopen($filename, 'rb');
} else { } else {
$fileHandle = false; $fileHandle = false;
} }
if ($fileHandle !== false) { if ($fileHandle !== false) {
$this->fileHandle = $fileHandle; $this->fileHandle = $fileHandle;
} else { } else {
throw new ReaderException('Could not open file ' . $pFilename . ' for reading.'); throw new ReaderException('Could not open file ' . $filename . ' for reading.');
} }
} }
} }

View File

@ -111,9 +111,9 @@ class Csv extends BaseReader
return self::$constructorCallback; return self::$constructorCallback;
} }
public function setInputEncoding(string $pValue): self public function setInputEncoding(string $encoding): self
{ {
$this->inputEncoding = $pValue; $this->inputEncoding = $encoding;
return $this; return $this;
} }
@ -198,10 +198,10 @@ class Csv extends BaseReader
/** /**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*/ */
public function listWorksheetInfo(string $pFilename): array public function listWorksheetInfo(string $filename): array
{ {
// Open file // Open file
$this->openFileOrMemory($pFilename); $this->openFileOrMemory($filename);
$fileHandle = $this->fileHandle; $fileHandle = $this->fileHandle;
// Skip BOM, if any // Skip BOM, if any
@ -238,7 +238,7 @@ class Csv extends BaseReader
* *
* @return Spreadsheet * @return Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0) public function load(string $filename, int $flags = 0)
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -246,23 +246,23 @@ class Csv extends BaseReader
$spreadsheet = new Spreadsheet(); $spreadsheet = new Spreadsheet();
// Load into this instance // Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet); return $this->loadIntoExisting($filename, $spreadsheet);
} }
private function openFileOrMemory(string $pFilename): void private function openFileOrMemory(string $filename): void
{ {
// Open file // Open file
$fhandle = $this->canRead($pFilename); $fhandle = $this->canRead($filename);
if (!$fhandle) { if (!$fhandle) {
throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); throw new Exception($filename . ' is an Invalid Spreadsheet file.');
} }
if ($this->inputEncoding === self::GUESS_ENCODING) { if ($this->inputEncoding === self::GUESS_ENCODING) {
$this->inputEncoding = self::guessEncoding($pFilename, $this->fallbackEncoding); $this->inputEncoding = self::guessEncoding($filename, $this->fallbackEncoding);
} }
$this->openFile($pFilename); $this->openFile($filename);
if ($this->inputEncoding !== 'UTF-8') { if ($this->inputEncoding !== 'UTF-8') {
fclose($this->fileHandle); fclose($this->fileHandle);
$entireFile = file_get_contents($pFilename); $entireFile = file_get_contents($filename);
$this->fileHandle = fopen('php://memory', 'r+b'); $this->fileHandle = fopen('php://memory', 'r+b');
if ($this->fileHandle !== false && $entireFile !== false) { if ($this->fileHandle !== false && $entireFile !== false) {
$data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding);
@ -288,13 +288,13 @@ class Csv extends BaseReader
/** /**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance. * Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
*/ */
public function loadIntoExisting(string $pFilename, Spreadsheet $spreadsheet): Spreadsheet public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet
{ {
// Deprecated in Php8.1 // Deprecated in Php8.1
$iniset = self::setAutoDetect('1'); $iniset = self::setAutoDetect('1');
// Open file // Open file
$this->openFileOrMemory($pFilename); $this->openFileOrMemory($filename);
$fileHandle = $this->fileHandle; $fileHandle = $this->fileHandle;
// Skip BOM, if any // Skip BOM, if any
@ -396,9 +396,9 @@ class Csv extends BaseReader
return $this->sheetIndex; return $this->sheetIndex;
} }
public function setSheetIndex(int $pValue): self public function setSheetIndex(int $indexValue): self
{ {
$this->sheetIndex = $pValue; $this->sheetIndex = $indexValue;
return $this; return $this;
} }
@ -427,27 +427,14 @@ class Csv extends BaseReader
return $this->escapeCharacter; return $this->escapeCharacter;
} }
/**
* Scrutinizer believes, incorrectly, that the specific pathinfo
* call in canRead can return something other than an array.
* Phpstan knows better.
* This function satisfies both.
*
* @param mixed $extension
*/
private static function extractStringLower($extension): string
{
return is_string($extension) ? strtolower($extension) : '';
}
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
// Check if file exists // Check if file exists
try { try {
$this->openFile($pFilename); $this->openFile($filename);
} catch (ReaderException $e) { } catch (ReaderException $e) {
return false; return false;
} }
@ -455,13 +442,13 @@ class Csv extends BaseReader
fclose($this->fileHandle); fclose($this->fileHandle);
// Trust file extension if any // Trust file extension if any
$extension = self::extractStringLower(pathinfo($pFilename, PATHINFO_EXTENSION)); $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (in_array($extension, ['csv', 'tsv'])) { if (in_array($extension, ['csv', 'tsv'])) {
return true; return true;
} }
// Attempt to guess mimetype // Attempt to guess mimetype
$type = mime_content_type($pFilename); $type = mime_content_type($filename);
$supportedTypes = [ $supportedTypes = [
'application/csv', 'application/csv',
'text/csv', 'text/csv',

View File

@ -7,13 +7,13 @@ class DefaultReadFilter implements IReadFilter
/** /**
* Should this cell be read? * Should this cell be read?
* *
* @param string $column Column address (as a string value like "A", or "IV") * @param string $columnAddress Column address (as a string value like "A", or "IV")
* @param int $row Row number * @param int $row Row number
* @param string $worksheetName Optional worksheet name * @param string $worksheetName Optional worksheet name
* *
* @return bool * @return bool
*/ */
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
return true; return true;
} }

View File

@ -78,20 +78,19 @@ class Gnumeric extends BaseReader
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
$data = '';
// Check if gzlib functions are available // Check if gzlib functions are available
if (File::testFileNoThrow($pFilename) && function_exists('gzread')) { if (File::testFileNoThrow($filename) && function_exists('gzread')) {
// Read signature data (first 3 bytes) // Read signature data (first 3 bytes)
$fh = fopen($pFilename, 'rb'); $fh = fopen($filename, 'rb');
if ($fh !== false) { if ($fh !== false) {
$data = fread($fh, 2); $data = fread($fh, 2);
fclose($fh); fclose($fh);
} }
} }
return $data === chr(0x1F) . chr(0x8B); return isset($data) && $data === chr(0x1F) . chr(0x8B);
} }
private static function matchXml(XMLReader $xml, string $expectedLocalName): bool private static function matchXml(XMLReader $xml, string $expectedLocalName): bool
@ -231,7 +230,7 @@ class Gnumeric extends BaseReader
* *
* @return Spreadsheet * @return Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0) public function load(string $filename, int $flags = 0)
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -240,7 +239,7 @@ class Gnumeric extends BaseReader
$spreadsheet->removeSheetByIndex(0); $spreadsheet->removeSheetByIndex(0);
// Load into this instance // Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet); return $this->loadIntoExisting($filename, $spreadsheet);
} }
/** /**

View File

@ -138,11 +138,11 @@ class Html extends BaseReader
/** /**
* Validate that the current file is an HTML file. * Validate that the current file is an HTML file.
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
// Check if file exists // Check if file exists
try { try {
$this->openFile($pFilename); $this->openFile($filename);
} catch (Exception $e) { } catch (Exception $e) {
return false; return false;
} }
@ -204,7 +204,7 @@ class Html extends BaseReader
* *
* @return Spreadsheet * @return Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0) public function load(string $filename, int $flags = 0)
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -212,7 +212,7 @@ class Html extends BaseReader
$spreadsheet = new Spreadsheet(); $spreadsheet = new Spreadsheet();
// Load into this instance // Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet); return $this->loadIntoExisting($filename, $spreadsheet);
} }
/** /**

View File

@ -7,11 +7,11 @@ interface IReadFilter
/** /**
* Should this cell be read? * Should this cell be read?
* *
* @param string $column Column address (as a string value like "A", or "IV") * @param string $columnAddress Column address (as a string value like "A", or "IV")
* @param int $row Row number * @param int $row Row number
* @param string $worksheetName Optional worksheet name * @param string $worksheetName Optional worksheet name
* *
* @return bool * @return bool
*/ */
public function readCell($column, $row, $worksheetName = ''); public function readCell($columnAddress, $row, $worksheetName = '');
} }

View File

@ -14,7 +14,7 @@ interface IReader
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
*/ */
public function canRead(string $pFilename): bool; public function canRead(string $filename): bool;
/** /**
* Read data only? * Read data only?
@ -125,5 +125,5 @@ interface IReader
* *
* @return \PhpOffice\PhpSpreadsheet\Spreadsheet * @return \PhpOffice\PhpSpreadsheet\Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0); public function load(string $filename, int $flags = 0);
} }

View File

@ -41,15 +41,15 @@ class Ods extends BaseReader
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
$mimeType = 'UNKNOWN'; $mimeType = 'UNKNOWN';
// Load file // Load file
if (File::testFileNoThrow($pFilename)) { if (File::testFileNoThrow($filename)) {
$zip = new ZipArchive(); $zip = new ZipArchive();
if ($zip->open($pFilename) === true) { if ($zip->open($filename) === true) {
// check if it is an OOXML archive // check if it is an OOXML archive
$stat = $zip->statName('mimetype'); $stat = $zip->statName('mimetype');
if ($stat && ($stat['size'] <= 255)) { if ($stat && ($stat['size'] <= 255)) {
@ -220,7 +220,7 @@ class Ods extends BaseReader
* *
* @return Spreadsheet * @return Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0) public function load(string $filename, int $flags = 0)
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -228,7 +228,7 @@ class Ods extends BaseReader
$spreadsheet = new Spreadsheet(); $spreadsheet = new Spreadsheet();
// Load into this instance // Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet); return $this->loadIntoExisting($filename, $spreadsheet);
} }
/** /**

View File

@ -65,10 +65,10 @@ class Slk extends BaseReader
/** /**
* Validate that the current file is a SYLK file. * Validate that the current file is a SYLK file.
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
try { try {
$this->openFile($pFilename); $this->openFile($filename);
} catch (ReaderException $e) { } catch (ReaderException $e) {
return false; return false;
} }
@ -194,7 +194,7 @@ class Slk extends BaseReader
* *
* @return Spreadsheet * @return Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0) public function load(string $filename, int $flags = 0)
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -202,7 +202,7 @@ class Slk extends BaseReader
$spreadsheet = new Spreadsheet(); $spreadsheet = new Spreadsheet();
// Load into this instance // Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet); return $this->loadIntoExisting($filename, $spreadsheet);
} }
private const COLOR_ARRAY = [ private const COLOR_ARRAY = [

View File

@ -420,9 +420,9 @@ class Xls extends BaseReader
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
if (!File::testFileNoThrow($pFilename)) { if (!File::testFileNoThrow($filename)) {
return false; return false;
} }
@ -431,7 +431,7 @@ class Xls extends BaseReader
$ole = new OLERead(); $ole = new OLERead();
// get excel data // get excel data
$ole->read($pFilename); $ole->read($filename);
return true; return true;
} catch (PhpSpreadsheetException $e) { } catch (PhpSpreadsheetException $e) {
@ -623,12 +623,12 @@ class Xls extends BaseReader
* *
* @return Spreadsheet * @return Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0) public function load(string $filename, int $flags = 0)
{ {
$this->processFlags($flags); $this->processFlags($flags);
// Read the OLE file // Read the OLE file
$this->loadOLE($pFilename); $this->loadOLE($filename);
// Initialisations // Initialisations
$this->spreadsheet = new Spreadsheet(); $this->spreadsheet = new Spreadsheet();

View File

@ -75,16 +75,16 @@ class Xlsx extends BaseReader
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
if (!File::testFileNoThrow($pFilename, self::INITIAL_FILE)) { if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) {
return false; return false;
} }
$result = false; $result = false;
$this->zip = $zip = new ZipArchive(); $this->zip = $zip = new ZipArchive();
if ($zip->open($pFilename) === true) { if ($zip->open($filename) === true) {
[$workbookBasename] = $this->getWorkbookBaseName(); [$workbookBasename] = $this->getWorkbookBaseName();
$result = !empty($workbookBasename); $result = !empty($workbookBasename);
@ -162,18 +162,18 @@ class Xlsx extends BaseReader
/** /**
* Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
* *
* @param string $pFilename * @param string $filename
* *
* @return array * @return array
*/ */
public function listWorksheetNames($pFilename) public function listWorksheetNames($filename)
{ {
File::assertFile($pFilename, self::INITIAL_FILE); File::assertFile($filename, self::INITIAL_FILE);
$worksheetNames = []; $worksheetNames = [];
$this->zip = $zip = new ZipArchive(); $this->zip = $zip = new ZipArchive();
$zip->open($pFilename); $zip->open($filename);
// The files we're looking at here are small enough that simpleXML is more efficient than XMLReader // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
$rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
@ -201,18 +201,18 @@ class Xlsx extends BaseReader
/** /**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
* *
* @param string $pFilename * @param string $filename
* *
* @return array * @return array
*/ */
public function listWorksheetInfo($pFilename) public function listWorksheetInfo($filename)
{ {
File::assertFile($pFilename, self::INITIAL_FILE); File::assertFile($filename, self::INITIAL_FILE);
$worksheetInfo = []; $worksheetInfo = [];
$this->zip = $zip = new ZipArchive(); $this->zip = $zip = new ZipArchive();
$zip->open($pFilename); $zip->open($filename);
$rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
foreach ($rels->Relationship as $relx) { foreach ($rels->Relationship as $relx) {
@ -252,7 +252,7 @@ class Xlsx extends BaseReader
$xml = new XMLReader(); $xml = new XMLReader();
$xml->xml( $xml->xml(
$this->securityScanner->scanFile( $this->securityScanner->scanFile(
'zip://' . File::realpath($pFilename) . '#' . $fileWorksheetPath 'zip://' . File::realpath($filename) . '#' . $fileWorksheetPath
), ),
null, null,
Settings::getLibXmlLoaderOptions() Settings::getLibXmlLoaderOptions()
@ -387,9 +387,9 @@ class Xlsx extends BaseReader
/** /**
* Loads Spreadsheet from file. * Loads Spreadsheet from file.
*/ */
public function load(string $pFilename, int $flags = 0): Spreadsheet public function load(string $filename, int $flags = 0): Spreadsheet
{ {
File::assertFile($pFilename, self::INITIAL_FILE); File::assertFile($filename, self::INITIAL_FILE);
$this->processFlags($flags); $this->processFlags($flags);
// Initialisations // Initialisations
@ -401,7 +401,7 @@ class Xlsx extends BaseReader
$unparsedLoadedData = []; $unparsedLoadedData = [];
$this->zip = $zip = new ZipArchive(); $this->zip = $zip = new ZipArchive();
$zip->open($pFilename); $zip->open($filename);
// Read the theme first, because we need the colour scheme when reading the styles // Read the theme first, because we need the colour scheme when reading the styles
[$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName(); [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName();
@ -1106,7 +1106,7 @@ class Xlsx extends BaseReader
$hfImages[(string) $shape['id']]->setName((string) $imageData['title']); $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
} }
$hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false); $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false);
$hfImages[(string) $shape['id']]->setResizeProportional(false); $hfImages[(string) $shape['id']]->setResizeProportional(false);
$hfImages[(string) $shape['id']]->setWidth($style['width']); $hfImages[(string) $shape['id']]->setWidth($style['width']);
$hfImages[(string) $shape['id']]->setHeight($style['height']); $hfImages[(string) $shape['id']]->setHeight($style['height']);
@ -1124,12 +1124,12 @@ class Xlsx extends BaseReader
} }
// TODO: Autoshapes from twoCellAnchors! // TODO: Autoshapes from twoCellAnchors!
$filename = dirname("$dir/$fileWorksheet") $drawingFilename = dirname("$dir/$fileWorksheet")
. '/_rels/' . '/_rels/'
. basename($fileWorksheet) . basename($fileWorksheet)
. '.rels'; . '.rels';
if ($zip->locateName($filename)) { if ($zip->locateName($drawingFilename)) {
$relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $relsWorksheet = $this->loadZipNoNamespace($drawingFilename, Namespaces::RELATIONSHIPS);
$drawings = []; $drawings = [];
foreach ($relsWorksheet->Relationship as $ele) { foreach ($relsWorksheet->Relationship as $ele) {
if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
@ -1142,8 +1142,8 @@ class Xlsx extends BaseReader
foreach ($xmlSheet->drawing as $drawing) { foreach ($xmlSheet->drawing as $drawing) {
$drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
$fileDrawing = $drawings[$drawingRelId]; $fileDrawing = $drawings[$drawingRelId];
$filename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels'; $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels';
$relsDrawing = $this->loadZipNoNamespace($filename, $xmlNamespaceBase); $relsDrawing = $this->loadZipNoNamespace($drawingFilename, $xmlNamespaceBase);
$images = []; $images = [];
$hyperlinks = []; $hyperlinks = [];
if ($relsDrawing && $relsDrawing->Relationship) { if ($relsDrawing && $relsDrawing->Relationship) {
@ -1188,7 +1188,7 @@ class Xlsx extends BaseReader
); );
if (isset($images[$embedImageKey])) { if (isset($images[$embedImageKey])) {
$objDrawing->setPath( $objDrawing->setPath(
'zip://' . File::realpath($pFilename) . '#' . 'zip://' . File::realpath($filename) . '#' .
$images[$embedImageKey], $images[$embedImageKey],
false false
); );
@ -1267,7 +1267,7 @@ class Xlsx extends BaseReader
); );
if (isset($images[$embedImageKey])) { if (isset($images[$embedImageKey])) {
$objDrawing->setPath( $objDrawing->setPath(
'zip://' . File::realpath($pFilename) . '#' . 'zip://' . File::realpath($filename) . '#' .
$images[$embedImageKey], $images[$embedImageKey],
false false
); );

View File

@ -54,7 +54,7 @@ class Xml extends BaseReader
/** /**
* Can the current IReader read the file? * Can the current IReader read the file?
*/ */
public function canRead(string $pFilename): bool public function canRead(string $filename): bool
{ {
// Office xmlns:o="urn:schemas-microsoft-com:office:office" // Office xmlns:o="urn:schemas-microsoft-com:office:office"
// Excel xmlns:x="urn:schemas-microsoft-com:office:excel" // Excel xmlns:x="urn:schemas-microsoft-com:office:excel"
@ -72,7 +72,7 @@ class Xml extends BaseReader
]; ];
// Open file // Open file
$data = file_get_contents($pFilename); $data = file_get_contents($filename);
// Why? // Why?
//$data = str_replace("'", '"', $data); // fix headers with single quote //$data = str_replace("'", '"', $data); // fix headers with single quote
@ -234,7 +234,7 @@ class Xml extends BaseReader
* *
* @return Spreadsheet * @return Spreadsheet
*/ */
public function load(string $pFilename, int $flags = 0) public function load(string $filename, int $flags = 0)
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -243,7 +243,7 @@ class Xml extends BaseReader
$spreadsheet->removeSheetByIndex(0); $spreadsheet->removeSheetByIndex(0);
// Load into this instance // Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet); return $this->loadIntoExisting($filename, $spreadsheet);
} }
/** /**

View File

@ -119,26 +119,26 @@ class ReferenceHelper
* *
* @param string $cellAddress Address of the cell we're testing * @param string $cellAddress Address of the cell we're testing
* @param int $beforeRow Number of the row we're inserting/deleting before * @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) * @param int $numberOfRows 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 $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 $numberOfCols Number of columns to insert/delete (negative values indicate deletion)
* *
* @return bool * @return bool
*/ */
private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfCols)
{ {
[$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress);
$cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn);
// Is cell within the range of rows/columns if we're deleting // Is cell within the range of rows/columns if we're deleting
if ( if (
$pNumRows < 0 && $numberOfRows < 0 &&
($cellRow >= ($beforeRow + $pNumRows)) && ($cellRow >= ($beforeRow + $numberOfRows)) &&
($cellRow < $beforeRow) ($cellRow < $beforeRow)
) { ) {
return true; return true;
} elseif ( } elseif (
$pNumCols < 0 && $numberOfCols < 0 &&
($cellColumnIndex >= ($beforeColumnIndex + $pNumCols)) && ($cellColumnIndex >= ($beforeColumnIndex + $numberOfCols)) &&
($cellColumnIndex < $beforeColumnIndex) ($cellColumnIndex < $beforeColumnIndex)
) { ) {
return true; return true;
@ -150,30 +150,30 @@ class ReferenceHelper
/** /**
* Update page breaks when inserting/deleting rows/columns. * Update page breaks when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $beforeRow Number of the row we're inserting/deleting before * @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) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustPageBreaks(Worksheet $pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void protected function adjustPageBreaks(Worksheet $worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void
{ {
$aBreaks = $pSheet->getBreaks(); $aBreaks = $worksheet->getBreaks();
($pNumCols > 0 || $pNumRows > 0) ? ($numberOfColumns > 0 || $numberOfRows > 0) ?
uksort($aBreaks, ['self', 'cellReverseSort']) : uksort($aBreaks, ['self', 'cellSort']); uksort($aBreaks, ['self', 'cellReverseSort']) : uksort($aBreaks, ['self', 'cellSort']);
foreach ($aBreaks as $key => $value) { foreach ($aBreaks as $key => $value) {
if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { if (self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) {
// If we're deleting, then clear any defined breaks that are within the range // If we're deleting, then clear any defined breaks that are within the range
// of rows/columns that we're deleting // of rows/columns that we're deleting
$pSheet->setBreak($key, Worksheet::BREAK_NONE); $worksheet->setBreak($key, Worksheet::BREAK_NONE);
} else { } else {
// Otherwise update any affected breaks by inserting a new break at the appropriate point // Otherwise update any affected breaks by inserting a new break at the appropriate point
// and removing the old affected break // and removing the old affected break
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($key != $newReference) { if ($key != $newReference) {
$pSheet->setBreak($newReference, $value) $worksheet->setBreak($newReference, $value)
->setBreak($key, Worksheet::BREAK_NONE); ->setBreak($key, Worksheet::BREAK_NONE);
} }
} }
@ -183,51 +183,49 @@ class ReferenceHelper
/** /**
* Update cell comments when inserting/deleting rows/columns. * Update cell comments when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
* @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $beforeRow Number of the row we're inserting/deleting before * @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) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void protected function adjustComments($worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void
{ {
$aComments = $pSheet->getComments(); $aComments = $worksheet->getComments();
$aNewComments = []; // the new array of all comments $aNewComments = []; // the new array of all comments
foreach ($aComments as $key => &$value) { foreach ($aComments as $key => &$value) {
// Any comments inside a deleted range will be ignored // Any comments inside a deleted range will be ignored
if (!self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { if (!self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) {
// Otherwise build a new array of comments indexed by the adjusted cell reference // Otherwise build a new array of comments indexed by the adjusted cell reference
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
$aNewComments[$newReference] = $value; $aNewComments[$newReference] = $value;
} }
} }
// Replace the comments array with the new set of comments // Replace the comments array with the new set of comments
$pSheet->setComments($aNewComments); $worksheet->setComments($aNewComments);
} }
/** /**
* Update hyperlinks when inserting/deleting rows/columns. * Update hyperlinks when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows 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): void protected function adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{ {
$aHyperlinkCollection = $pSheet->getHyperlinkCollection(); $aHyperlinkCollection = $worksheet->getHyperlinkCollection();
($pNumCols > 0 || $pNumRows > 0) ? ($numberOfColumns > 0 || $numberOfRows > 0) ?
uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : uksort($aHyperlinkCollection, ['self', 'cellSort']); uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : uksort($aHyperlinkCollection, ['self', 'cellSort']);
foreach ($aHyperlinkCollection as $key => $value) { foreach ($aHyperlinkCollection as $key => $value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($key != $newReference) { if ($key != $newReference) {
$pSheet->setHyperlink($newReference, $value); $worksheet->setHyperlink($newReference, $value);
$pSheet->setHyperlink($key, null); $worksheet->setHyperlink($key, null);
} }
} }
} }
@ -235,24 +233,22 @@ class ReferenceHelper
/** /**
* Update data validations when inserting/deleting rows/columns. * Update data validations when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
* @param 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 $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) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void protected function adjustDataValidations(Worksheet $worksheet, $pBefore, $pNumCols, $pNumRows): void
{ {
$aDataValidationCollection = $pSheet->getDataValidationCollection(); $aDataValidationCollection = $worksheet->getDataValidationCollection();
($pNumCols > 0 || $pNumRows > 0) ? ($pNumCols > 0 || $pNumRows > 0) ?
uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']); uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']);
foreach ($aDataValidationCollection as $key => $value) { foreach ($aDataValidationCollection as $key => $value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
if ($key != $newReference) { if ($key != $newReference) {
$pSheet->setDataValidation($newReference, $value); $worksheet->setDataValidation($newReference, $value);
$pSheet->setDataValidation($key, null); $worksheet->setDataValidation($key, null);
} }
} }
} }
@ -260,44 +256,40 @@ class ReferenceHelper
/** /**
* Update merged cells when inserting/deleting rows/columns. * Update merged cells when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows 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): void protected function adjustMergeCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{ {
$aMergeCells = $pSheet->getMergeCells(); $aMergeCells = $worksheet->getMergeCells();
$aNewMergeCells = []; // the new array of all merge cells $aNewMergeCells = []; // the new array of all merge cells
foreach ($aMergeCells as $key => &$value) { foreach ($aMergeCells as $key => &$value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
$aNewMergeCells[$newReference] = $newReference; $aNewMergeCells[$newReference] = $newReference;
} }
$pSheet->setMergeCells($aNewMergeCells); // replace the merge cells array $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array
} }
/** /**
* Update protected cells when inserting/deleting rows/columns. * Update protected cells when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows 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): void protected function adjustProtectedCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{ {
$aProtectedCells = $pSheet->getProtectedCells(); $aProtectedCells = $worksheet->getProtectedCells();
($pNumCols > 0 || $pNumRows > 0) ? ($numberOfColumns > 0 || $numberOfRows > 0) ?
uksort($aProtectedCells, ['self', 'cellReverseSort']) : uksort($aProtectedCells, ['self', 'cellSort']); uksort($aProtectedCells, ['self', 'cellReverseSort']) : uksort($aProtectedCells, ['self', 'cellSort']);
foreach ($aProtectedCells as $key => $value) { foreach ($aProtectedCells as $key => $value) {
$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($key != $newReference) { if ($key != $newReference) {
$pSheet->protectCells($newReference, $value, true); $worksheet->protectCells($newReference, $value, true);
$pSheet->unprotectCells($key); $worksheet->unprotectCells($key);
} }
} }
} }
@ -305,54 +297,51 @@ class ReferenceHelper
/** /**
* Update column dimensions when inserting/deleting rows/columns. * Update column dimensions when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows 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): void protected function adjustColumnDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{ {
$aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true); $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true);
if (!empty($aColumnDimensions)) { if (!empty($aColumnDimensions)) {
foreach ($aColumnDimensions as $objColumnDimension) { foreach ($aColumnDimensions as $objColumnDimension) {
$newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows);
[$newReference] = Coordinate::coordinateFromString($newReference); [$newReference] = Coordinate::coordinateFromString($newReference);
if ($objColumnDimension->getColumnIndex() != $newReference) { if ($objColumnDimension->getColumnIndex() != $newReference) {
$objColumnDimension->setColumnIndex($newReference); $objColumnDimension->setColumnIndex($newReference);
} }
} }
$pSheet->refreshColumnDimensions(); $worksheet->refreshColumnDimensions();
} }
} }
/** /**
* Update row dimensions when inserting/deleting rows/columns. * Update row dimensions when inserting/deleting rows/columns.
* *
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
* @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @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 $beforeRow Number of the row we're inserting/deleting before
* @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/ */
protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void protected function adjustRowDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows): void
{ {
$aRowDimensions = array_reverse($pSheet->getRowDimensions(), true); $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true);
if (!empty($aRowDimensions)) { if (!empty($aRowDimensions)) {
foreach ($aRowDimensions as $objRowDimension) { foreach ($aRowDimensions as $objRowDimension) {
$newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $beforeCellAddress, $numberOfColumns, $numberOfRows);
[, $newReference] = Coordinate::coordinateFromString($newReference); [, $newReference] = Coordinate::coordinateFromString($newReference);
if ($objRowDimension->getRowIndex() != $newReference) { if ($objRowDimension->getRowIndex() != $newReference) {
$objRowDimension->setRowIndex($newReference); $objRowDimension->setRowIndex($newReference);
} }
} }
$pSheet->refreshRowDimensions(); $worksheet->refreshRowDimensions();
$copyDimension = $pSheet->getRowDimension($beforeRow - 1); $copyDimension = $worksheet->getRowDimension($beforeRow - 1);
for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) { for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) {
$newDimension = $pSheet->getRowDimension($i); $newDimension = $worksheet->getRowDimension($i);
$newDimension->setRowHeight($copyDimension->getRowHeight()); $newDimension->setRowHeight($copyDimension->getRowHeight());
$newDimension->setVisible($copyDimension->getVisible()); $newDimension->setVisible($copyDimension->getVisible());
$newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
@ -364,46 +353,46 @@ class ReferenceHelper
/** /**
* Insert a new column or row, updating all possible related data. * Insert a new column or row, updating all possible related data.
* *
* @param string $pBefore Insert before this cell address (e.g. 'A1') * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1')
* @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
* @param Worksheet $pSheet The worksheet that we're editing * @param Worksheet $worksheet The worksheet that we're editing
*/ */
public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pSheet): void public function insertNewBefore($beforeCellAddress, $numberOfColumns, $numberOfRows, Worksheet $worksheet): void
{ {
$remove = ($pNumCols < 0 || $pNumRows < 0); $remove = ($numberOfColumns < 0 || $numberOfRows < 0);
$allCoordinates = $pSheet->getCoordinates(); $allCoordinates = $worksheet->getCoordinates();
// Get coordinate of $pBefore // Get coordinate of $beforeCellAddress
[$beforeColumn, $beforeRow] = Coordinate::indexesFromString($pBefore); [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress);
// Clear cells if we are removing columns or rows // Clear cells if we are removing columns or rows
$highestColumn = $pSheet->getHighestColumn(); $highestColumn = $worksheet->getHighestColumn();
$highestRow = $pSheet->getHighestRow(); $highestRow = $worksheet->getHighestRow();
// 1. Clear column strips if we are removing columns // 1. Clear column strips if we are removing columns
if ($pNumCols < 0 && $beforeColumn - 2 + $pNumCols > 0) { if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) {
for ($i = 1; $i <= $highestRow - 1; ++$i) { for ($i = 1; $i <= $highestRow - 1; ++$i) {
for ($j = $beforeColumn - 1 + $pNumCols; $j <= $beforeColumn - 2; ++$j) { for ($j = $beforeColumn - 1 + $numberOfColumns; $j <= $beforeColumn - 2; ++$j) {
$coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i; $coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i;
$pSheet->removeConditionalStyles($coordinate); $worksheet->removeConditionalStyles($coordinate);
if ($pSheet->cellExists($coordinate)) { if ($worksheet->cellExists($coordinate)) {
$pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
$pSheet->getCell($coordinate)->setXfIndex(0); $worksheet->getCell($coordinate)->setXfIndex(0);
} }
} }
} }
} }
// 2. Clear row strips if we are removing rows // 2. Clear row strips if we are removing rows
if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) { if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) {
for ($i = $beforeColumn - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) { for ($i = $beforeColumn - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) {
for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) { for ($j = $beforeRow + $numberOfRows; $j <= $beforeRow - 1; ++$j) {
$coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j; $coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j;
$pSheet->removeConditionalStyles($coordinate); $worksheet->removeConditionalStyles($coordinate);
if ($pSheet->cellExists($coordinate)) { if ($worksheet->cellExists($coordinate)) {
$pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
$pSheet->getCell($coordinate)->setXfIndex(0); $worksheet->getCell($coordinate)->setXfIndex(0);
} }
} }
} }
@ -415,85 +404,85 @@ class ReferenceHelper
$allCoordinates = array_reverse($allCoordinates); $allCoordinates = array_reverse($allCoordinates);
} }
while ($coordinate = array_pop($allCoordinates)) { while ($coordinate = array_pop($allCoordinates)) {
$cell = $pSheet->getCell($coordinate); $cell = $worksheet->getCell($coordinate);
$cellIndex = Coordinate::columnIndexFromString($cell->getColumn()); $cellIndex = Coordinate::columnIndexFromString($cell->getColumn());
if ($cellIndex - 1 + $pNumCols < 0) { if ($cellIndex - 1 + $numberOfColumns < 0) {
continue; continue;
} }
// New coordinate // New coordinate
$newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $pNumCols) . ($cell->getRow() + $pNumRows); $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows);
// Should the cell be updated? Move value and cellXf index from one cell to another. // Should the cell be updated? Move value and cellXf index from one cell to another.
if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) {
// Update cell styles // Update cell styles
$pSheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
// Insert this cell at its new location // Insert this cell at its new location
if ($cell->getDataType() == DataType::TYPE_FORMULA) { if ($cell->getDataType() == DataType::TYPE_FORMULA) {
// Formula should be adjusted // Formula should be adjusted
$pSheet->getCell($newCoordinate) $worksheet->getCell($newCoordinate)
->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
} else { } else {
// Formula should not be adjusted // Formula should not be adjusted
$pSheet->getCell($newCoordinate)->setValue($cell->getValue()); $worksheet->getCell($newCoordinate)->setValue($cell->getValue());
} }
// Clear the original cell // Clear the original cell
$pSheet->getCellCollection()->delete($coordinate); $worksheet->getCellCollection()->delete($coordinate);
} else { } else {
/* We don't need to update styles for rows/columns before our insertion position, /* We don't need to update styles for rows/columns before our insertion position,
but we do still need to adjust any formulae in those cells */ but we do still need to adjust any formulae in those cells */
if ($cell->getDataType() == DataType::TYPE_FORMULA) { if ($cell->getDataType() == DataType::TYPE_FORMULA) {
// Formula should be adjusted // Formula should be adjusted
$cell->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
} }
} }
} }
// Duplicate styles for the newly inserted cells // Duplicate styles for the newly inserted cells
$highestColumn = $pSheet->getHighestColumn(); $highestColumn = $worksheet->getHighestColumn();
$highestRow = $pSheet->getHighestRow(); $highestRow = $worksheet->getHighestRow();
if ($pNumCols > 0 && $beforeColumn - 2 > 0) { if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) {
for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
// Style // Style
$coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i; $coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i;
if ($pSheet->cellExists($coordinate)) { if ($worksheet->cellExists($coordinate)) {
$xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
$conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
$pSheet->getConditionalStyles($coordinate) : false; $worksheet->getConditionalStyles($coordinate) : false;
for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $pNumCols; ++$j) { for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) {
$pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
if ($conditionalStyles) { if ($conditionalStyles) {
$cloned = []; $cloned = [];
foreach ($conditionalStyles as $conditionalStyle) { foreach ($conditionalStyles as $conditionalStyle) {
$cloned[] = clone $conditionalStyle; $cloned[] = clone $conditionalStyle;
} }
$pSheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned); $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned);
} }
} }
} }
} }
} }
if ($pNumRows > 0 && $beforeRow - 1 > 0) { if ($numberOfRows > 0 && $beforeRow - 1 > 0) {
for ($i = $beforeColumn; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) { for ($i = $beforeColumn; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) {
// Style // Style
$coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1);
if ($pSheet->cellExists($coordinate)) { if ($worksheet->cellExists($coordinate)) {
$xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
$conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
$pSheet->getConditionalStyles($coordinate) : false; $worksheet->getConditionalStyles($coordinate) : false;
for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) { for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) {
$pSheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
if ($conditionalStyles) { if ($conditionalStyles) {
$cloned = []; $cloned = [];
foreach ($conditionalStyles as $conditionalStyle) { foreach ($conditionalStyles as $conditionalStyle) {
$cloned[] = clone $conditionalStyle; $cloned[] = clone $conditionalStyle;
} }
$pSheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned); $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned);
} }
} }
} }
@ -501,47 +490,47 @@ class ReferenceHelper
} }
// Update worksheet: column dimensions // Update worksheet: column dimensions
$this->adjustColumnDimensions($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustColumnDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: row dimensions // Update worksheet: row dimensions
$this->adjustRowDimensions($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows);
// Update worksheet: page breaks // Update worksheet: page breaks
$this->adjustPageBreaks($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
// Update worksheet: comments // Update worksheet: comments
$this->adjustComments($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
// Update worksheet: hyperlinks // Update worksheet: hyperlinks
$this->adjustHyperlinks($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: data validations // Update worksheet: data validations
$this->adjustDataValidations($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustDataValidations($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: merge cells // Update worksheet: merge cells
$this->adjustMergeCells($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustMergeCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: protected cells // Update worksheet: protected cells
$this->adjustProtectedCells($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); $this->adjustProtectedCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: autofilter // Update worksheet: autofilter
$autoFilter = $pSheet->getAutoFilter(); $autoFilter = $worksheet->getAutoFilter();
$autoFilterRange = $autoFilter->getRange(); $autoFilterRange = $autoFilter->getRange();
if (!empty($autoFilterRange)) { if (!empty($autoFilterRange)) {
if ($pNumCols != 0) { if ($numberOfColumns != 0) {
$autoFilterColumns = $autoFilter->getColumns(); $autoFilterColumns = $autoFilter->getColumns();
if (count($autoFilterColumns) > 0) { if (count($autoFilterColumns) > 0) {
$column = ''; $column = '';
$row = 0; $row = 0;
sscanf($pBefore, '%[A-Z]%d', $column, $row); sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
$columnIndex = Coordinate::columnIndexFromString($column); $columnIndex = Coordinate::columnIndexFromString($column);
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange);
if ($columnIndex <= $rangeEnd[0]) { if ($columnIndex <= $rangeEnd[0]) {
if ($pNumCols < 0) { if ($numberOfColumns < 0) {
// If we're actually deleting any columns that fall within the autofilter range, // If we're actually deleting any columns that fall within the autofilter range,
// then we delete any rules for those columns // then we delete any rules for those columns
$deleteColumn = $columnIndex + $pNumCols - 1; $deleteColumn = $columnIndex + $numberOfColumns - 1;
$deleteCount = abs($pNumCols); $deleteCount = abs($numberOfColumns);
for ($i = 1; $i <= $deleteCount; ++$i) { for ($i = 1; $i <= $deleteCount; ++$i) {
if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) { if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) {
$autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1)); $autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1));
@ -552,10 +541,10 @@ class ReferenceHelper
$startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
// Shuffle columns in autofilter range // Shuffle columns in autofilter range
if ($pNumCols > 0) { if ($numberOfColumns > 0) {
$startColRef = $startCol; $startColRef = $startCol;
$endColRef = $rangeEnd[0]; $endColRef = $rangeEnd[0];
$toColRef = $rangeEnd[0] + $pNumCols; $toColRef = $rangeEnd[0] + $numberOfColumns;
do { do {
$autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
@ -565,7 +554,7 @@ class ReferenceHelper
} else { } else {
// For delete, we shuffle from beginning to end to avoid overwriting // For delete, we shuffle from beginning to end to avoid overwriting
$startColID = Coordinate::stringFromColumnIndex($startCol); $startColID = Coordinate::stringFromColumnIndex($startCol);
$toColID = Coordinate::stringFromColumnIndex($startCol + $pNumCols); $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
$endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1); $endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1);
do { do {
$autoFilter->shiftColumn($startColID, $toColID); $autoFilter->shiftColumn($startColID, $toColID);
@ -576,62 +565,62 @@ class ReferenceHelper
} }
} }
} }
$pSheet->setAutoFilter($this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows)); $worksheet->setAutoFilter($this->updateCellReference($autoFilterRange, $beforeCellAddress, $numberOfColumns, $numberOfRows));
} }
// Update worksheet: freeze pane // Update worksheet: freeze pane
if ($pSheet->getFreezePane()) { if ($worksheet->getFreezePane()) {
$splitCell = $pSheet->getFreezePane() ?? ''; $splitCell = $worksheet->getFreezePane() ?? '';
$topLeftCell = $pSheet->getTopLeftCell() ?? ''; $topLeftCell = $worksheet->getTopLeftCell() ?? '';
$splitCell = $this->updateCellReference($splitCell, $pBefore, $pNumCols, $pNumRows); $splitCell = $this->updateCellReference($splitCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
$topLeftCell = $this->updateCellReference($topLeftCell, $pBefore, $pNumCols, $pNumRows); $topLeftCell = $this->updateCellReference($topLeftCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
$pSheet->freezePane($splitCell, $topLeftCell); $worksheet->freezePane($splitCell, $topLeftCell);
} }
// Page setup // Page setup
if ($pSheet->getPageSetup()->isPrintAreaSet()) { if ($worksheet->getPageSetup()->isPrintAreaSet()) {
$pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows)); $worksheet->getPageSetup()->setPrintArea($this->updateCellReference($worksheet->getPageSetup()->getPrintArea(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
} }
// Update worksheet: drawings // Update worksheet: drawings
$aDrawings = $pSheet->getDrawingCollection(); $aDrawings = $worksheet->getDrawingCollection();
foreach ($aDrawings as $objDrawing) { foreach ($aDrawings as $objDrawing) {
$newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows); $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($objDrawing->getCoordinates() != $newReference) { if ($objDrawing->getCoordinates() != $newReference) {
$objDrawing->setCoordinates($newReference); $objDrawing->setCoordinates($newReference);
} }
} }
// Update workbook: define names // Update workbook: define names
if (count($pSheet->getParent()->getDefinedNames()) > 0) { if (count($worksheet->getParent()->getDefinedNames()) > 0) {
foreach ($pSheet->getParent()->getDefinedNames() as $definedName) { foreach ($worksheet->getParent()->getDefinedNames() as $definedName) {
if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $pSheet->getHashCode()) { if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
$definedName->setValue($this->updateCellReference($definedName->getValue(), $pBefore, $pNumCols, $pNumRows)); $definedName->setValue($this->updateCellReference($definedName->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
} }
} }
} }
// Garbage collect // Garbage collect
$pSheet->garbageCollect(); $worksheet->garbageCollect();
} }
/** /**
* Update references within formulas. * Update references within formulas.
* *
* @param string $pFormula Formula to update * @param string $formula Formula to update
* @param string $pBefore Insert before this one * @param string $beforeCellAddress Insert before this one
* @param int $pNumCols Number of columns to insert * @param int $numberOfColumns Number of columns to insert
* @param int $pNumRows Number of rows to insert * @param int $numberOfRows Number of rows to insert
* @param string $sheetName Worksheet name/title * @param string $worksheetName Worksheet name/title
* *
* @return string Updated formula * @return string Updated formula
*/ */
public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') public function updateFormulaReferences($formula = '', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0, $worksheetName = '')
{ {
// Update cell references in the formula // Update cell references in the formula
$formulaBlocks = explode('"', $pFormula); $formulaBlocks = explode('"', $formula);
$i = false; $i = false;
foreach ($formulaBlocks as &$formulaBlock) { foreach ($formulaBlocks as &$formulaBlock) {
// Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
@ -644,11 +633,11 @@ class ReferenceHelper
foreach ($matches as $match) { foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3] . ':' . $match[4]; $fromString .= $match[3] . ':' . $match[4];
$modified3 = substr($this->updateCellReference('$A' . $match[3], $pBefore, $pNumCols, $pNumRows), 2); $modified3 = substr($this->updateCellReference('$A' . $match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
$modified4 = substr($this->updateCellReference('$A' . $match[4], $pBefore, $pNumCols, $pNumRows), 2); $modified4 = substr($this->updateCellReference('$A' . $match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
$toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3 . ':' . $modified4; $toString .= $modified3 . ':' . $modified4;
// Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
@ -669,11 +658,11 @@ class ReferenceHelper
foreach ($matches as $match) { foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3] . ':' . $match[4]; $fromString .= $match[3] . ':' . $match[4];
$modified3 = substr($this->updateCellReference($match[3] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2); $modified3 = substr($this->updateCellReference($match[3] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
$modified4 = substr($this->updateCellReference($match[4] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2); $modified4 = substr($this->updateCellReference($match[4] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
$toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3 . ':' . $modified4; $toString .= $modified3 . ':' . $modified4;
// Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
@ -694,11 +683,11 @@ class ReferenceHelper
foreach ($matches as $match) { foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3] . ':' . $match[4]; $fromString .= $match[3] . ':' . $match[4];
$modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
$modified4 = $this->updateCellReference($match[4], $pBefore, $pNumCols, $pNumRows); $modified4 = $this->updateCellReference($match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($match[3] . $match[4] !== $modified3 . $modified4) { if ($match[3] . $match[4] !== $modified3 . $modified4) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
$toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3 . ':' . $modified4; $toString .= $modified3 . ':' . $modified4;
[$column, $row] = Coordinate::coordinateFromString($match[3]); [$column, $row] = Coordinate::coordinateFromString($match[3]);
@ -722,9 +711,9 @@ class ReferenceHelper
$fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3]; $fromString .= $match[3];
$modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($match[3] !== $modified3) { if ($match[3] !== $modified3) {
if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
$toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString = ($match[2] > '') ? $match[2] . '!' : '';
$toString .= $modified3; $toString .= $modified3;
[$column, $row] = Coordinate::coordinateFromString($match[3]); [$column, $row] = Coordinate::coordinateFromString($match[3]);
@ -741,7 +730,7 @@ class ReferenceHelper
} }
} }
if ($adjustCount > 0) { if ($adjustCount > 0) {
if ($pNumCols > 0 || $pNumRows > 0) { if ($numberOfColumns > 0 || $numberOfRows > 0) {
krsort($cellTokens); krsort($cellTokens);
krsort($newCellTokens); krsort($newCellTokens);
} else { } else {
@ -761,22 +750,22 @@ class ReferenceHelper
/** /**
* Update all cell references within a formula, irrespective of worksheet. * Update all cell references within a formula, irrespective of worksheet.
*/ */
public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $insertColumns = 0, int $insertRows = 0): string public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
{ {
$formula = $this->updateCellReferencesAllWorksheets($formula, $insertColumns, $insertRows); $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
if ($insertColumns !== 0) { if ($numberOfColumns !== 0) {
$formula = $this->updateColumnRangesAllWorksheets($formula, $insertColumns); $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
} }
if ($insertRows !== 0) { if ($numberOfRows !== 0) {
$formula = $this->updateRowRangesAllWorksheets($formula, $insertRows); $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
} }
return $formula; return $formula;
} }
private function updateCellReferencesAllWorksheets(string $formula, int $insertColumns, int $insertRows): string private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
{ {
$splitCount = preg_match_all( $splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
@ -803,11 +792,11 @@ class ReferenceHelper
$row = $rows[$splitCount][0]; $row = $rows[$splitCount][0];
if (!empty($column) && $column[0] !== '$') { if (!empty($column) && $column[0] !== '$') {
$column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $insertColumns); $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns);
$formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength); $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
} }
if (!empty($row) && $row[0] !== '$') { if (!empty($row) && $row[0] !== '$') {
$row += $insertRows; $row += $numberOfRows;
$formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength); $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
} }
} }
@ -815,7 +804,7 @@ class ReferenceHelper
return $formula; return $formula;
} }
private function updateColumnRangesAllWorksheets(string $formula, int $insertColumns): string private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
{ {
$splitCount = preg_match_all( $splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui', '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
@ -842,11 +831,11 @@ class ReferenceHelper
$toColumn = $toColumns[$splitCount][0]; $toColumn = $toColumns[$splitCount][0];
if (!empty($fromColumn) && $fromColumn[0] !== '$') { if (!empty($fromColumn) && $fromColumn[0] !== '$') {
$fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $insertColumns); $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns);
$formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength); $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength);
} }
if (!empty($toColumn) && $toColumn[0] !== '$') { if (!empty($toColumn) && $toColumn[0] !== '$') {
$toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $insertColumns); $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
$formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength); $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
} }
} }
@ -854,7 +843,7 @@ class ReferenceHelper
return $formula; return $formula;
} }
private function updateRowRangesAllWorksheets(string $formula, int $insertRows): string private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
{ {
$splitCount = preg_match_all( $splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui', '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
@ -881,11 +870,11 @@ class ReferenceHelper
$toRow = $toRows[$splitCount][0]; $toRow = $toRows[$splitCount][0];
if (!empty($fromRow) && $fromRow[0] !== '$') { if (!empty($fromRow) && $fromRow[0] !== '$') {
$fromRow += $insertRows; $fromRow += $numberOfRows;
$formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength); $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
} }
if (!empty($toRow) && $toRow[0] !== '$') { if (!empty($toRow) && $toRow[0] !== '$') {
$toRow += $insertRows; $toRow += $numberOfRows;
$formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength); $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
} }
} }
@ -896,29 +885,29 @@ class ReferenceHelper
/** /**
* Update cell reference. * Update cell reference.
* *
* @param string $pCellRange Cell range * @param string $cellReference Cell address or range of addresses
* @param string $pBefore Insert before this one * @param string $beforeCellAddress Insert before this one
* @param int $pNumCols Number of columns to increment * @param int $numberOfColumns Number of columns to increment
* @param int $pNumRows Number of rows to increment * @param int $numberOfRows Number of rows to increment
* *
* @return string Updated cell range * @return string Updated cell range
*/ */
public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) public function updateCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
{ {
// Is it in another worksheet? Will not have to update anything. // Is it in another worksheet? Will not have to update anything.
if (strpos($pCellRange, '!') !== false) { if (strpos($cellReference, '!') !== false) {
return $pCellRange; return $cellReference;
// Is it a range or a single cell? // Is it a range or a single cell?
} elseif (!Coordinate::coordinateIsRange($pCellRange)) { } elseif (!Coordinate::coordinateIsRange($cellReference)) {
// Single cell // Single cell
return $this->updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows); return $this->updateSingleCellReference($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
} elseif (Coordinate::coordinateIsRange($pCellRange)) { } elseif (Coordinate::coordinateIsRange($cellReference)) {
// Range // Range
return $this->updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows); return $this->updateCellRange($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
} }
// Return original // Return original
return $pCellRange; return $cellReference;
} }
/** /**
@ -952,33 +941,33 @@ class ReferenceHelper
/** /**
* Update cell range. * Update cell range.
* *
* @param string $pCellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
* @param string $pBefore Insert before this one * @param string $beforeCellAddress Insert before this one
* @param int $pNumCols Number of columns to increment * @param int $numberOfColumns Number of columns to increment
* @param int $pNumRows Number of rows to increment * @param int $numberOfRows Number of rows to increment
* *
* @return string Updated cell range * @return string Updated cell range
*/ */
private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) private function updateCellRange($cellRange = 'A1:A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
{ {
if (!Coordinate::coordinateIsRange($pCellRange)) { if (!Coordinate::coordinateIsRange($cellRange)) {
throw new Exception('Only cell ranges may be passed to this method.'); throw new Exception('Only cell ranges may be passed to this method.');
} }
// Update range // Update range
$range = Coordinate::splitRange($pCellRange); $range = Coordinate::splitRange($cellRange);
$ic = count($range); $ic = count($range);
for ($i = 0; $i < $ic; ++$i) { for ($i = 0; $i < $ic; ++$i) {
$jc = count($range[$i]); $jc = count($range[$i]);
for ($j = 0; $j < $jc; ++$j) { for ($j = 0; $j < $jc; ++$j) {
if (ctype_alpha($range[$i][$j])) { if (ctype_alpha($range[$i][$j])) {
$r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $pBefore, $pNumCols, $pNumRows)); $r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows));
$range[$i][$j] = $r[0]; $range[$i][$j] = $r[0];
} elseif (ctype_digit($range[$i][$j])) { } elseif (ctype_digit($range[$i][$j])) {
$r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $pBefore, $pNumCols, $pNumRows)); $r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows));
$range[$i][$j] = $r[1]; $range[$i][$j] = $r[1];
} else { } else {
$range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows); $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows);
} }
} }
} }
@ -990,24 +979,24 @@ class ReferenceHelper
/** /**
* Update single cell reference. * Update single cell reference.
* *
* @param string $pCellReference Single cell reference * @param string $cellReference Single cell reference
* @param string $pBefore Insert before this one * @param string $beforeCellAddress Insert before this one
* @param int $pNumCols Number of columns to increment * @param int $numberOfColumns Number of columns to increment
* @param int $pNumRows Number of rows to increment * @param int $numberOfRows Number of rows to increment
* *
* @return string Updated cell reference * @return string Updated cell reference
*/ */
private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) private function updateSingleCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
{ {
if (Coordinate::coordinateIsRange($pCellReference)) { if (Coordinate::coordinateIsRange($cellReference)) {
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.');
} }
// Get coordinate of $pBefore // Get coordinate of $beforeCellAddress
[$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($pBefore); [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress);
// Get coordinate of $pCellReference // Get coordinate of $cellReference
[$newColumn, $newRow] = Coordinate::coordinateFromString($pCellReference); [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference);
// Verify which parts should be updated // Verify which parts should be updated
$updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn))); $updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn)));
@ -1015,12 +1004,12 @@ class ReferenceHelper
// Create new column reference // Create new column reference
if ($updateColumn) { if ($updateColumn) {
$newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $pNumCols); $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $numberOfColumns);
} }
// Create new row reference // Create new row reference
if ($updateRow) { if ($updateRow) {
$newRow = (int) $newRow + $pNumRows; $newRow = (int) $newRow + $numberOfRows;
} }
// Return new reference // Return new reference

View File

@ -42,13 +42,13 @@ class RichText implements IComparable
/** /**
* Add text. * Add text.
* *
* @param ITextElement $pText Rich text element * @param ITextElement $text Rich text element
* *
* @return $this * @return $this
*/ */
public function addText(ITextElement $pText) public function addText(ITextElement $text)
{ {
$this->richTextElements[] = $pText; $this->richTextElements[] = $text;
return $this; return $this;
} }
@ -56,13 +56,13 @@ class RichText implements IComparable
/** /**
* Create text. * Create text.
* *
* @param string $pText Text * @param string $text Text
* *
* @return TextElement * @return TextElement
*/ */
public function createText($pText) public function createText($text)
{ {
$objText = new TextElement($pText); $objText = new TextElement($text);
$this->addText($objText); $this->addText($objText);
return $objText; return $objText;
@ -71,13 +71,13 @@ class RichText implements IComparable
/** /**
* Create text run. * Create text run.
* *
* @param string $pText Text * @param string $text Text
* *
* @return Run * @return Run
*/ */
public function createTextRun($pText) public function createTextRun($text)
{ {
$objText = new Run($pText); $objText = new Run($text);
$this->addText($objText); $this->addText($objText);
return $objText; return $objText;

View File

@ -16,11 +16,11 @@ class Run extends TextElement implements ITextElement
/** /**
* Create a new Run instance. * Create a new Run instance.
* *
* @param string $pText Text * @param string $text Text
*/ */
public function __construct($pText = '') public function __construct($text = '')
{ {
parent::__construct($pText); parent::__construct($text);
// Initialise variables // Initialise variables
$this->font = new Font(); $this->font = new Font();
} }
@ -38,13 +38,13 @@ class Run extends TextElement implements ITextElement
/** /**
* Set font. * Set font.
* *
* @param Font $pFont Font * @param Font $font Font
* *
* @return $this * @return $this
*/ */
public function setFont(?Font $pFont = null) public function setFont(?Font $font = null)
{ {
$this->font = $pFont; $this->font = $font;
return $this; return $this;
} }

View File

@ -14,12 +14,12 @@ class TextElement implements ITextElement
/** /**
* Create a new TextElement instance. * Create a new TextElement instance.
* *
* @param string $pText Text * @param string $text Text
*/ */
public function __construct($pText = '') public function __construct($text = '')
{ {
// Initialise variables // Initialise variables
$this->text = $pText; $this->text = $text;
} }
/** /**

View File

@ -63,7 +63,7 @@ class Settings
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function setLocale($locale) public static function setLocale(string $locale)
{ {
return Calculation::getInstance()->setLocale($locale); return Calculation::getInstance()->setLocale($locale);
} }
@ -76,16 +76,16 @@ class Settings
/** /**
* Identify to PhpSpreadsheet the external library to use for rendering charts. * Identify to PhpSpreadsheet the external library to use for rendering charts.
* *
* @param string $rendererClass Class name of the chart renderer * @param string $rendererClassName Class name of the chart renderer
* eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph
*/ */
public static function setChartRenderer($rendererClass): void public static function setChartRenderer(string $rendererClassName): void
{ {
if (!is_a($rendererClass, IRenderer::class, true)) { if (!is_a($rendererClassName, IRenderer::class, true)) {
throw new Exception('Chart renderer must implement ' . IRenderer::class); throw new Exception('Chart renderer must implement ' . IRenderer::class);
} }
self::$chartRenderer = $rendererClass; self::$chartRenderer = $rendererClassName;
} }
/** /**
@ -94,7 +94,7 @@ class Settings
* @return null|string Class name of the chart renderer * @return null|string Class name of the chart renderer
* eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph
*/ */
public static function getChartRenderer() public static function getChartRenderer(): ?string
{ {
return self::$chartRenderer; return self::$chartRenderer;
} }
@ -123,7 +123,7 @@ class Settings
* *
* @return int Default options for libxml loader * @return int Default options for libxml loader
*/ */
public static function getLibXmlLoaderOptions() public static function getLibXmlLoaderOptions(): int
{ {
if (self::$libXmlLoaderOptions === null && defined('LIBXML_DTDLOAD')) { if (self::$libXmlLoaderOptions === null && defined('LIBXML_DTDLOAD')) {
self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR); self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR);
@ -154,7 +154,7 @@ class Settings
* *
* @return bool $state * @return bool $state
*/ */
public static function getLibXmlDisableEntityLoader() public static function getLibXmlDisableEntityLoader(): bool
{ {
return self::$libXmlDisableEntityLoader; return self::$libXmlDisableEntityLoader;
} }
@ -168,11 +168,9 @@ class Settings
} }
/** /**
* Gets the implementation of cache that should be used for cell collection. * Gets the implementation of cache that is being used for cell collection.
*
* @return CacheInterface
*/ */
public static function getCache() public static function getCache(): CacheInterface
{ {
if (!self::$cache) { if (!self::$cache) {
self::$cache = new Memory(); self::$cache = new Memory();

View File

@ -66,17 +66,17 @@ class Date
/** /**
* Set the Excel calendar (Windows 1900 or Mac 1904). * Set the Excel calendar (Windows 1900 or Mac 1904).
* *
* @param int $baseDate Excel base date (1900 or 1904) * @param int $baseYear Excel base date (1900 or 1904)
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function setExcelCalendar($baseDate) public static function setExcelCalendar($baseYear)
{ {
if ( if (
($baseDate == self::CALENDAR_WINDOWS_1900) || ($baseYear == self::CALENDAR_WINDOWS_1900) ||
($baseDate == self::CALENDAR_MAC_1904) ($baseYear == self::CALENDAR_MAC_1904)
) { ) {
self::$excelCalendar = $baseDate; self::$excelCalendar = $baseYear;
return true; return true;
} }
@ -263,17 +263,17 @@ class Date
/** /**
* Convert a Unix timestamp to an MS Excel serialized date/time value. * Convert a Unix timestamp to an MS Excel serialized date/time value.
* *
* @param int $dateValue Unix Timestamp * @param int $unixTimestamp Unix Timestamp
* *
* @return false|float MS Excel serialized date/time value * @return false|float MS Excel serialized date/time value
*/ */
public static function timestampToExcel($dateValue) public static function timestampToExcel($unixTimestamp)
{ {
if (!is_numeric($dateValue)) { if (!is_numeric($unixTimestamp)) {
return false; return false;
} }
return self::dateTimeToExcel(new DateTime('@' . $dateValue)); return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp));
} }
/** /**
@ -343,9 +343,9 @@ class Date
* *
* @return bool * @return bool
*/ */
public static function isDateTimeFormat(NumberFormat $pFormat) public static function isDateTimeFormat(NumberFormat $excelFormatCode)
{ {
return self::isDateTimeFormatCode($pFormat->getFormatCode()); return self::isDateTimeFormatCode($excelFormatCode->getFormatCode());
} }
private static $possibleDateFormatCharacters = 'eymdHs'; private static $possibleDateFormatCharacters = 'eymdHs';
@ -353,23 +353,23 @@ class Date
/** /**
* Is a given number format code a date/time? * Is a given number format code a date/time?
* *
* @param string $pFormatCode * @param string $excelFormatCode
* *
* @return bool * @return bool
*/ */
public static function isDateTimeFormatCode($pFormatCode) public static function isDateTimeFormatCode($excelFormatCode)
{ {
if (strtolower($pFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) { if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
// "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check) // "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check)
return false; return false;
} }
if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) { if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) {
// Scientific format // Scientific format
return false; return false;
} }
// Switch on formatcode // Switch on formatcode
switch ($pFormatCode) { switch ($excelFormatCode) {
// Explicitly defined date formats // Explicitly defined date formats
case NumberFormat::FORMAT_DATE_YYYYMMDD: case NumberFormat::FORMAT_DATE_YYYYMMDD:
case NumberFormat::FORMAT_DATE_YYYYMMDD2: case NumberFormat::FORMAT_DATE_YYYYMMDD2:
@ -397,21 +397,21 @@ class Date
} }
// Typically number, currency or accounting (or occasionally fraction) formats // Typically number, currency or accounting (or occasionally fraction) formats
if ((substr($pFormatCode, 0, 1) == '_') || (substr($pFormatCode, 0, 2) == '0 ')) { if ((substr($excelFormatCode, 0, 1) == '_') || (substr($excelFormatCode, 0, 2) == '0 ')) {
return false; return false;
} }
// Some "special formats" provided in German Excel versions were detected as date time value, // Some "special formats" provided in German Excel versions were detected as date time value,
// so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany). // so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany).
if (\strpos($pFormatCode, '-00000') !== false) { if (\strpos($excelFormatCode, '-00000') !== false) {
return false; return false;
} }
// Try checking for any of the date formatting characters that don't appear within square braces // Try checking for any of the date formatting characters that don't appear within square braces
if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $pFormatCode)) { if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $excelFormatCode)) {
// We might also have a format mask containing quoted strings... // We might also have a format mask containing quoted strings...
// we don't want to test for any of our characters within the quoted blocks // we don't want to test for any of our characters within the quoted blocks
if (strpos($pFormatCode, '"') !== false) { if (strpos($excelFormatCode, '"') !== false) {
$segMatcher = false; $segMatcher = false;
foreach (explode('"', $pFormatCode) as $subVal) { foreach (explode('"', $excelFormatCode) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks) // Only test in alternate array entries (the non-quoted blocks)
if ( if (
($segMatcher = !$segMatcher) && ($segMatcher = !$segMatcher) &&
@ -467,21 +467,21 @@ class Date
/** /**
* Converts a month name (either a long or a short name) to a month number. * Converts a month name (either a long or a short name) to a month number.
* *
* @param string $month Month name or abbreviation * @param string $monthName Month name or abbreviation
* *
* @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
*/ */
public static function monthStringToNumber($month) public static function monthStringToNumber($monthName)
{ {
$monthIndex = 1; $monthIndex = 1;
foreach (self::$monthNames as $shortMonthName => $longMonthName) { foreach (self::$monthNames as $shortMonthName => $longMonthName) {
if (($month === $longMonthName) || ($month === $shortMonthName)) { if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) {
return $monthIndex; return $monthIndex;
} }
++$monthIndex; ++$monthIndex;
} }
return $month; return $monthName;
} }
/** /**

View File

@ -42,15 +42,14 @@ class Drawing
* This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional. * This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional.
* *
* @param int $pixelValue Value in pixels * @param int $pixelValue Value in pixels
* @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook
* *
* @return float|int Value in cell dimension * @return float|int Value in cell dimension
*/ */
public static function pixelsToCellDimension($pixelValue, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont) public static function pixelsToCellDimension($pixelValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont)
{ {
// Font name and size // Font name and size
$name = $pDefaultFont->getName(); $name = $defaultFont->getName();
$size = $pDefaultFont->getSize(); $size = $defaultFont->getSize();
if (isset(Font::$defaultColumnWidths[$name][$size])) { if (isset(Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined // Exact width can be determined
@ -126,27 +125,27 @@ class Drawing
/** /**
* Convert degrees to angle. * Convert degrees to angle.
* *
* @param int $pValue Degrees * @param int $degrees Degrees
* *
* @return int Angle * @return int Angle
*/ */
public static function degreesToAngle($pValue) public static function degreesToAngle($degrees)
{ {
return (int) round($pValue * 60000); return (int) round($degrees * 60000);
} }
/** /**
* Convert angle to degrees. * Convert angle to degrees.
* *
* @param int|SimpleXMLElement $pValue Angle * @param int|SimpleXMLElement $angle Angle
* *
* @return int Degrees * @return int Degrees
*/ */
public static function angleToDegrees($pValue) public static function angleToDegrees($angle)
{ {
$pValue = (int) $pValue; $angle = (int) $angle;
if ($pValue != 0) { if ($angle != 0) {
return (int) round($pValue / 60000); return (int) round($angle / 60000);
} }
return 0; return 0;
@ -157,14 +156,14 @@ class Drawing
* *
* @see http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214 * @see http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
* *
* @param string $p_sFile Path to Windows DIB (BMP) image * @param string $bmpFilename Path to Windows DIB (BMP) image
* *
* @return GdImage|resource * @return GdImage|resource
*/ */
public static function imagecreatefrombmp($p_sFile) public static function imagecreatefrombmp($bmpFilename)
{ {
// Load the image into a string // Load the image into a string
$file = fopen($p_sFile, 'rb'); $file = fopen($bmpFilename, 'rb');
$read = fread($file, 10); $read = fread($file, 10);
while (!feof($file) && ($read != '')) { while (!feof($file) && ($read != '')) {
$read .= fread($file, 1024); $read .= fread($file, 1024);

View File

@ -49,15 +49,15 @@ class File
/** /**
* Verify if a file exists. * Verify if a file exists.
*/ */
public static function fileExists(string $pFilename): bool public static function fileExists(string $filename): bool
{ {
// Sick construction, but it seems that // Sick construction, but it seems that
// file_exists returns strange values when // file_exists returns strange values when
// doing the original file_exists on ZIP archives... // doing the original file_exists on ZIP archives...
if (strtolower(substr($pFilename, 0, 6)) == 'zip://') { if (strtolower(substr($filename, 0, 6)) == 'zip://') {
// Open ZIP file and verify if the file exists // Open ZIP file and verify if the file exists
$zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); $zipFile = substr($filename, 6, strpos($filename, '#') - 6);
$archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); $archiveFile = substr($filename, strpos($filename, '#') + 1);
if (self::validateZipFirst4($zipFile)) { if (self::validateZipFirst4($zipFile)) {
$zip = new ZipArchive(); $zip = new ZipArchive();
@ -73,25 +73,25 @@ class File
return false; return false;
} }
return file_exists($pFilename); return file_exists($filename);
} }
/** /**
* Returns canonicalized absolute pathname, also for ZIP archives. * Returns canonicalized absolute pathname, also for ZIP archives.
*/ */
public static function realpath(string $pFilename): string public static function realpath(string $filename): string
{ {
// Returnvalue // Returnvalue
$returnValue = ''; $returnValue = '';
// Try using realpath() // Try using realpath()
if (file_exists($pFilename)) { if (file_exists($filename)) {
$returnValue = realpath($pFilename) ?: ''; $returnValue = realpath($filename) ?: '';
} }
// Found something? // Found something?
if ($returnValue === '') { if ($returnValue === '') {
$pathArray = explode('/', $pFilename); $pathArray = explode('/', $filename);
while (in_array('..', $pathArray) && $pathArray[0] != '..') { while (in_array('..', $pathArray) && $pathArray[0] != '..') {
$iMax = count($pathArray); $iMax = count($pathArray);
for ($i = 0; $i < $iMax; ++$i) { for ($i = 0; $i < $iMax; ++$i) {

View File

@ -5,6 +5,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Font as FontStyle;
class Font class Font
{ {
@ -164,16 +165,16 @@ class Font
/** /**
* Set autoSize method. * Set autoSize method.
* *
* @param string $pValue see self::AUTOSIZE_METHOD_* * @param string $method see self::AUTOSIZE_METHOD_*
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function setAutoSizeMethod($pValue) public static function setAutoSizeMethod($method)
{ {
if (!in_array($pValue, self::$autoSizeMethods)) { if (!in_array($method, self::$autoSizeMethods)) {
return false; return false;
} }
self::$autoSizeMethod = $pValue; self::$autoSizeMethod = $method;
return true; return true;
} }
@ -197,11 +198,11 @@ class Font
* <li>~/.fonts/</li> * <li>~/.fonts/</li>
* </ul>. * </ul>.
* *
* @param string $pValue * @param string $folderPath
*/ */
public static function setTrueTypeFontPath($pValue): void public static function setTrueTypeFontPath($folderPath): void
{ {
self::$trueTypeFontPath = $pValue; self::$trueTypeFontPath = $folderPath;
} }
/** /**
@ -217,14 +218,14 @@ class Font
/** /**
* Calculate an (approximate) OpenXML column width, based on font size and text contained. * Calculate an (approximate) OpenXML column width, based on font size and text contained.
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font Font object * @param FontStyle $font Font object
* @param RichText|string $cellText Text to calculate width * @param RichText|string $cellText Text to calculate width
* @param int $rotation Rotation angle * @param int $rotation Rotation angle
* @param null|\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Font object * @param null|FontStyle $defaultFont Font object
* *
* @return int Column width * @return int Column width
*/ */
public static function calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font $font, $cellText = '', $rotation = 0, ?\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont = null) public static function calculateColumnWidth(FontStyle $font, $cellText = '', $rotation = 0, ?FontStyle $defaultFont = null)
{ {
// If it is rich text, use plain text // If it is rich text, use plain text
if ($cellText instanceof RichText) { if ($cellText instanceof RichText) {
@ -274,7 +275,7 @@ class Font
/** /**
* Get GD text width in pixels for a string of text in a certain font at a certain rotation angle. * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle.
*/ */
public static function getTextWidthPixelsExact(string $text, \PhpOffice\PhpSpreadsheet\Style\Font $font, int $rotation = 0): int public static function getTextWidthPixelsExact(string $text, FontStyle $font, int $rotation = 0): int
{ {
if (!function_exists('imagettfbbox')) { if (!function_exists('imagettfbbox')) {
throw new PhpSpreadsheetException('GD library needs to be enabled'); throw new PhpSpreadsheetException('GD library needs to be enabled');
@ -303,7 +304,7 @@ class Font
* *
* @return int Text width in pixels (no padding added) * @return int Text width in pixels (no padding added)
*/ */
public static function getTextWidthPixelsApprox($columnText, \PhpOffice\PhpSpreadsheet\Style\Font $font, $rotation = 0) public static function getTextWidthPixelsApprox($columnText, FontStyle $font, $rotation = 0)
{ {
$fontName = $font->getName(); $fontName = $font->getName();
$fontSize = $font->getSize(); $fontSize = $font->getSize();
@ -391,11 +392,9 @@ class Font
/** /**
* Returns the font path given the font. * Returns the font path given the font.
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font
*
* @return string Path to TrueType font file * @return string Path to TrueType font file
*/ */
public static function getTrueTypeFontFileFromFont($font) public static function getTrueTypeFontFileFromFont(FontStyle $font)
{ {
if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) { if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) {
throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified'); throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified');
@ -521,13 +520,13 @@ class Font
/** /**
* Returns the associated charset for the font name. * Returns the associated charset for the font name.
* *
* @param string $name Font name * @param string $fontName Font name
* *
* @return int Character set code * @return int Character set code
*/ */
public static function getCharsetFromFontName($name) public static function getCharsetFromFontName($fontName)
{ {
switch ($name) { switch ($fontName) {
// Add more cases. Check FONT records in real Excel files. // Add more cases. Check FONT records in real Excel files.
case 'EucrosiaUPC': case 'EucrosiaUPC':
return self::CHARSET_ANSI_THAI; return self::CHARSET_ANSI_THAI;
@ -546,28 +545,28 @@ class Font
* Get the effective column width for columns without a column dimension or column with width -1 * Get the effective column width for columns without a column dimension or column with width -1
* For example, for Calibri 11 this is 9.140625 (64 px). * For example, for Calibri 11 this is 9.140625 (64 px).
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font * @param FontStyle $font The workbooks default font
* @param bool $pPixels true = return column width in pixels, false = return in OOXML units * @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units
* *
* @return mixed Column width * @return mixed Column width
*/ */
public static function getDefaultColumnWidthByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font, $pPixels = false) public static function getDefaultColumnWidthByFont(FontStyle $font, $returnAsPixels = false)
{ {
if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) { if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) {
// Exact width can be determined // Exact width can be determined
$columnWidth = $pPixels ? $columnWidth = $returnAsPixels ?
self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px'] self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px']
: self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width']; : self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width'];
} else { } else {
// We don't have data for this particular font and size, use approximation by // We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11 // extrapolating from Calibri 11
$columnWidth = $pPixels ? $columnWidth = $returnAsPixels ?
self::$defaultColumnWidths['Calibri'][11]['px'] self::$defaultColumnWidths['Calibri'][11]['px']
: self::$defaultColumnWidths['Calibri'][11]['width']; : self::$defaultColumnWidths['Calibri'][11]['width'];
$columnWidth = $columnWidth * $font->getSize() / 11; $columnWidth = $columnWidth * $font->getSize() / 11;
// Round pixels to closest integer // Round pixels to closest integer
if ($pPixels) { if ($returnAsPixels) {
$columnWidth = (int) round($columnWidth); $columnWidth = (int) round($columnWidth);
} }
} }
@ -579,11 +578,11 @@ class Font
* Get the effective row height for rows without a row dimension or rows with height -1 * Get the effective row height for rows without a row dimension or rows with height -1
* For example, for Calibri 11 this is 15 points. * For example, for Calibri 11 this is 15 points.
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font * @param FontStyle $font The workbooks default font
* *
* @return float Row height in points * @return float Row height in points
*/ */
public static function getDefaultRowHeightByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font) public static function getDefaultRowHeightByFont(FontStyle $font)
{ {
switch ($font->getName()) { switch ($font->getName()) {
case 'Arial': case 'Arial':

View File

@ -110,15 +110,15 @@ class OLE
* *
* @acces public * @acces public
* *
* @param string $file * @param string $filename
* *
* @return bool true on success, PEAR_Error on failure * @return bool true on success, PEAR_Error on failure
*/ */
public function read($file) public function read($filename)
{ {
$fh = fopen($file, 'rb'); $fh = fopen($filename, 'rb');
if (!$fh) { if (!$fh) {
throw new ReaderException("Can't open file $file"); throw new ReaderException("Can't open file $filename");
} }
$this->_file_handle = $fh; $this->_file_handle = $fh;
@ -245,13 +245,13 @@ class OLE
/** /**
* Reads a signed char. * Reads a signed char.
* *
* @param resource $fh file handle * @param resource $fileHandle file handle
* *
* @return int * @return int
*/ */
private static function readInt1($fh) private static function readInt1($fileHandle)
{ {
[, $tmp] = unpack('c', fread($fh, 1)); [, $tmp] = unpack('c', fread($fileHandle, 1));
return $tmp; return $tmp;
} }
@ -259,13 +259,13 @@ class OLE
/** /**
* Reads an unsigned short (2 octets). * Reads an unsigned short (2 octets).
* *
* @param resource $fh file handle * @param resource $fileHandle file handle
* *
* @return int * @return int
*/ */
private static function readInt2($fh) private static function readInt2($fileHandle)
{ {
[, $tmp] = unpack('v', fread($fh, 2)); [, $tmp] = unpack('v', fread($fileHandle, 2));
return $tmp; return $tmp;
} }
@ -273,13 +273,13 @@ class OLE
/** /**
* Reads an unsigned long (4 octets). * Reads an unsigned long (4 octets).
* *
* @param resource $fh file handle * @param resource $fileHandle file handle
* *
* @return int * @return int
*/ */
private static function readInt4($fh) private static function readInt4($fileHandle)
{ {
[, $tmp] = unpack('V', fread($fh, 4)); [, $tmp] = unpack('V', fread($fileHandle, 4));
return $tmp; return $tmp;
} }

View File

@ -93,22 +93,22 @@ class OLERead
/** /**
* Read the file. * Read the file.
*/ */
public function read(string $pFilename): void public function read(string $filename): void
{ {
File::assertFile($pFilename); File::assertFile($filename);
// Get the file identifier // Get the file identifier
// Don't bother reading the whole file until we know it's a valid OLE file // Don't bother reading the whole file until we know it's a valid OLE file
$this->data = file_get_contents($pFilename, false, null, 0, 8); $this->data = file_get_contents($filename, false, null, 0, 8);
// Check OLE identifier // Check OLE identifier
$identifierOle = pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1); $identifierOle = pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1);
if ($this->data != $identifierOle) { if ($this->data != $identifierOle) {
throw new ReaderException('The filename ' . $pFilename . ' is not recognised as an OLE file'); throw new ReaderException('The filename ' . $filename . ' is not recognised as an OLE file');
} }
// Get the file data // Get the file data
$this->data = file_get_contents($pFilename); $this->data = file_get_contents($filename);
// Total number of sectors used for the SAT // Total number of sectors used for the SAT
$this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
@ -235,13 +235,12 @@ class OLERead
/** /**
* Read a standard stream (by joining sectors using information from SAT). * Read a standard stream (by joining sectors using information from SAT).
* *
* @param int $bl Sector ID where the stream starts * @param int $block Sector ID where the stream starts
* *
* @return string Data for standard stream * @return string Data for standard stream
*/ */
private function readData($bl) private function readData($block)
{ {
$block = $bl;
$data = ''; $data = '';
while ($block != -2) { while ($block != -2) {

View File

@ -53,13 +53,13 @@ class PasswordHasher
* Scrutinizer will squawk at the use of bitwise operations here, * Scrutinizer will squawk at the use of bitwise operations here,
* but it should ultimately pass. * but it should ultimately pass.
* *
* @param string $pPassword Password to hash * @param string $password Password to hash
*/ */
private static function defaultHashPassword(string $pPassword): string private static function defaultHashPassword(string $password): string
{ {
$verifier = 0; $verifier = 0;
$pwlen = strlen($pPassword); $pwlen = strlen($password);
$passwordArray = pack('c', $pwlen) . $pPassword; $passwordArray = pack('c', $pwlen) . $password;
for ($i = $pwlen; $i >= 0; --$i) { for ($i = $pwlen; $i >= 0; --$i) {
$intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1; $intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1;
$intermediate2 = 2 * $verifier; $intermediate2 = 2 * $verifier;

View File

@ -294,15 +294,15 @@ class StringHelper
* So you could end up with something like _x0008_ in a string (either in a cell value (<v>) * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
* element or in the shared string <t> element. * element or in the shared string <t> element.
* *
* @param string $value Value to unescape * @param string $textValue Value to unescape
* *
* @return string * @return string
*/ */
public static function controlCharacterOOXML2PHP($value) public static function controlCharacterOOXML2PHP($textValue)
{ {
self::buildCharacterSets(); self::buildCharacterSets();
return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $value); return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $textValue);
} }
/** /**
@ -316,64 +316,64 @@ class StringHelper
* So you could end up with something like _x0008_ in a string (either in a cell value (<v>) * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
* element or in the shared string <t> element. * element or in the shared string <t> element.
* *
* @param string $value Value to escape * @param string $textValue Value to escape
* *
* @return string * @return string
*/ */
public static function controlCharacterPHP2OOXML($value) public static function controlCharacterPHP2OOXML($textValue)
{ {
self::buildCharacterSets(); self::buildCharacterSets();
return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $value); return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $textValue);
} }
/** /**
* Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters. * Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters.
* *
* @param string $value * @param string $textValue
* *
* @return string * @return string
*/ */
public static function sanitizeUTF8($value) public static function sanitizeUTF8($textValue)
{ {
if (self::getIsIconvEnabled()) { if (self::getIsIconvEnabled()) {
$value = @iconv('UTF-8', 'UTF-8', $value); $textValue = @iconv('UTF-8', 'UTF-8', $textValue);
return $value; return $textValue;
} }
$value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); $textValue = mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
return $value; return $textValue;
} }
/** /**
* Check if a string contains UTF8 data. * Check if a string contains UTF8 data.
* *
* @param string $value * @param string $textValue
* *
* @return bool * @return bool
*/ */
public static function isUTF8($value) public static function isUTF8($textValue)
{ {
return $value === '' || preg_match('/^./su', $value) === 1; return $textValue === '' || preg_match('/^./su', $textValue) === 1;
} }
/** /**
* Formats a numeric value as a string for output in various output writers forcing * Formats a numeric value as a string for output in various output writers forcing
* point as decimal separator in case locale is other than English. * point as decimal separator in case locale is other than English.
* *
* @param mixed $value * @param mixed $numericValue
* *
* @return string * @return string
*/ */
public static function formatNumber($value) public static function formatNumber($numericValue)
{ {
if (is_float($value)) { if (is_float($numericValue)) {
return str_replace(',', '.', $value); return str_replace(',', '.', $numericValue);
} }
return (string) $value; return (string) $numericValue;
} }
/** /**
@ -383,25 +383,25 @@ class StringHelper
* although this will give wrong results for non-ASCII strings * although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
* *
* @param string $value UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* @param mixed[] $arrcRuns Details of rich text runs in $value * @param mixed[] $arrcRuns Details of rich text runs in $value
* *
* @return string * @return string
*/ */
public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = []) public static function UTF8toBIFF8UnicodeShort($textValue, $arrcRuns = [])
{ {
// character count // character count
$ln = self::countCharacters($value, 'UTF-8'); $ln = self::countCharacters($textValue, 'UTF-8');
// option flags // option flags
if (empty($arrcRuns)) { if (empty($arrcRuns)) {
$data = pack('CC', $ln, 0x0001); $data = pack('CC', $ln, 0x0001);
// characters // characters
$data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
} else { } else {
$data = pack('vC', $ln, 0x09); $data = pack('vC', $ln, 0x09);
$data .= pack('v', count($arrcRuns)); $data .= pack('v', count($arrcRuns));
// characters // characters
$data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
foreach ($arrcRuns as $cRun) { foreach ($arrcRuns as $cRun) {
$data .= pack('v', $cRun['strlen']); $data .= pack('v', $cRun['strlen']);
$data .= pack('v', $cRun['fontidx']); $data .= pack('v', $cRun['fontidx']);
@ -418,17 +418,17 @@ class StringHelper
* although this will give wrong results for non-ASCII strings * although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
* *
* @param string $value UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function UTF8toBIFF8UnicodeLong($value) public static function UTF8toBIFF8UnicodeLong($textValue)
{ {
// character count // character count
$ln = self::countCharacters($value, 'UTF-8'); $ln = self::countCharacters($textValue, 'UTF-8');
// characters // characters
$chars = self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
return pack('vC', $ln, 0x0001) . $chars; return pack('vC', $ln, 0x0001) . $chars;
} }
@ -436,91 +436,91 @@ class StringHelper
/** /**
* Convert string from one encoding to another. * Convert string from one encoding to another.
* *
* @param string $value * @param string $textValue
* @param string $to Encoding to convert to, e.g. 'UTF-8' * @param string $to Encoding to convert to, e.g. 'UTF-8'
* @param string $from Encoding to convert from, e.g. 'UTF-16LE' * @param string $from Encoding to convert from, e.g. 'UTF-16LE'
* *
* @return string * @return string
*/ */
public static function convertEncoding($value, $to, $from) public static function convertEncoding($textValue, $to, $from)
{ {
if (self::getIsIconvEnabled()) { if (self::getIsIconvEnabled()) {
$result = iconv($from, $to . self::$iconvOptions, $value); $result = iconv($from, $to . self::$iconvOptions, $textValue);
if (false !== $result) { if (false !== $result) {
return $result; return $result;
} }
} }
return mb_convert_encoding($value, $to, $from); return mb_convert_encoding($textValue, $to, $from);
} }
/** /**
* Get character count. * Get character count.
* *
* @param string $value * @param string $textValue
* @param string $enc Encoding * @param string $encoding Encoding
* *
* @return int Character count * @return int Character count
*/ */
public static function countCharacters($value, $enc = 'UTF-8') public static function countCharacters($textValue, $encoding = 'UTF-8')
{ {
return mb_strlen($value ?? '', $enc); return mb_strlen($textValue ?? '', $encoding);
} }
/** /**
* Get a substring of a UTF-8 encoded string. * Get a substring of a UTF-8 encoded string.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* @param int $pStart Start offset * @param int $offset Start offset
* @param int $pLength Maximum number of characters in substring * @param int $length Maximum number of characters in substring
* *
* @return string * @return string
*/ */
public static function substring($pValue, $pStart, $pLength = 0) public static function substring($textValue, $offset, $length = 0)
{ {
return mb_substr($pValue, $pStart, $pLength, 'UTF-8'); return mb_substr($textValue, $offset, $length, 'UTF-8');
} }
/** /**
* Convert a UTF-8 encoded string to upper case. * Convert a UTF-8 encoded string to upper case.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strToUpper($pValue) public static function strToUpper($textValue)
{ {
return mb_convert_case($pValue, MB_CASE_UPPER, 'UTF-8'); return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8');
} }
/** /**
* Convert a UTF-8 encoded string to lower case. * Convert a UTF-8 encoded string to lower case.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strToLower($pValue) public static function strToLower($textValue)
{ {
return mb_convert_case($pValue ?? '', MB_CASE_LOWER, 'UTF-8'); return mb_convert_case($textValue ?? '', MB_CASE_LOWER, 'UTF-8');
} }
/** /**
* Convert a UTF-8 encoded string to title/proper case * Convert a UTF-8 encoded string to title/proper case
* (uppercase every first character in each word, lower case all other characters). * (uppercase every first character in each word, lower case all other characters).
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strToTitle($pValue) public static function strToTitle($textValue)
{ {
return mb_convert_case($pValue, MB_CASE_TITLE, 'UTF-8'); return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8');
} }
public static function mbIsUpper($char) public static function mbIsUpper($character)
{ {
return mb_strtolower($char, 'UTF-8') != $char; return mb_strtolower($character, 'UTF-8') != $character;
} }
public static function mbStrSplit($string) public static function mbStrSplit($string)
@ -534,13 +534,13 @@ class StringHelper
* Reverse the case of a string, so that all uppercase characters become lowercase * Reverse the case of a string, so that all uppercase characters become lowercase
* and all lowercase characters become uppercase. * and all lowercase characters become uppercase.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strCaseReverse($pValue) public static function strCaseReverse($textValue)
{ {
$characters = self::mbStrSplit($pValue); $characters = self::mbStrSplit($textValue);
foreach ($characters as &$character) { foreach ($characters as &$character) {
if (self::mbIsUpper($character)) { if (self::mbIsUpper($character)) {
$character = mb_strtolower($character, 'UTF-8'); $character = mb_strtolower($character, 'UTF-8');
@ -601,11 +601,11 @@ class StringHelper
* Set the decimal separator. Only used by NumberFormat::toFormattedString() * Set the decimal separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
* *
* @param string $pValue Character for decimal separator * @param string $separator Character for decimal separator
*/ */
public static function setDecimalSeparator($pValue): void public static function setDecimalSeparator($separator): void
{ {
self::$decimalSeparator = $pValue; self::$decimalSeparator = $separator;
} }
/** /**
@ -634,11 +634,11 @@ class StringHelper
* Set the thousands separator. Only used by NumberFormat::toFormattedString() * Set the thousands separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
* *
* @param string $pValue Character for thousands separator * @param string $separator Character for thousands separator
*/ */
public static function setThousandsSeparator($pValue): void public static function setThousandsSeparator($separator): void
{ {
self::$thousandsSeparator = $pValue; self::$thousandsSeparator = $separator;
} }
/** /**
@ -672,51 +672,51 @@ class StringHelper
* Set the currency code. Only used by NumberFormat::toFormattedString() * Set the currency code. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
* *
* @param string $pValue Character for currency code * @param string $currencyCode Character for currency code
*/ */
public static function setCurrencyCode($pValue): void public static function setCurrencyCode($currencyCode): void
{ {
self::$currencyCode = $pValue; self::$currencyCode = $currencyCode;
} }
/** /**
* Convert SYLK encoded string to UTF-8. * Convert SYLK encoded string to UTF-8.
* *
* @param string $pValue * @param string $textValue
* *
* @return string UTF-8 encoded string * @return string UTF-8 encoded string
*/ */
public static function SYLKtoUTF8($pValue) public static function SYLKtoUTF8($textValue)
{ {
self::buildCharacterSets(); self::buildCharacterSets();
// If there is no escape character in the string there is nothing to do // If there is no escape character in the string there is nothing to do
if (strpos($pValue, '') === false) { if (strpos($textValue, '') === false) {
return $pValue; return $textValue;
} }
foreach (self::$SYLKCharacters as $k => $v) { foreach (self::$SYLKCharacters as $k => $v) {
$pValue = str_replace($k, $v, $pValue); $textValue = str_replace($k, $v, $textValue);
} }
return $pValue; return $textValue;
} }
/** /**
* Retrieve any leading numeric part of a string, or return the full string if no leading numeric * Retrieve any leading numeric part of a string, or return the full string if no leading numeric
* (handles basic integer or float, but not exponent or non decimal). * (handles basic integer or float, but not exponent or non decimal).
* *
* @param string $value * @param string $textValue
* *
* @return mixed string or only the leading numeric part of the string * @return mixed string or only the leading numeric part of the string
*/ */
public static function testStringAsNumeric($value) public static function testStringAsNumeric($textValue)
{ {
if (is_numeric($value)) { if (is_numeric($textValue)) {
return $value; return $textValue;
} }
$v = (float) $value; $v = (float) $textValue;
return (is_numeric(substr($value, 0, strlen($v)))) ? $v : $value; return (is_numeric(substr($textValue, 0, strlen($v)))) ? $v : $textValue;
} }
} }

View File

@ -17,26 +17,26 @@ class TimeZone
/** /**
* Validate a Timezone name. * Validate a Timezone name.
* *
* @param string $timezone Time zone (e.g. 'Europe/London') * @param string $timezoneName Time zone (e.g. 'Europe/London')
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
private static function validateTimeZone($timezone) private static function validateTimeZone($timezoneName)
{ {
return in_array($timezone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC)); return in_array($timezoneName, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC));
} }
/** /**
* Set the Default Timezone used for date/time conversions. * Set the Default Timezone used for date/time conversions.
* *
* @param string $timezone Time zone (e.g. 'Europe/London') * @param string $timezoneName Time zone (e.g. 'Europe/London')
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function setTimeZone($timezone) public static function setTimeZone($timezoneName)
{ {
if (self::validateTimezone($timezone)) { if (self::validateTimezone($timezoneName)) {
self::$timezone = $timezone; self::$timezone = $timezoneName;
return true; return true;
} }
@ -58,19 +58,19 @@ class TimeZone
* Return the Timezone offset used for date/time conversions to/from UST * Return the Timezone offset used for date/time conversions to/from UST
* This requires both the timezone and the calculated date/time to allow for local DST. * 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 ?string $timezoneName The timezone for finding the adjustment to UST
* @param float|int $timestamp PHP date/time value * @param float|int $timestamp PHP date/time value
* *
* @return int Number of seconds for timezone adjustment * @return int Number of seconds for timezone adjustment
*/ */
public static function getTimeZoneAdjustment($timezone, $timestamp) public static function getTimeZoneAdjustment($timezoneName, $timestamp)
{ {
$timezone = $timezone ?? self::$timezone; $timezoneName = $timezoneName ?? self::$timezone;
$dtobj = Date::dateTimeFromTimestamp("$timestamp"); $dtobj = Date::dateTimeFromTimestamp("$timestamp");
if (!self::validateTimezone($timezone)) { if (!self::validateTimezone($timezoneName)) {
throw new PhpSpreadsheetException("Invalid timezone $timezone"); throw new PhpSpreadsheetException("Invalid timezone $timezoneName");
} }
$dtobj->setTimeZone(new DateTimeZone($timezone)); $dtobj->setTimeZone(new DateTimeZone($timezoneName));
return $dtobj->getOffset(); return $dtobj->getOffset();
} }

View File

@ -2,8 +2,6 @@
namespace PhpOffice\PhpSpreadsheet\Shared; namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Settings;
class XMLWriter extends \XMLWriter class XMLWriter extends \XMLWriter
{ {
public static $debugEnabled = false; public static $debugEnabled = false;
@ -22,20 +20,20 @@ class XMLWriter extends \XMLWriter
/** /**
* Create a new XMLWriter instance. * Create a new XMLWriter instance.
* *
* @param int $pTemporaryStorage Temporary storage location * @param int $temporaryStorage Temporary storage location
* @param string $pTemporaryStorageFolder Temporary storage folder * @param string $temporaryStorageFolder Temporary storage folder
*/ */
public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTemporaryStorageFolder = null) public function __construct($temporaryStorage = self::STORAGE_MEMORY, $temporaryStorageFolder = null)
{ {
// Open temporary storage // Open temporary storage
if ($pTemporaryStorage == self::STORAGE_MEMORY) { if ($temporaryStorage == self::STORAGE_MEMORY) {
$this->openMemory(); $this->openMemory();
} else { } else {
// Create temporary filename // Create temporary filename
if ($pTemporaryStorageFolder === null) { if ($temporaryStorageFolder === null) {
$pTemporaryStorageFolder = File::sysGetTempDir(); $temporaryStorageFolder = File::sysGetTempDir();
} }
$this->tempFileName = @tempnam($pTemporaryStorageFolder, 'xml'); $this->tempFileName = @tempnam($temporaryStorageFolder, 'xml');
// Open storage // Open storage
if ($this->openUri($this->tempFileName) === false) { if ($this->openUri($this->tempFileName) === false) {
@ -79,16 +77,16 @@ class XMLWriter extends \XMLWriter
/** /**
* Wrapper method for writeRaw. * Wrapper method for writeRaw.
* *
* @param string|string[] $text * @param null|string|string[] $rawTextData
* *
* @return bool * @return bool
*/ */
public function writeRawData($text) public function writeRawData($rawTextData)
{ {
if (is_array($text)) { if (is_array($rawTextData)) {
$text = implode("\n", $text); $rawTextData = implode("\n", $rawTextData);
} }
return $this->writeRaw(htmlspecialchars($text ?? '', Settings::htmlEntityFlags())); return $this->writeRaw(htmlspecialchars($rawTextData ?? ''));
} }
} }

View File

@ -13,17 +13,17 @@ class Xls
* x is the width in intrinsic Excel units (measuring width in number of normal characters) * x is the width in intrinsic Excel units (measuring width in number of normal characters)
* This holds for Arial 10. * This holds for Arial 10.
* *
* @param Worksheet $sheet The sheet * @param Worksheet $worksheet The sheet
* @param string $col The column * @param string $col The column
* *
* @return int The width in pixels * @return int The width in pixels
*/ */
public static function sizeCol($sheet, $col = 'A') public static function sizeCol(Worksheet $worksheet, $col = 'A')
{ {
// default font of the workbook // default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont(); $font = $worksheet->getParent()->getDefaultStyle()->getFont();
$columnDimensions = $sheet->getColumnDimensions(); $columnDimensions = $worksheet->getColumnDimensions();
// first find the true column width in pixels (uncollapsed and unhidden) // first find the true column width in pixels (uncollapsed and unhidden)
if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) { if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) {
@ -31,9 +31,9 @@ class Xls
$columnDimension = $columnDimensions[$col]; $columnDimension = $columnDimensions[$col];
$width = $columnDimension->getWidth(); $width = $columnDimension->getWidth();
$pixelWidth = Drawing::cellDimensionToPixels($width, $font); $pixelWidth = Drawing::cellDimensionToPixels($width, $font);
} elseif ($sheet->getDefaultColumnDimension()->getWidth() != -1) { } elseif ($worksheet->getDefaultColumnDimension()->getWidth() != -1) {
// then we have default column dimension with explicit width // then we have default column dimension with explicit width
$defaultColumnDimension = $sheet->getDefaultColumnDimension(); $defaultColumnDimension = $worksheet->getDefaultColumnDimension();
$width = $defaultColumnDimension->getWidth(); $width = $defaultColumnDimension->getWidth();
$pixelWidth = Drawing::cellDimensionToPixels($width, $font); $pixelWidth = Drawing::cellDimensionToPixels($width, $font);
} else { } else {
@ -56,17 +56,17 @@ class Xls
* the relationship is: y = 4/3x. If the height hasn't been set by the user we * the relationship is: y = 4/3x. If the height hasn't been set by the user we
* use the default value. If the row is hidden we use a value of zero. * use the default value. If the row is hidden we use a value of zero.
* *
* @param Worksheet $sheet The sheet * @param Worksheet $worksheet The sheet
* @param int $row The row index (1-based) * @param int $row The row index (1-based)
* *
* @return int The width in pixels * @return int The width in pixels
*/ */
public static function sizeRow($sheet, $row = 1) public static function sizeRow(Worksheet $worksheet, $row = 1)
{ {
// default font of the workbook // default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont(); $font = $worksheet->getParent()->getDefaultStyle()->getFont();
$rowDimensions = $sheet->getRowDimensions(); $rowDimensions = $worksheet->getRowDimensions();
// first find the true row height in pixels (uncollapsed and unhidden) // first find the true row height in pixels (uncollapsed and unhidden)
if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) { if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) {
@ -74,9 +74,9 @@ class Xls
$rowDimension = $rowDimensions[$row]; $rowDimension = $rowDimensions[$row];
$rowHeight = $rowDimension->getRowHeight(); $rowHeight = $rowDimension->getRowHeight();
$pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10
} elseif ($sheet->getDefaultRowDimension()->getRowHeight() != -1) { } elseif ($worksheet->getDefaultRowDimension()->getRowHeight() != -1) {
// then we have a default row dimension with explicit height // then we have a default row dimension with explicit height
$defaultRowDimension = $sheet->getDefaultRowDimension(); $defaultRowDimension = $worksheet->getDefaultRowDimension();
$pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS); $pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS);
} else { } else {
// we don't even have any default row dimension. Height depends on default font // we don't even have any default row dimension. Height depends on default font
@ -105,7 +105,7 @@ class Xls
* *
* @return int Horizontal measured in pixels * @return int Horizontal measured in pixels
*/ */
public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0) public static function getDistanceX(Worksheet $worksheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0)
{ {
$distanceX = 0; $distanceX = 0;
@ -113,14 +113,14 @@ class Xls
$startColumnIndex = Coordinate::columnIndexFromString($startColumn); $startColumnIndex = Coordinate::columnIndexFromString($startColumn);
$endColumnIndex = Coordinate::columnIndexFromString($endColumn); $endColumnIndex = Coordinate::columnIndexFromString($endColumn);
for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) { for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) {
$distanceX += self::sizeCol($sheet, Coordinate::stringFromColumnIndex($i)); $distanceX += self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($i));
} }
// correct for offsetX in startcell // correct for offsetX in startcell
$distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024); $distanceX -= (int) floor(self::sizeCol($worksheet, $startColumn) * $startOffsetX / 1024);
// correct for offsetX in endcell // correct for offsetX in endcell
$distanceX -= (int) floor(self::sizeCol($sheet, $endColumn) * (1 - $endOffsetX / 1024)); $distanceX -= (int) floor(self::sizeCol($worksheet, $endColumn) * (1 - $endOffsetX / 1024));
return $distanceX; return $distanceX;
} }
@ -136,20 +136,20 @@ class Xls
* *
* @return int Vertical distance measured in pixels * @return int Vertical distance measured in pixels
*/ */
public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0) public static function getDistanceY(Worksheet $worksheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0)
{ {
$distanceY = 0; $distanceY = 0;
// add the widths of the spanning rows // add the widths of the spanning rows
for ($row = $startRow; $row <= $endRow; ++$row) { for ($row = $startRow; $row <= $endRow; ++$row) {
$distanceY += self::sizeRow($sheet, $row); $distanceY += self::sizeRow($worksheet, $row);
} }
// correct for offsetX in startcell // correct for offsetX in startcell
$distanceY -= (int) floor(self::sizeRow($sheet, $startRow) * $startOffsetY / 256); $distanceY -= (int) floor(self::sizeRow($worksheet, $startRow) * $startOffsetY / 256);
// correct for offsetX in endcell // correct for offsetX in endcell
$distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256)); $distanceY -= (int) floor(self::sizeRow($worksheet, $endRow) * (1 - $endOffsetY / 256));
return $distanceY; return $distanceY;
} }
@ -198,7 +198,6 @@ class Xls
* W is the width of the cell * W is the width of the cell
* H is the height of the cell * H is the height of the cell
* *
* @param Worksheet $sheet
* @param string $coordinates E.g. 'A1' * @param string $coordinates E.g. 'A1'
* @param int $offsetX Horizontal offset in pixels * @param int $offsetX Horizontal offset in pixels
* @param int $offsetY Vertical offset in pixels * @param int $offsetY Vertical offset in pixels
@ -207,7 +206,7 @@ class Xls
* *
* @return null|array * @return null|array
*/ */
public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height) public static function oneAnchor2twoAnchor(Worksheet $worksheet, $coordinates, $offsetX, $offsetY, $width, $height)
{ {
[$col_start, $row] = Coordinate::indexesFromString($coordinates); [$col_start, $row] = Coordinate::indexesFromString($coordinates);
$row_start = $row - 1; $row_start = $row - 1;
@ -220,10 +219,10 @@ class Xls
$row_end = $row_start; // Row containing bottom right corner of object $row_end = $row_start; // Row containing bottom right corner of object
// Zero the specified offset if greater than the cell dimensions // Zero the specified offset if greater than the cell dimensions
if ($x1 >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start))) { if ($x1 >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start))) {
$x1 = 0; $x1 = 0;
} }
if ($y1 >= self::sizeRow($sheet, $row_start + 1)) { if ($y1 >= self::sizeRow($worksheet, $row_start + 1)) {
$y1 = 0; $y1 = 0;
} }
@ -231,37 +230,37 @@ class Xls
$height = $height + $y1 - 1; $height = $height + $y1 - 1;
// Subtract the underlying cell widths to find the end cell of the image // Subtract the underlying cell widths to find the end cell of the image
while ($width >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end))) { while ($width >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end))) {
$width -= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)); $width -= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end));
++$col_end; ++$col_end;
} }
// Subtract the underlying cell heights to find the end cell of the image // Subtract the underlying cell heights to find the end cell of the image
while ($height >= self::sizeRow($sheet, $row_end + 1)) { while ($height >= self::sizeRow($worksheet, $row_end + 1)) {
$height -= self::sizeRow($sheet, $row_end + 1); $height -= self::sizeRow($worksheet, $row_end + 1);
++$row_end; ++$row_end;
} }
// Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
// with zero height or width. // with zero height or width.
if (self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start)) == 0) { if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) == 0) {
return null; return null;
} }
if (self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0) {
return null; return null;
} }
if (self::sizeRow($sheet, $row_start + 1) == 0) { if (self::sizeRow($worksheet, $row_start + 1) == 0) {
return null; return null;
} }
if (self::sizeRow($sheet, $row_end + 1) == 0) { if (self::sizeRow($worksheet, $row_end + 1) == 0) {
return null; return null;
} }
// Convert the pixel values to the percentage value expected by Excel // Convert the pixel values to the percentage value expected by Excel
$x1 = $x1 / self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; $x1 = $x1 / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) * 1024;
$y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256; $y1 = $y1 / self::sizeRow($worksheet, $row_start + 1) * 256;
$x2 = ($width + 1) / self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object $x2 = ($width + 1) / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
$y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object $y2 = ($height + 1) / self::sizeRow($worksheet, $row_end + 1) * 256; // Distance to bottom of object
$startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1); $startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1);
$endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1); $endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1);

View File

@ -439,27 +439,27 @@ class Spreadsheet
/** /**
* Check if a sheet with a specified code name already exists. * Check if a sheet with a specified code name already exists.
* *
* @param string $pSheetCodeName Name of the worksheet to check * @param string $codeName Name of the worksheet to check
* *
* @return bool * @return bool
*/ */
public function sheetCodeNameExists($pSheetCodeName) public function sheetCodeNameExists($codeName)
{ {
return $this->getSheetByCodeName($pSheetCodeName) !== null; return $this->getSheetByCodeName($codeName) !== null;
} }
/** /**
* Get sheet by code name. Warning : sheet don't have always a code name ! * Get sheet by code name. Warning : sheet don't have always a code name !
* *
* @param string $pName Sheet name * @param string $codeName Sheet name
* *
* @return null|Worksheet * @return null|Worksheet
*/ */
public function getSheetByCodeName($pName) public function getSheetByCodeName($codeName)
{ {
$worksheetCount = count($this->workSheetCollection); $worksheetCount = count($this->workSheetCollection);
for ($i = 0; $i < $worksheetCount; ++$i) { for ($i = 0; $i < $worksheetCount; ++$i) {
if ($this->workSheetCollection[$i]->getCodeName() == $pName) { if ($this->workSheetCollection[$i]->getCodeName() == $codeName) {
return $this->workSheetCollection[$i]; return $this->workSheetCollection[$i];
} }
} }
@ -545,9 +545,9 @@ class Spreadsheet
/** /**
* Set properties. * Set properties.
*/ */
public function setProperties(Document\Properties $pValue): void public function setProperties(Document\Properties $documentProperties): void
{ {
$this->properties = $pValue; $this->properties = $documentProperties;
} }
/** /**
@ -563,9 +563,9 @@ class Spreadsheet
/** /**
* Set security. * Set security.
*/ */
public function setSecurity(Document\Security $pValue): void public function setSecurity(Document\Security $documentSecurity): void
{ {
$this->security = $pValue; $this->security = $documentSecurity;
} }
/** /**
@ -596,75 +596,76 @@ class Spreadsheet
/** /**
* Check if a sheet with a specified name already exists. * Check if a sheet with a specified name already exists.
* *
* @param string $pSheetName Name of the worksheet to check * @param string $worksheetName Name of the worksheet to check
* *
* @return bool * @return bool
*/ */
public function sheetNameExists($pSheetName) public function sheetNameExists($worksheetName)
{ {
return $this->getSheetByName($pSheetName) !== null; return $this->getSheetByName($worksheetName) !== null;
} }
/** /**
* Add sheet. * Add sheet.
* *
* @param null|int $iSheetIndex Index where sheet should go (0,1,..., or null for last) * @param Worksheet $worksheet The worskeet to add
* @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
* *
* @return Worksheet * @return Worksheet
*/ */
public function addSheet(Worksheet $pSheet, $iSheetIndex = null) public function addSheet(Worksheet $worksheet, $sheetIndex = null)
{ {
if ($this->sheetNameExists($pSheet->getTitle())) { if ($this->sheetNameExists($worksheet->getTitle())) {
throw new Exception( throw new Exception(
"Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first." "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first."
); );
} }
if ($iSheetIndex === null) { if ($sheetIndex === null) {
if ($this->activeSheetIndex < 0) { if ($this->activeSheetIndex < 0) {
$this->activeSheetIndex = 0; $this->activeSheetIndex = 0;
} }
$this->workSheetCollection[] = $pSheet; $this->workSheetCollection[] = $worksheet;
} else { } else {
// Insert the sheet at the requested index // Insert the sheet at the requested index
array_splice( array_splice(
$this->workSheetCollection, $this->workSheetCollection,
$iSheetIndex, $sheetIndex,
0, 0,
[$pSheet] [$worksheet]
); );
// Adjust active sheet index if necessary // Adjust active sheet index if necessary
if ($this->activeSheetIndex >= $iSheetIndex) { if ($this->activeSheetIndex >= $sheetIndex) {
++$this->activeSheetIndex; ++$this->activeSheetIndex;
} }
} }
if ($pSheet->getParent() === null) { if ($worksheet->getParent() === null) {
$pSheet->rebindParent($this); $worksheet->rebindParent($this);
} }
return $pSheet; return $worksheet;
} }
/** /**
* Remove sheet by index. * Remove sheet by index.
* *
* @param int $pIndex Active sheet index * @param int $sheetIndex Index position of the worksheet to remove
*/ */
public function removeSheetByIndex($pIndex): void public function removeSheetByIndex($sheetIndex): void
{ {
$numSheets = count($this->workSheetCollection); $numSheets = count($this->workSheetCollection);
if ($pIndex > $numSheets - 1) { if ($sheetIndex > $numSheets - 1) {
throw new Exception( throw new Exception(
"You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}."
); );
} }
array_splice($this->workSheetCollection, $pIndex, 1); array_splice($this->workSheetCollection, $sheetIndex, 1);
// Adjust active sheet index if necessary // Adjust active sheet index if necessary
if ( if (
($this->activeSheetIndex >= $pIndex) && ($this->activeSheetIndex >= $sheetIndex) &&
($this->activeSheetIndex > 0 || $numSheets <= 1) ($this->activeSheetIndex > 0 || $numSheets <= 1)
) { ) {
--$this->activeSheetIndex; --$this->activeSheetIndex;
@ -674,21 +675,21 @@ class Spreadsheet
/** /**
* Get sheet by index. * Get sheet by index.
* *
* @param int $pIndex Sheet index * @param int $sheetIndex Sheet index
* *
* @return Worksheet * @return Worksheet
*/ */
public function getSheet($pIndex) public function getSheet($sheetIndex)
{ {
if (!isset($this->workSheetCollection[$pIndex])) { if (!isset($this->workSheetCollection[$sheetIndex])) {
$numSheets = $this->getSheetCount(); $numSheets = $this->getSheetCount();
throw new Exception( throw new Exception(
"Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}." "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}."
); );
} }
return $this->workSheetCollection[$pIndex]; return $this->workSheetCollection[$sheetIndex];
} }
/** /**
@ -704,15 +705,15 @@ class Spreadsheet
/** /**
* Get sheet by name. * Get sheet by name.
* *
* @param string $pName Sheet name * @param string $worksheetName Sheet name
* *
* @return null|Worksheet * @return null|Worksheet
*/ */
public function getSheetByName($pName) public function getSheetByName($worksheetName)
{ {
$worksheetCount = count($this->workSheetCollection); $worksheetCount = count($this->workSheetCollection);
for ($i = 0; $i < $worksheetCount; ++$i) { for ($i = 0; $i < $worksheetCount; ++$i) {
if ($this->workSheetCollection[$i]->getTitle() === trim($pName, "'")) { if ($this->workSheetCollection[$i]->getTitle() === trim($worksheetName, "'")) {
return $this->workSheetCollection[$i]; return $this->workSheetCollection[$i];
} }
} }
@ -725,10 +726,10 @@ class Spreadsheet
* *
* @return int index * @return int index
*/ */
public function getIndex(Worksheet $pSheet) public function getIndex(Worksheet $worksheet)
{ {
foreach ($this->workSheetCollection as $key => $value) { foreach ($this->workSheetCollection as $key => $value) {
if ($value->getHashCode() === $pSheet->getHashCode()) { if ($value->getHashCode() === $worksheet->getHashCode()) {
return $key; return $key;
} }
} }
@ -739,27 +740,27 @@ class Spreadsheet
/** /**
* Set index for sheet by sheet name. * Set index for sheet by sheet name.
* *
* @param string $sheetName Sheet name to modify index for * @param string $worksheetName Sheet name to modify index for
* @param int $newIndex New index for the sheet * @param int $newIndexPosition New index for the sheet
* *
* @return int New sheet index * @return int New sheet index
*/ */
public function setIndexByName($sheetName, $newIndex) public function setIndexByName($worksheetName, $newIndexPosition)
{ {
$oldIndex = $this->getIndex($this->getSheetByName($sheetName)); $oldIndex = $this->getIndex($this->getSheetByName($worksheetName));
$pSheet = array_splice( $worksheet = array_splice(
$this->workSheetCollection, $this->workSheetCollection,
$oldIndex, $oldIndex,
1 1
); );
array_splice( array_splice(
$this->workSheetCollection, $this->workSheetCollection,
$newIndex, $newIndexPosition,
0, 0,
$pSheet $worksheet
); );
return $newIndex; return $newIndexPosition;
} }
/** /**
@ -785,20 +786,20 @@ class Spreadsheet
/** /**
* Set active sheet index. * Set active sheet index.
* *
* @param int $pIndex Active sheet index * @param int $worksheetIndex Active sheet index
* *
* @return Worksheet * @return Worksheet
*/ */
public function setActiveSheetIndex($pIndex) public function setActiveSheetIndex($worksheetIndex)
{ {
$numSheets = count($this->workSheetCollection); $numSheets = count($this->workSheetCollection);
if ($pIndex > $numSheets - 1) { if ($worksheetIndex > $numSheets - 1) {
throw new Exception( throw new Exception(
"You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}."
); );
} }
$this->activeSheetIndex = $pIndex; $this->activeSheetIndex = $worksheetIndex;
return $this->getActiveSheet(); return $this->getActiveSheet();
} }
@ -806,19 +807,19 @@ class Spreadsheet
/** /**
* Set active sheet index by name. * Set active sheet index by name.
* *
* @param string $pValue Sheet title * @param string $worksheetName Sheet title
* *
* @return Worksheet * @return Worksheet
*/ */
public function setActiveSheetIndexByName($pValue) public function setActiveSheetIndexByName($worksheetName)
{ {
if (($worksheet = $this->getSheetByName($pValue)) instanceof Worksheet) { if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {
$this->setActiveSheetIndex($this->getIndex($worksheet)); $this->setActiveSheetIndex($this->getIndex($worksheet));
return $worksheet; return $worksheet;
} }
throw new Exception('Workbook does not contain sheet:' . $pValue); throw new Exception('Workbook does not contain sheet:' . $worksheetName);
} }
/** /**
@ -840,35 +841,35 @@ class Spreadsheet
/** /**
* Add external sheet. * Add external sheet.
* *
* @param Worksheet $pSheet External sheet to add * @param Worksheet $worksheet External sheet to add
* @param null|int $iSheetIndex Index where sheet should go (0,1,..., or null for last) * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
* *
* @return Worksheet * @return Worksheet
*/ */
public function addExternalSheet(Worksheet $pSheet, $iSheetIndex = null) public function addExternalSheet(Worksheet $worksheet, $sheetIndex = null)
{ {
if ($this->sheetNameExists($pSheet->getTitle())) { if ($this->sheetNameExists($worksheet->getTitle())) {
throw new Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first."); throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first.");
} }
// count how many cellXfs there are in this workbook currently, we will need this below // count how many cellXfs there are in this workbook currently, we will need this below
$countCellXfs = count($this->cellXfCollection); $countCellXfs = count($this->cellXfCollection);
// copy all the shared cellXfs from the external workbook and append them to the current // copy all the shared cellXfs from the external workbook and append them to the current
foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) { foreach ($worksheet->getParent()->getCellXfCollection() as $cellXf) {
$this->addCellXf(clone $cellXf); $this->addCellXf(clone $cellXf);
} }
// move sheet to this workbook // move sheet to this workbook
$pSheet->rebindParent($this); $worksheet->rebindParent($this);
// update the cellXfs // update the cellXfs
foreach ($pSheet->getCoordinates(false) as $coordinate) { foreach ($worksheet->getCoordinates(false) as $coordinate) {
$cell = $pSheet->getCell($coordinate); $cell = $worksheet->getCell($coordinate);
$cell->setXfIndex($cell->getXfIndex() + $countCellXfs); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
} }
return $this->addSheet($pSheet, $iSheetIndex); return $this->addSheet($worksheet, $sheetIndex);
} }
/** /**
@ -948,9 +949,9 @@ class Spreadsheet
/** /**
* Get named range. * Get named range.
* *
* @param null|Worksheet $pSheet Scope. Use null for global scope * @param null|Worksheet $worksheet Scope. Use null for global scope
*/ */
public function getNamedRange(string $namedRange, ?Worksheet $pSheet = null): ?NamedRange public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange
{ {
$returnValue = null; $returnValue = null;
@ -959,7 +960,7 @@ class Spreadsheet
// first look for global named range // first look for global named range
$returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE); $returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE);
// then look for local named range (has priority over global named range if both names exist) // then look for local named range (has priority over global named range if both names exist)
$returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $pSheet) ?: $returnValue; $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue;
} }
return $returnValue instanceof NamedRange ? $returnValue : null; return $returnValue instanceof NamedRange ? $returnValue : null;
@ -968,9 +969,9 @@ class Spreadsheet
/** /**
* Get named formula. * Get named formula.
* *
* @param null|Worksheet $pSheet Scope. Use null for global scope * @param null|Worksheet $worksheet Scope. Use null for global scope
*/ */
public function getNamedFormula(string $namedFormula, ?Worksheet $pSheet = null): ?NamedFormula public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula
{ {
$returnValue = null; $returnValue = null;
@ -979,7 +980,7 @@ class Spreadsheet
// first look for global named formula // first look for global named formula
$returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA); $returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA);
// then look for local named formula (has priority over global named formula if both names exist) // then look for local named formula (has priority over global named formula if both names exist)
$returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $pSheet) ?: $returnValue; $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue;
} }
return $returnValue instanceof NamedFormula ? $returnValue : null; return $returnValue instanceof NamedFormula ? $returnValue : null;
@ -994,13 +995,13 @@ class Spreadsheet
return null; return null;
} }
private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $pSheet = null): ?DefinedName private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName
{ {
if ( if (
($pSheet !== null) && isset($this->definedNames[$pSheet->getTitle() . '!' . $name]) ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name])
&& $this->definedNames[$pSheet->getTitle() . '!' . $name]->isFormula() === $type && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type
) { ) {
return $this->definedNames[$pSheet->getTitle() . '!' . $name]; return $this->definedNames[$worksheet->getTitle() . '!' . $name];
} }
return null; return null;
@ -1009,9 +1010,9 @@ class Spreadsheet
/** /**
* Get named range. * Get named range.
* *
* @param null|Worksheet $pSheet Scope. Use null for global scope * @param null|Worksheet $worksheet Scope. Use null for global scope
*/ */
public function getDefinedName(string $definedName, ?Worksheet $pSheet = null): ?DefinedName public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName
{ {
$returnValue = null; $returnValue = null;
@ -1023,8 +1024,8 @@ class Spreadsheet
} }
// then look for local defined name (has priority over global defined name if both names exist) // then look for local defined name (has priority over global defined name if both names exist)
if (($pSheet !== null) && isset($this->definedNames[$pSheet->getTitle() . '!' . $definedName])) { if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
$returnValue = $this->definedNames[$pSheet->getTitle() . '!' . $definedName]; $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName];
} }
} }
@ -1034,53 +1035,53 @@ class Spreadsheet
/** /**
* Remove named range. * Remove named range.
* *
* @param null|Worksheet $pSheet scope: use null for global scope * @param null|Worksheet $worksheet scope: use null for global scope
* *
* @return $this * @return $this
*/ */
public function removeNamedRange(string $namedRange, ?Worksheet $pSheet = null): self public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self
{ {
if ($this->getNamedRange($namedRange, $pSheet) === null) { if ($this->getNamedRange($namedRange, $worksheet) === null) {
return $this; return $this;
} }
return $this->removeDefinedName($namedRange, $pSheet); return $this->removeDefinedName($namedRange, $worksheet);
} }
/** /**
* Remove named formula. * Remove named formula.
* *
* @param null|Worksheet $pSheet scope: use null for global scope * @param null|Worksheet $worksheet scope: use null for global scope
* *
* @return $this * @return $this
*/ */
public function removeNamedFormula(string $namedFormula, ?Worksheet $pSheet = null): self public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self
{ {
if ($this->getNamedFormula($namedFormula, $pSheet) === null) { if ($this->getNamedFormula($namedFormula, $worksheet) === null) {
return $this; return $this;
} }
return $this->removeDefinedName($namedFormula, $pSheet); return $this->removeDefinedName($namedFormula, $worksheet);
} }
/** /**
* Remove defined name. * Remove defined name.
* *
* @param null|Worksheet $pSheet scope: use null for global scope * @param null|Worksheet $worksheet scope: use null for global scope
* *
* @return $this * @return $this
*/ */
public function removeDefinedName(string $definedName, ?Worksheet $pSheet = null): self public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self
{ {
$definedName = StringHelper::strToUpper($definedName); $definedName = StringHelper::strToUpper($definedName);
if ($pSheet === null) { if ($worksheet === null) {
if (isset($this->definedNames[$definedName])) { if (isset($this->definedNames[$definedName])) {
unset($this->definedNames[$definedName]); unset($this->definedNames[$definedName]);
} }
} else { } else {
if (isset($this->definedNames[$pSheet->getTitle() . '!' . $definedName])) { if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
unset($this->definedNames[$pSheet->getTitle() . '!' . $definedName]); unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]);
} elseif (isset($this->definedNames[$definedName])) { } elseif (isset($this->definedNames[$definedName])) {
unset($this->definedNames[$definedName]); unset($this->definedNames[$definedName]);
} }
@ -1143,26 +1144,26 @@ class Spreadsheet
/** /**
* Get cellXf by index. * Get cellXf by index.
* *
* @param int $pIndex * @param int $cellStyleIndex
* *
* @return Style * @return Style
*/ */
public function getCellXfByIndex($pIndex) public function getCellXfByIndex($cellStyleIndex)
{ {
return $this->cellXfCollection[$pIndex]; return $this->cellXfCollection[$cellStyleIndex];
} }
/** /**
* Get cellXf by hash code. * Get cellXf by hash code.
* *
* @param string $pValue * @param string $hashcode
* *
* @return false|Style * @return false|Style
*/ */
public function getCellXfByHashCode($pValue) public function getCellXfByHashCode($hashcode)
{ {
foreach ($this->cellXfCollection as $cellXf) { foreach ($this->cellXfCollection as $cellXf) {
if ($cellXf->getHashCode() === $pValue) { if ($cellXf->getHashCode() === $hashcode) {
return $cellXf; return $cellXf;
} }
} }
@ -1173,13 +1174,13 @@ class Spreadsheet
/** /**
* Check if style exists in style collection. * Check if style exists in style collection.
* *
* @param Style $pCellStyle * @param Style $cellStyleIndex
* *
* @return bool * @return bool
*/ */
public function cellXfExists($pCellStyle) public function cellXfExists($cellStyleIndex)
{ {
return in_array($pCellStyle, $this->cellXfCollection, true); return in_array($cellStyleIndex, $this->cellXfCollection, true);
} }
/** /**
@ -1208,26 +1209,26 @@ class Spreadsheet
/** /**
* Remove cellXf by index. It is ensured that all cells get their xf index updated. * Remove cellXf by index. It is ensured that all cells get their xf index updated.
* *
* @param int $pIndex Index to cellXf * @param int $cellStyleIndex Index to cellXf
*/ */
public function removeCellXfByIndex($pIndex): void public function removeCellXfByIndex($cellStyleIndex): void
{ {
if ($pIndex > count($this->cellXfCollection) - 1) { if ($cellStyleIndex > count($this->cellXfCollection) - 1) {
throw new Exception('CellXf index is out of bounds.'); throw new Exception('CellXf index is out of bounds.');
} }
// first remove the cellXf // first remove the cellXf
array_splice($this->cellXfCollection, $pIndex, 1); array_splice($this->cellXfCollection, $cellStyleIndex, 1);
// then update cellXf indexes for cells // then update cellXf indexes for cells
foreach ($this->workSheetCollection as $worksheet) { foreach ($this->workSheetCollection as $worksheet) {
foreach ($worksheet->getCoordinates(false) as $coordinate) { foreach ($worksheet->getCoordinates(false) as $coordinate) {
$cell = $worksheet->getCell($coordinate); $cell = $worksheet->getCell($coordinate);
$xfIndex = $cell->getXfIndex(); $xfIndex = $cell->getXfIndex();
if ($xfIndex > $pIndex) { if ($xfIndex > $cellStyleIndex) {
// decrease xf index by 1 // decrease xf index by 1
$cell->setXfIndex($xfIndex - 1); $cell->setXfIndex($xfIndex - 1);
} elseif ($xfIndex == $pIndex) { } elseif ($xfIndex == $cellStyleIndex) {
// set to default xf index 0 // set to default xf index 0
$cell->setXfIndex(0); $cell->setXfIndex(0);
} }
@ -1258,26 +1259,26 @@ class Spreadsheet
/** /**
* Get cellStyleXf by index. * Get cellStyleXf by index.
* *
* @param int $pIndex Index to cellXf * @param int $cellStyleIndex Index to cellXf
* *
* @return Style * @return Style
*/ */
public function getCellStyleXfByIndex($pIndex) public function getCellStyleXfByIndex($cellStyleIndex)
{ {
return $this->cellStyleXfCollection[$pIndex]; return $this->cellStyleXfCollection[$cellStyleIndex];
} }
/** /**
* Get cellStyleXf by hash code. * Get cellStyleXf by hash code.
* *
* @param string $pValue * @param string $hashcode
* *
* @return false|Style * @return false|Style
*/ */
public function getCellStyleXfByHashCode($pValue) public function getCellStyleXfByHashCode($hashcode)
{ {
foreach ($this->cellStyleXfCollection as $cellStyleXf) { foreach ($this->cellStyleXfCollection as $cellStyleXf) {
if ($cellStyleXf->getHashCode() === $pValue) { if ($cellStyleXf->getHashCode() === $hashcode) {
return $cellStyleXf; return $cellStyleXf;
} }
} }
@ -1288,23 +1289,23 @@ class Spreadsheet
/** /**
* Add a cellStyleXf to the workbook. * Add a cellStyleXf to the workbook.
*/ */
public function addCellStyleXf(Style $pStyle): void public function addCellStyleXf(Style $style): void
{ {
$this->cellStyleXfCollection[] = $pStyle; $this->cellStyleXfCollection[] = $style;
$pStyle->setIndex(count($this->cellStyleXfCollection) - 1); $style->setIndex(count($this->cellStyleXfCollection) - 1);
} }
/** /**
* Remove cellStyleXf by index. * Remove cellStyleXf by index.
* *
* @param int $pIndex Index to cellXf * @param int $cellStyleIndex Index to cellXf
*/ */
public function removeCellStyleXfByIndex($pIndex): void public function removeCellStyleXfByIndex($cellStyleIndex): void
{ {
if ($pIndex > count($this->cellStyleXfCollection) - 1) { if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) {
throw new Exception('CellStyleXf index is out of bounds.'); throw new Exception('CellStyleXf index is out of bounds.');
} }
array_splice($this->cellStyleXfCollection, $pIndex, 1); array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1);
} }
/** /**

View File

@ -140,36 +140,36 @@ class Alignment extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells()) $this->getActiveSheet()->getStyle($this->getSelectedCells())
->applyFromArray($this->getStyleArray($pStyles)); ->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['horizontal'])) { if (isset($styleArray['horizontal'])) {
$this->setHorizontal($pStyles['horizontal']); $this->setHorizontal($styleArray['horizontal']);
} }
if (isset($pStyles['vertical'])) { if (isset($styleArray['vertical'])) {
$this->setVertical($pStyles['vertical']); $this->setVertical($styleArray['vertical']);
} }
if (isset($pStyles['textRotation'])) { if (isset($styleArray['textRotation'])) {
$this->setTextRotation($pStyles['textRotation']); $this->setTextRotation($styleArray['textRotation']);
} }
if (isset($pStyles['wrapText'])) { if (isset($styleArray['wrapText'])) {
$this->setWrapText($pStyles['wrapText']); $this->setWrapText($styleArray['wrapText']);
} }
if (isset($pStyles['shrinkToFit'])) { if (isset($styleArray['shrinkToFit'])) {
$this->setShrinkToFit($pStyles['shrinkToFit']); $this->setShrinkToFit($styleArray['shrinkToFit']);
} }
if (isset($pStyles['indent'])) { if (isset($styleArray['indent'])) {
$this->setIndent($pStyles['indent']); $this->setIndent($styleArray['indent']);
} }
if (isset($pStyles['readOrder'])) { if (isset($styleArray['readOrder'])) {
$this->setReadOrder($pStyles['readOrder']); $this->setReadOrder($styleArray['readOrder']);
} }
} }
@ -193,21 +193,21 @@ class Alignment extends Supervisor
/** /**
* Set Horizontal. * Set Horizontal.
* *
* @param string $pValue see self::HORIZONTAL_* * @param string $horizontalAlignment see self::HORIZONTAL_*
* *
* @return $this * @return $this
*/ */
public function setHorizontal($pValue) public function setHorizontal(string $horizontalAlignment)
{ {
if ($pValue == '') { if ($horizontalAlignment == '') {
$pValue = self::HORIZONTAL_GENERAL; $horizontalAlignment = self::HORIZONTAL_GENERAL;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['horizontal' => $pValue]); $styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->horizontal = $pValue; $this->horizontal = $horizontalAlignment;
} }
return $this; return $this;
@ -230,21 +230,21 @@ class Alignment extends Supervisor
/** /**
* Set Vertical. * Set Vertical.
* *
* @param string $pValue see self::VERTICAL_* * @param string $verticalAlignment see self::VERTICAL_*
* *
* @return $this * @return $this
*/ */
public function setVertical($pValue) public function setVertical($verticalAlignment)
{ {
if ($pValue == '') { if ($verticalAlignment == '') {
$pValue = self::VERTICAL_BOTTOM; $verticalAlignment = self::VERTICAL_BOTTOM;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['vertical' => $pValue]); $styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->vertical = $pValue; $this->vertical = $verticalAlignment;
} }
return $this; return $this;
@ -267,24 +267,24 @@ class Alignment extends Supervisor
/** /**
* Set TextRotation. * Set TextRotation.
* *
* @param int $pValue * @param int $angleInDegrees
* *
* @return $this * @return $this
*/ */
public function setTextRotation($pValue) public function setTextRotation($angleInDegrees)
{ {
// Excel2007 value 255 => PhpSpreadsheet value -165 // Excel2007 value 255 => PhpSpreadsheet value -165
if ($pValue == self::TEXTROTATION_STACK_EXCEL) { if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) {
$pValue = self::TEXTROTATION_STACK_PHPSPREADSHEET; $angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET;
} }
// Set rotation // Set rotation
if (($pValue >= -90 && $pValue <= 90) || $pValue == self::TEXTROTATION_STACK_PHPSPREADSHEET) { if (($angleInDegrees >= -90 && $angleInDegrees <= 90) || $angleInDegrees == self::TEXTROTATION_STACK_PHPSPREADSHEET) {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['textRotation' => $pValue]); $styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->textRotation = $pValue; $this->textRotation = $angleInDegrees;
} }
} else { } else {
throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.'); throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.');
@ -310,20 +310,20 @@ class Alignment extends Supervisor
/** /**
* Set Wrap Text. * Set Wrap Text.
* *
* @param bool $pValue * @param bool $wrapped
* *
* @return $this * @return $this
*/ */
public function setWrapText($pValue) public function setWrapText($wrapped)
{ {
if ($pValue == '') { if ($wrapped == '') {
$pValue = false; $wrapped = false;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['wrapText' => $pValue]); $styleArray = $this->getStyleArray(['wrapText' => $wrapped]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->wrapText = $pValue; $this->wrapText = $wrapped;
} }
return $this; return $this;
@ -346,20 +346,20 @@ class Alignment extends Supervisor
/** /**
* Set Shrink to fit. * Set Shrink to fit.
* *
* @param bool $pValue * @param bool $shrink
* *
* @return $this * @return $this
*/ */
public function setShrinkToFit($pValue) public function setShrinkToFit($shrink)
{ {
if ($pValue == '') { if ($shrink == '') {
$pValue = false; $shrink = false;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['shrinkToFit' => $pValue]); $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->shrinkToFit = $pValue; $this->shrinkToFit = $shrink;
} }
return $this; return $this;
@ -382,27 +382,27 @@ class Alignment extends Supervisor
/** /**
* Set indent. * Set indent.
* *
* @param int $pValue * @param int $indent
* *
* @return $this * @return $this
*/ */
public function setIndent($pValue) public function setIndent($indent)
{ {
if ($pValue > 0) { if ($indent > 0) {
if ( if (
$this->getHorizontal() != self::HORIZONTAL_GENERAL && $this->getHorizontal() != self::HORIZONTAL_GENERAL &&
$this->getHorizontal() != self::HORIZONTAL_LEFT && $this->getHorizontal() != self::HORIZONTAL_LEFT &&
$this->getHorizontal() != self::HORIZONTAL_RIGHT && $this->getHorizontal() != self::HORIZONTAL_RIGHT &&
$this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED
) { ) {
$pValue = 0; // indent not supported $indent = 0; // indent not supported
} }
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['indent' => $pValue]); $styleArray = $this->getStyleArray(['indent' => $indent]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->indent = $pValue; $this->indent = $indent;
} }
return $this; return $this;
@ -425,20 +425,20 @@ class Alignment extends Supervisor
/** /**
* Set read order. * Set read order.
* *
* @param int $pValue * @param int $readOrder
* *
* @return $this * @return $this
*/ */
public function setReadOrder($pValue) public function setReadOrder($readOrder)
{ {
if ($pValue < 0 || $pValue > 2) { if ($readOrder < 0 || $readOrder > 2) {
$pValue = 0; $readOrder = 0;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['readOrder' => $pValue]); $styleArray = $this->getStyleArray(['readOrder' => $readOrder]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->readOrder = $pValue; $this->readOrder = $readOrder;
} }
return $this; return $this;

View File

@ -114,20 +114,20 @@ class Border extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['borderStyle'])) { if (isset($styleArray['borderStyle'])) {
$this->setBorderStyle($pStyles['borderStyle']); $this->setBorderStyle($styleArray['borderStyle']);
} }
if (isset($pStyles['color'])) { if (isset($styleArray['color'])) {
$this->getColor()->applyFromArray($pStyles['color']); $this->getColor()->applyFromArray($styleArray['color']);
} }
} }
@ -151,24 +151,25 @@ class Border extends Supervisor
/** /**
* Set Border style. * Set Border style.
* *
* @param bool|string $pValue * @param bool|string $style
* When passing a boolean, FALSE equates Border::BORDER_NONE * When passing a boolean, FALSE equates Border::BORDER_NONE
* and TRUE to Border::BORDER_MEDIUM * and TRUE to Border::BORDER_MEDIUM
* *
* @return $this * @return $this
*/ */
public function setBorderStyle($pValue) public function setBorderStyle($style)
{ {
if (empty($pValue)) { if (empty($style)) {
$pValue = self::BORDER_NONE; $style = self::BORDER_NONE;
} elseif (is_bool($pValue) && $pValue) { } elseif (is_bool($style)) {
$pValue = self::BORDER_MEDIUM; $style = self::BORDER_MEDIUM;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['borderStyle' => $pValue]); $styleArray = $this->getStyleArray(['borderStyle' => $style]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->borderStyle = $pValue; $this->borderStyle = $style;
} }
return $this; return $this;
@ -189,10 +190,10 @@ class Border extends Supervisor
* *
* @return $this * @return $this
*/ */
public function setColor(Color $pValue) public function setColor(Color $color)
{ {
// make sure parameter is a real color and not a supervisor // make sure parameter is a real color and not a supervisor
$color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]);

View File

@ -190,38 +190,38 @@ class Borders extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['left'])) { if (isset($styleArray['left'])) {
$this->getLeft()->applyFromArray($pStyles['left']); $this->getLeft()->applyFromArray($styleArray['left']);
} }
if (isset($pStyles['right'])) { if (isset($styleArray['right'])) {
$this->getRight()->applyFromArray($pStyles['right']); $this->getRight()->applyFromArray($styleArray['right']);
} }
if (isset($pStyles['top'])) { if (isset($styleArray['top'])) {
$this->getTop()->applyFromArray($pStyles['top']); $this->getTop()->applyFromArray($styleArray['top']);
} }
if (isset($pStyles['bottom'])) { if (isset($styleArray['bottom'])) {
$this->getBottom()->applyFromArray($pStyles['bottom']); $this->getBottom()->applyFromArray($styleArray['bottom']);
} }
if (isset($pStyles['diagonal'])) { if (isset($styleArray['diagonal'])) {
$this->getDiagonal()->applyFromArray($pStyles['diagonal']); $this->getDiagonal()->applyFromArray($styleArray['diagonal']);
} }
if (isset($pStyles['diagonalDirection'])) { if (isset($styleArray['diagonalDirection'])) {
$this->setDiagonalDirection($pStyles['diagonalDirection']); $this->setDiagonalDirection($styleArray['diagonalDirection']);
} }
if (isset($pStyles['allBorders'])) { if (isset($styleArray['allBorders'])) {
$this->getLeft()->applyFromArray($pStyles['allBorders']); $this->getLeft()->applyFromArray($styleArray['allBorders']);
$this->getRight()->applyFromArray($pStyles['allBorders']); $this->getRight()->applyFromArray($styleArray['allBorders']);
$this->getTop()->applyFromArray($pStyles['allBorders']); $this->getTop()->applyFromArray($styleArray['allBorders']);
$this->getBottom()->applyFromArray($pStyles['allBorders']); $this->getBottom()->applyFromArray($styleArray['allBorders']);
} }
} }
@ -365,20 +365,20 @@ class Borders extends Supervisor
/** /**
* Set DiagonalDirection. * Set DiagonalDirection.
* *
* @param int $pValue see self::DIAGONAL_* * @param int $direction see self::DIAGONAL_*
* *
* @return $this * @return $this
*/ */
public function setDiagonalDirection($pValue) public function setDiagonalDirection($direction)
{ {
if ($pValue == '') { if ($direction == '') {
$pValue = self::DIAGONAL_NONE; $direction = self::DIAGONAL_NONE;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['diagonalDirection' => $pValue]); $styleArray = $this->getStyleArray(['diagonalDirection' => $direction]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->diagonalDirection = $pValue; $this->diagonalDirection = $direction;
} }
return $this; return $this;

View File

@ -27,6 +27,10 @@ class Color extends Supervisor
const COLOR_YELLOW = 'FFFFFF00'; const COLOR_YELLOW = 'FFFFFF00';
const COLOR_DARKYELLOW = 'FF808000'; const COLOR_DARKYELLOW = 'FF808000';
const VALIDATE_ARGB_SIZE = 8;
const VALIDATE_RGB_SIZE = 6;
const VALIDATE_COLOR_VALUE = '/^[A-F0-9]{%d}$/i';
/** /**
* Indexed colors array. * Indexed colors array.
* *
@ -37,14 +41,14 @@ class Color extends Supervisor
/** /**
* ARGB - Alpha RGB. * ARGB - Alpha RGB.
* *
* @var string * @var null|string
*/ */
protected $argb; protected $argb;
/** /**
* Create a new Color. * Create a new Color.
* *
* @param string $pARGB ARGB value for the colour * @param string $colorValue ARGB value for the colour, or named colour
* @param bool $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 * Leave this value at default unless you understand exactly what
* its ramifications are * its ramifications are
@ -52,14 +56,14 @@ class Color extends Supervisor
* Leave this value at default unless you understand exactly what * Leave this value at default unless you understand exactly what
* its ramifications are * its ramifications are
*/ */
public function __construct($pARGB = self::COLOR_BLACK, $isSupervisor = false, $isConditional = false) public function __construct($colorValue = self::COLOR_BLACK, $isSupervisor = false, $isConditional = false)
{ {
// Supervisor? // Supervisor?
parent::__construct($isSupervisor); parent::__construct($isSupervisor);
// Initialise values // Initialise values
if (!$isConditional) { if (!$isConditional) {
$this->argb = $pARGB; $this->argb = $this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE) ? $colorValue : self::COLOR_BLACK;
} }
} }
@ -102,32 +106,36 @@ class Color extends Supervisor
* $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']); * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']);
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['rgb'])) { if (isset($styleArray['rgb'])) {
$this->setRGB($pStyles['rgb']); $this->setRGB($styleArray['rgb']);
} }
if (isset($pStyles['argb'])) { if (isset($styleArray['argb'])) {
$this->setARGB($pStyles['argb']); $this->setARGB($styleArray['argb']);
} }
} }
return $this; return $this;
} }
private function validateColor(string $colorValue, int $size): bool
{
return in_array(ucfirst(strtolower($colorValue)), self::NAMED_COLORS) ||
preg_match(sprintf(self::VALIDATE_COLOR_VALUE, $size), $colorValue);
}
/** /**
* Get ARGB. * Get ARGB.
*
* @return string
*/ */
public function getARGB() public function getARGB(): ?string
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
return $this->getSharedComponent()->getARGB(); return $this->getSharedComponent()->getARGB();
@ -139,20 +147,23 @@ class Color extends Supervisor
/** /**
* Set ARGB. * Set ARGB.
* *
* @param string $pValue see self::COLOR_* * @param string $colorValue ARGB value, or a named color
* *
* @return $this * @return $this
*/ */
public function setARGB($pValue) public function setARGB(?string $colorValue = self::COLOR_BLACK)
{ {
if ($pValue == '') { if ($colorValue === '' || $colorValue === null) {
$pValue = self::COLOR_BLACK; $colorValue = self::COLOR_BLACK;
} elseif (!$this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE)) {
return $this;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['argb' => $pValue]); $styleArray = $this->getStyleArray(['argb' => $colorValue]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->argb = $pValue; $this->argb = $colorValue;
} }
return $this; return $this;
@ -160,10 +171,8 @@ class Color extends Supervisor
/** /**
* Get RGB. * Get RGB.
*
* @return string
*/ */
public function getRGB() public function getRGB(): string
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
return $this->getSharedComponent()->getRGB(); return $this->getSharedComponent()->getRGB();
@ -175,20 +184,23 @@ class Color extends Supervisor
/** /**
* Set RGB. * Set RGB.
* *
* @param string $pValue RGB value * @param string $colorValue RGB value, or a named color
* *
* @return $this * @return $this
*/ */
public function setRGB($pValue) public function setRGB(?string $colorValue = self::COLOR_BLACK)
{ {
if ($pValue == '') { if ($colorValue === '' || $colorValue === null) {
$pValue = '000000'; $colorValue = '000000';
} elseif (!$this->validateColor($colorValue, self::VALIDATE_RGB_SIZE)) {
return $this;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['argb' => 'FF' . $pValue]); $styleArray = $this->getStyleArray(['argb' => 'FF' . $colorValue]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->argb = 'FF' . $pValue; $this->argb = 'FF' . $colorValue;
} }
return $this; return $this;
@ -197,16 +209,16 @@ class Color extends Supervisor
/** /**
* Get a specified colour component of an RGB value. * Get a specified colour component of an RGB value.
* *
* @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param int $offset Position within the RGB value to extract * @param int $offset Position within the RGB value to extract
* @param bool $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 * decimal value
* *
* @return int|string The extracted colour component * @return int|string The extracted colour component
*/ */
private static function getColourComponent($RGB, $offset, $hex = true) private static function getColourComponent($rgbValue, $offset, $hex = true)
{ {
$colour = substr($RGB, $offset, 2); $colour = substr($rgbValue, $offset, 2);
return ($hex) ? $colour : hexdec($colour); return ($hex) ? $colour : hexdec($colour);
} }
@ -214,64 +226,64 @@ class Color extends Supervisor
/** /**
* Get the red colour component of an RGB value. * Get the red colour component of an RGB value.
* *
* @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $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 * decimal value
* *
* @return int|string The red colour component * @return int|string The red colour component
*/ */
public static function getRed($RGB, $hex = true) public static function getRed($rgbValue, $hex = true)
{ {
return self::getColourComponent($RGB, strlen($RGB) - 6, $hex); return self::getColourComponent($rgbValue, strlen($rgbValue) - 6, $hex);
} }
/** /**
* Get the green colour component of an RGB value. * Get the green colour component of an RGB value.
* *
* @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $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 * decimal value
* *
* @return int|string The green colour component * @return int|string The green colour component
*/ */
public static function getGreen($RGB, $hex = true) public static function getGreen($rgbValue, $hex = true)
{ {
return self::getColourComponent($RGB, strlen($RGB) - 4, $hex); return self::getColourComponent($rgbValue, strlen($rgbValue) - 4, $hex);
} }
/** /**
* Get the blue colour component of an RGB value. * Get the blue colour component of an RGB value.
* *
* @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $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 * decimal value
* *
* @return int|string The blue colour component * @return int|string The blue colour component
*/ */
public static function getBlue($RGB, $hex = true) public static function getBlue($rgbValue, $hex = true)
{ {
return self::getColourComponent($RGB, strlen($RGB) - 2, $hex); return self::getColourComponent($rgbValue, strlen($rgbValue) - 2, $hex);
} }
/** /**
* Adjust the brightness of a color. * Adjust the brightness of a color.
* *
* @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) * @param string $hexColourValue The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
* @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1 * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1
* *
* @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
*/ */
public static function changeBrightness($hex, $adjustPercentage) public static function changeBrightness($hexColourValue, $adjustPercentage)
{ {
$rgba = (strlen($hex) === 8); $rgba = (strlen($hexColourValue) === 8);
$adjustPercentage = max(-1.0, min(1.0, $adjustPercentage)); $adjustPercentage = max(-1.0, min(1.0, $adjustPercentage));
/** @var int $red */ /** @var int $red */
$red = self::getRed($hex, false); $red = self::getRed($hexColourValue, false);
/** @var int $green */ /** @var int $green */
$green = self::getGreen($hex, false); $green = self::getGreen($hexColourValue, false);
/** @var int $blue */ /** @var int $blue */
$blue = self::getBlue($hex, false); $blue = self::getBlue($hexColourValue, false);
if ($adjustPercentage > 0) { if ($adjustPercentage > 0) {
$red += (255 - $red) * $adjustPercentage; $red += (255 - $red) * $adjustPercentage;
$green += (255 - $green) * $adjustPercentage; $green += (255 - $green) * $adjustPercentage;
@ -294,16 +306,16 @@ class Color extends Supervisor
/** /**
* Get indexed color. * Get indexed color.
* *
* @param int $pIndex Index entry point into the colour array * @param int $colorIndex Index entry point into the colour array
* @param bool $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 * should be returned if the indexed colour doesn't exist
* *
* @return self * @return Color
*/ */
public static function indexedColor($pIndex, $background = false) public static function indexedColor($colorIndex, $background = false): self
{ {
// Clean parameter // Clean parameter
$pIndex = (int) $pIndex; $colorIndex = (int) $colorIndex;
// Indexed colors // Indexed colors
if (self::$indexedColors === null) { if (self::$indexedColors === null) {
@ -367,15 +379,11 @@ class Color extends Supervisor
]; ];
} }
if (isset(self::$indexedColors[$pIndex])) { if (isset(self::$indexedColors[$colorIndex])) {
return new self(self::$indexedColors[$pIndex]); return new self(self::$indexedColors[$colorIndex]);
} }
if ($background) { return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK);
return new self(self::COLOR_WHITE);
}
return new self(self::COLOR_BLACK);
} }
/** /**
@ -383,7 +391,7 @@ class Color extends Supervisor
* *
* @return string Hash code * @return string Hash code
*/ */
public function getHashCode() public function getHashCode(): string
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode(); return $this->getSharedComponent()->getHashCode();

View File

@ -112,13 +112,13 @@ class Conditional implements IComparable
/** /**
* Set Condition type. * Set Condition type.
* *
* @param string $pValue Condition type, see self::CONDITION_* * @param string $type Condition type, see self::CONDITION_*
* *
* @return $this * @return $this
*/ */
public function setConditionType($pValue) public function setConditionType($type)
{ {
$this->conditionType = $pValue; $this->conditionType = $type;
return $this; return $this;
} }
@ -136,13 +136,13 @@ class Conditional implements IComparable
/** /**
* Set Operator type. * Set Operator type.
* *
* @param string $pValue Conditional operator type, see self::OPERATOR_* * @param string $type Conditional operator type, see self::OPERATOR_*
* *
* @return $this * @return $this
*/ */
public function setOperatorType($pValue) public function setOperatorType($type)
{ {
$this->operatorType = $pValue; $this->operatorType = $type;
return $this; return $this;
} }
@ -160,13 +160,13 @@ class Conditional implements IComparable
/** /**
* Set text. * Set text.
* *
* @param string $value * @param string $text
* *
* @return $this * @return $this
*/ */
public function setText($value) public function setText($text)
{ {
$this->text = $value; $this->text = $text;
return $this; return $this;
} }
@ -184,13 +184,13 @@ class Conditional implements IComparable
/** /**
* Set StopIfTrue. * Set StopIfTrue.
* *
* @param bool $value * @param bool $stopIfTrue
* *
* @return $this * @return $this
*/ */
public function setStopIfTrue($value) public function setStopIfTrue($stopIfTrue)
{ {
$this->stopIfTrue = $value; $this->stopIfTrue = $stopIfTrue;
return $this; return $this;
} }
@ -208,16 +208,16 @@ class Conditional implements IComparable
/** /**
* Set Conditions. * Set Conditions.
* *
* @param bool|float|int|string|string[] $pValue Condition * @param bool|float|int|string|string[] $conditions Condition
* *
* @return $this * @return $this
*/ */
public function setConditions($pValue) public function setConditions($conditions)
{ {
if (!is_array($pValue)) { if (!is_array($conditions)) {
$pValue = [$pValue]; $conditions = [$conditions];
} }
$this->condition = $pValue; $this->condition = $conditions;
return $this; return $this;
} }
@ -225,13 +225,13 @@ class Conditional implements IComparable
/** /**
* Add Condition. * Add Condition.
* *
* @param string $pValue Condition * @param string $condition Condition
* *
* @return $this * @return $this
*/ */
public function addCondition($pValue) public function addCondition($condition)
{ {
$this->condition[] = $pValue; $this->condition[] = $condition;
return $this; return $this;
} }
@ -249,13 +249,13 @@ class Conditional implements IComparable
/** /**
* Set Style. * Set Style.
* *
* @param Style $pValue * @param Style $style
* *
* @return $this * @return $this
*/ */
public function setStyle(?Style $pValue = null) public function setStyle(?Style $style = null)
{ {
$this->style = $pValue; $this->style = $style;
return $this; return $this;
} }

View File

@ -135,30 +135,30 @@ class Fill extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['fillType'])) { if (isset($styleArray['fillType'])) {
$this->setFillType($pStyles['fillType']); $this->setFillType($styleArray['fillType']);
} }
if (isset($pStyles['rotation'])) { if (isset($styleArray['rotation'])) {
$this->setRotation($pStyles['rotation']); $this->setRotation($styleArray['rotation']);
} }
if (isset($pStyles['startColor'])) { if (isset($styleArray['startColor'])) {
$this->getStartColor()->applyFromArray($pStyles['startColor']); $this->getStartColor()->applyFromArray($styleArray['startColor']);
} }
if (isset($pStyles['endColor'])) { if (isset($styleArray['endColor'])) {
$this->getEndColor()->applyFromArray($pStyles['endColor']); $this->getEndColor()->applyFromArray($styleArray['endColor']);
} }
if (isset($pStyles['color'])) { if (isset($styleArray['color'])) {
$this->getStartColor()->applyFromArray($pStyles['color']); $this->getStartColor()->applyFromArray($styleArray['color']);
$this->getEndColor()->applyFromArray($pStyles['color']); $this->getEndColor()->applyFromArray($styleArray['color']);
} }
} }
@ -182,17 +182,17 @@ class Fill extends Supervisor
/** /**
* Set Fill Type. * Set Fill Type.
* *
* @param string $pValue Fill type, see self::FILL_* * @param string $fillType Fill type, see self::FILL_*
* *
* @return $this * @return $this
*/ */
public function setFillType($pValue) public function setFillType($fillType)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['fillType' => $pValue]); $styleArray = $this->getStyleArray(['fillType' => $fillType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->fillType = $pValue; $this->fillType = $fillType;
} }
return $this; return $this;
@ -215,17 +215,17 @@ class Fill extends Supervisor
/** /**
* Set Rotation. * Set Rotation.
* *
* @param float $pValue * @param float $angleInDegrees
* *
* @return $this * @return $this
*/ */
public function setRotation($pValue) public function setRotation($angleInDegrees)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['rotation' => $pValue]); $styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->rotation = $pValue; $this->rotation = $angleInDegrees;
} }
return $this; return $this;
@ -246,10 +246,10 @@ class Fill extends Supervisor
* *
* @return $this * @return $this
*/ */
public function setStartColor(Color $pValue) public function setStartColor(Color $color)
{ {
// make sure parameter is a real color and not a supervisor // make sure parameter is a real color and not a supervisor
$color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]); $styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]);
@ -276,10 +276,10 @@ class Fill extends Supervisor
* *
* @return $this * @return $this
*/ */
public function setEndColor(Color $pValue) public function setEndColor(Color $color)
{ {
// make sure parameter is a real color and not a supervisor // make sure parameter is a real color and not a supervisor
$color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]); $styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]);

View File

@ -155,41 +155,41 @@ class Font extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['name'])) { if (isset($styleArray['name'])) {
$this->setName($pStyles['name']); $this->setName($styleArray['name']);
} }
if (isset($pStyles['bold'])) { if (isset($styleArray['bold'])) {
$this->setBold($pStyles['bold']); $this->setBold($styleArray['bold']);
} }
if (isset($pStyles['italic'])) { if (isset($styleArray['italic'])) {
$this->setItalic($pStyles['italic']); $this->setItalic($styleArray['italic']);
} }
if (isset($pStyles['superscript'])) { if (isset($styleArray['superscript'])) {
$this->setSuperscript($pStyles['superscript']); $this->setSuperscript($styleArray['superscript']);
} }
if (isset($pStyles['subscript'])) { if (isset($styleArray['subscript'])) {
$this->setSubscript($pStyles['subscript']); $this->setSubscript($styleArray['subscript']);
} }
if (isset($pStyles['underline'])) { if (isset($styleArray['underline'])) {
$this->setUnderline($pStyles['underline']); $this->setUnderline($styleArray['underline']);
} }
if (isset($pStyles['strikethrough'])) { if (isset($styleArray['strikethrough'])) {
$this->setStrikethrough($pStyles['strikethrough']); $this->setStrikethrough($styleArray['strikethrough']);
} }
if (isset($pStyles['color'])) { if (isset($styleArray['color'])) {
$this->getColor()->applyFromArray($pStyles['color']); $this->getColor()->applyFromArray($styleArray['color']);
} }
if (isset($pStyles['size'])) { if (isset($styleArray['size'])) {
$this->setSize($pStyles['size']); $this->setSize($styleArray['size']);
} }
} }
@ -292,20 +292,20 @@ class Font extends Supervisor
/** /**
* Set Bold. * Set Bold.
* *
* @param bool $pValue * @param bool $bold
* *
* @return $this * @return $this
*/ */
public function setBold($pValue) public function setBold($bold)
{ {
if ($pValue == '') { if ($bold == '') {
$pValue = false; $bold = false;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['bold' => $pValue]); $styleArray = $this->getStyleArray(['bold' => $bold]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->bold = $pValue; $this->bold = $bold;
} }
return $this; return $this;
@ -328,20 +328,20 @@ class Font extends Supervisor
/** /**
* Set Italic. * Set Italic.
* *
* @param bool $pValue * @param bool $italic
* *
* @return $this * @return $this
*/ */
public function setItalic($pValue) public function setItalic($italic)
{ {
if ($pValue == '') { if ($italic == '') {
$pValue = false; $italic = false;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['italic' => $pValue]); $styleArray = $this->getStyleArray(['italic' => $italic]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->italic = $pValue; $this->italic = $italic;
} }
return $this; return $this;
@ -366,13 +366,13 @@ class Font extends Supervisor
* *
* @return $this * @return $this
*/ */
public function setSuperscript(bool $pValue) public function setSuperscript(bool $superscript)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['superscript' => $pValue]); $styleArray = $this->getStyleArray(['superscript' => $superscript]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->superscript = $pValue; $this->superscript = $superscript;
if ($this->superscript) { if ($this->superscript) {
$this->subscript = false; $this->subscript = false;
} }
@ -400,13 +400,13 @@ class Font extends Supervisor
* *
* @return $this * @return $this
*/ */
public function setSubscript(bool $pValue) public function setSubscript(bool $subscript)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['subscript' => $pValue]); $styleArray = $this->getStyleArray(['subscript' => $subscript]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->subscript = $pValue; $this->subscript = $subscript;
if ($this->subscript) { if ($this->subscript) {
$this->superscript = false; $this->superscript = false;
} }
@ -432,24 +432,24 @@ class Font extends Supervisor
/** /**
* Set Underline. * Set Underline.
* *
* @param bool|string $pValue \PhpOffice\PhpSpreadsheet\Style\Font underline type * @param bool|string $underlineStyle \PhpOffice\PhpSpreadsheet\Style\Font underline type
* If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE, * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE,
* false equates to UNDERLINE_NONE * false equates to UNDERLINE_NONE
* *
* @return $this * @return $this
*/ */
public function setUnderline($pValue) public function setUnderline($underlineStyle)
{ {
if (is_bool($pValue)) { if (is_bool($underlineStyle)) {
$pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; $underlineStyle = ($underlineStyle) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
} elseif ($pValue == '') { } elseif ($underlineStyle == '') {
$pValue = self::UNDERLINE_NONE; $underlineStyle = self::UNDERLINE_NONE;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['underline' => $pValue]); $styleArray = $this->getStyleArray(['underline' => $underlineStyle]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->underline = $pValue; $this->underline = $underlineStyle;
} }
return $this; return $this;
@ -472,21 +472,21 @@ class Font extends Supervisor
/** /**
* Set Strikethrough. * Set Strikethrough.
* *
* @param bool $pValue * @param bool $strikethru
* *
* @return $this * @return $this
*/ */
public function setStrikethrough($pValue) public function setStrikethrough($strikethru)
{ {
if ($pValue == '') { if ($strikethru == '') {
$pValue = false; $strikethru = false;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['strikethrough' => $pValue]); $styleArray = $this->getStyleArray(['strikethrough' => $strikethru]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->strikethrough = $pValue; $this->strikethrough = $strikethru;
} }
return $this; return $this;
@ -507,10 +507,10 @@ class Font extends Supervisor
* *
* @return $this * @return $this
*/ */
public function setColor(Color $pValue) public function setColor(Color $color)
{ {
// make sure parameter is a real color and not a supervisor // make sure parameter is a real color and not a supervisor
$color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]);

View File

@ -130,17 +130,17 @@ class NumberFormat extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['formatCode'])) { if (isset($styleArray['formatCode'])) {
$this->setFormatCode($pStyles['formatCode']); $this->setFormatCode($styleArray['formatCode']);
} }
} }
@ -167,21 +167,21 @@ class NumberFormat extends Supervisor
/** /**
* Set Format Code. * Set Format Code.
* *
* @param string $pValue see self::FORMAT_* * @param string $formatCode see self::FORMAT_*
* *
* @return $this * @return $this
*/ */
public function setFormatCode($pValue) public function setFormatCode($formatCode)
{ {
if ($pValue == '') { if ($formatCode == '') {
$pValue = self::FORMAT_GENERAL; $formatCode = self::FORMAT_GENERAL;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['formatCode' => $pValue]); $styleArray = $this->getStyleArray(['formatCode' => $formatCode]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->formatCode = $pValue; $this->formatCode = $formatCode;
$this->builtInFormatCode = self::builtInFormatCodeIndex($pValue); $this->builtInFormatCode = self::builtInFormatCodeIndex($formatCode);
} }
return $this; return $this;
@ -204,18 +204,18 @@ class NumberFormat extends Supervisor
/** /**
* Set Built-In Format Code. * Set Built-In Format Code.
* *
* @param int $pValue * @param int $formatCodeIndex
* *
* @return $this * @return $this
*/ */
public function setBuiltInFormatCode($pValue) public function setBuiltInFormatCode($formatCodeIndex)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($pValue)]); $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($formatCodeIndex)]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->builtInFormatCode = $pValue; $this->builtInFormatCode = $formatCodeIndex;
$this->formatCode = self::builtInFormatCode($pValue); $this->formatCode = self::builtInFormatCode($formatCodeIndex);
} }
return $this; return $this;
@ -327,21 +327,21 @@ class NumberFormat extends Supervisor
/** /**
* Get built-in format code. * Get built-in format code.
* *
* @param int $pIndex * @param int $index
* *
* @return string * @return string
*/ */
public static function builtInFormatCode($pIndex) public static function builtInFormatCode($index)
{ {
// Clean parameter // Clean parameter
$pIndex = (int) $pIndex; $index = (int) $index;
// Ensure built-in format codes are available // Ensure built-in format codes are available
self::fillBuiltInFormatCodes(); self::fillBuiltInFormatCodes();
// Lookup format code // Lookup format code
if (isset(self::$builtInFormats[$pIndex])) { if (isset(self::$builtInFormats[$index])) {
return self::$builtInFormats[$pIndex]; return self::$builtInFormats[$index];
} }
return ''; return '';
@ -350,18 +350,18 @@ class NumberFormat extends Supervisor
/** /**
* Get built-in format code index. * Get built-in format code index.
* *
* @param string $formatCode * @param string $formatCodeIndex
* *
* @return bool|int * @return bool|int
*/ */
public static function builtInFormatCodeIndex($formatCode) public static function builtInFormatCodeIndex($formatCodeIndex)
{ {
// Ensure built-in format codes are available // Ensure built-in format codes are available
self::fillBuiltInFormatCodes(); self::fillBuiltInFormatCodes();
// Lookup format code // Lookup format code
if (array_key_exists($formatCode, self::$flippedBuiltInFormats)) { if (array_key_exists($formatCodeIndex, self::$flippedBuiltInFormats)) {
return self::$flippedBuiltInFormats[$formatCode]; return self::$flippedBuiltInFormats[$formatCodeIndex];
} }
return false; return false;

View File

@ -80,20 +80,20 @@ class Protection extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles) public function applyFromArray(array $styleArray)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else { } else {
if (isset($pStyles['locked'])) { if (isset($styleArray['locked'])) {
$this->setLocked($pStyles['locked']); $this->setLocked($styleArray['locked']);
} }
if (isset($pStyles['hidden'])) { if (isset($styleArray['hidden'])) {
$this->setHidden($pStyles['hidden']); $this->setHidden($styleArray['hidden']);
} }
} }
@ -117,17 +117,17 @@ class Protection extends Supervisor
/** /**
* Set locked. * Set locked.
* *
* @param string $pValue see self::PROTECTION_* * @param string $lockType see self::PROTECTION_*
* *
* @return $this * @return $this
*/ */
public function setLocked($pValue) public function setLocked($lockType)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['locked' => $pValue]); $styleArray = $this->getStyleArray(['locked' => $lockType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->locked = $pValue; $this->locked = $lockType;
} }
return $this; return $this;
@ -150,17 +150,17 @@ class Protection extends Supervisor
/** /**
* Set hidden. * Set hidden.
* *
* @param string $pValue see self::PROTECTION_* * @param string $hiddenType see self::PROTECTION_*
* *
* @return $this * @return $this
*/ */
public function setHidden($pValue) public function setHidden($hiddenType)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['hidden' => $pValue]); $styleArray = $this->getStyleArray(['hidden' => $hiddenType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->hidden = $pValue; $this->hidden = $hiddenType;
} }
return $this; return $this;

View File

@ -120,10 +120,8 @@ class Style extends Supervisor
/** /**
* Get the shared style component for the currently active cell in currently active sheet. * Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor. * Only used for style supervisor.
*
* @return Style
*/ */
public function getSharedComponent() public function getSharedComponent(): self
{ {
$activeSheet = $this->getActiveSheet(); $activeSheet = $this->getActiveSheet();
$selectedCell = $this->getActiveCell(); // e.g. 'A1' $selectedCell = $this->getActiveCell(); // e.g. 'A1'
@ -199,12 +197,12 @@ class Style extends Supervisor
* ); * );
* </code> * </code>
* *
* @param array $pStyles Array containing style information * @param array $styleArray Array containing style information
* @param bool $pAdvanced advanced mode for setting borders * @param bool $advancedBorders advanced mode for setting borders
* *
* @return $this * @return $this
*/ */
public function applyFromArray(array $pStyles, $pAdvanced = true) public function applyFromArray(array $styleArray, $advancedBorders = true)
{ {
if ($this->isSupervisor) { if ($this->isSupervisor) {
$pRange = $this->getSelectedCells(); $pRange = $this->getSelectedCells();
@ -237,36 +235,36 @@ class Style extends Supervisor
} }
// ADVANCED MODE: // ADVANCED MODE:
if ($pAdvanced && isset($pStyles['borders'])) { if ($advancedBorders && isset($styleArray['borders'])) {
// 'allBorders' is a shorthand property for 'outline' and 'inside' and // 'allBorders' is a shorthand property for 'outline' and 'inside' and
// it applies to components that have not been set explicitly // it applies to components that have not been set explicitly
if (isset($pStyles['borders']['allBorders'])) { if (isset($styleArray['borders']['allBorders'])) {
foreach (['outline', 'inside'] as $component) { foreach (['outline', 'inside'] as $component) {
if (!isset($pStyles['borders'][$component])) { if (!isset($styleArray['borders'][$component])) {
$pStyles['borders'][$component] = $pStyles['borders']['allBorders']; $styleArray['borders'][$component] = $styleArray['borders']['allBorders'];
} }
} }
unset($pStyles['borders']['allBorders']); // not needed any more unset($styleArray['borders']['allBorders']); // not needed any more
} }
// 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left' // 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left'
// it applies to components that have not been set explicitly // it applies to components that have not been set explicitly
if (isset($pStyles['borders']['outline'])) { if (isset($styleArray['borders']['outline'])) {
foreach (['top', 'right', 'bottom', 'left'] as $component) { foreach (['top', 'right', 'bottom', 'left'] as $component) {
if (!isset($pStyles['borders'][$component])) { if (!isset($styleArray['borders'][$component])) {
$pStyles['borders'][$component] = $pStyles['borders']['outline']; $styleArray['borders'][$component] = $styleArray['borders']['outline'];
} }
} }
unset($pStyles['borders']['outline']); // not needed any more unset($styleArray['borders']['outline']); // not needed any more
} }
// 'inside' is a shorthand property for 'vertical' and 'horizontal' // 'inside' is a shorthand property for 'vertical' and 'horizontal'
// it applies to components that have not been set explicitly // it applies to components that have not been set explicitly
if (isset($pStyles['borders']['inside'])) { if (isset($styleArray['borders']['inside'])) {
foreach (['vertical', 'horizontal'] as $component) { foreach (['vertical', 'horizontal'] as $component) {
if (!isset($pStyles['borders'][$component])) { if (!isset($styleArray['borders'][$component])) {
$pStyles['borders'][$component] = $pStyles['borders']['inside']; $styleArray['borders'][$component] = $styleArray['borders']['inside'];
} }
} }
unset($pStyles['borders']['inside']); // not needed any more unset($styleArray['borders']['inside']); // not needed any more
} }
// width and height characteristics of selection, 1, 2, or 3 (for 3 or more) // width and height characteristics of selection, 1, 2, or 3 (for 3 or more)
$xMax = min($rangeEndIndexes[0] - $rangeStartIndexes[0] + 1, 3); $xMax = min($rangeEndIndexes[0] - $rangeStartIndexes[0] + 1, 3);
@ -315,7 +313,7 @@ class Style extends Supervisor
$range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd;
// retrieve relevant style array for region // retrieve relevant style array for region
$regionStyles = $pStyles; $regionStyles = $styleArray;
unset($regionStyles['borders']['inside']); unset($regionStyles['borders']['inside']);
// what are the inner edges of the region when looking at the selection // what are the inner edges of the region when looking at the selection
@ -327,8 +325,8 @@ class Style extends Supervisor
case 'top': case 'top':
case 'bottom': case 'bottom':
// should pick up 'horizontal' border property if set // should pick up 'horizontal' border property if set
if (isset($pStyles['borders']['horizontal'])) { if (isset($styleArray['borders']['horizontal'])) {
$regionStyles['borders'][$innerEdge] = $pStyles['borders']['horizontal']; $regionStyles['borders'][$innerEdge] = $styleArray['borders']['horizontal'];
} else { } else {
unset($regionStyles['borders'][$innerEdge]); unset($regionStyles['borders'][$innerEdge]);
} }
@ -337,8 +335,8 @@ class Style extends Supervisor
case 'left': case 'left':
case 'right': case 'right':
// should pick up 'vertical' border property if set // should pick up 'vertical' border property if set
if (isset($pStyles['borders']['vertical'])) { if (isset($styleArray['borders']['vertical'])) {
$regionStyles['borders'][$innerEdge] = $pStyles['borders']['vertical']; $regionStyles['borders'][$innerEdge] = $styleArray['borders']['vertical'];
} else { } else {
unset($regionStyles['borders'][$innerEdge]); unset($regionStyles['borders'][$innerEdge]);
} }
@ -375,7 +373,7 @@ class Style extends Supervisor
} }
// First loop through columns, rows, or cells to find out which styles are affected by this operation // First loop through columns, rows, or cells to find out which styles are affected by this operation
$oldXfIndexes = $this->getOldXfIndexes($selectionType, $rangeStartIndexes, $rangeEndIndexes, $columnStart, $columnEnd, $pStyles); $oldXfIndexes = $this->getOldXfIndexes($selectionType, $rangeStartIndexes, $rangeEndIndexes, $columnStart, $columnEnd, $styleArray);
// clone each of the affected styles, apply the style array, and add the new styles to the workbook // clone each of the affected styles, apply the style array, and add the new styles to the workbook
$workbook = $this->getActiveSheet()->getParent(); $workbook = $this->getActiveSheet()->getParent();
@ -387,7 +385,7 @@ class Style extends Supervisor
if (self::$cachedStyles === null) { if (self::$cachedStyles === null) {
// Clone the old style and apply style-array // Clone the old style and apply style-array
$newStyle = clone $style; $newStyle = clone $style;
$newStyle->applyFromArray($pStyles); $newStyle->applyFromArray($styleArray);
// Look for existing style we can use instead (reduce memory usage) // Look for existing style we can use instead (reduce memory usage)
$existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode());
@ -409,7 +407,7 @@ class Style extends Supervisor
if (!$existingStyle) { if (!$existingStyle) {
// The old style combined with the new style array is not cached, so we create it now // The old style combined with the new style array is not cached, so we create it now
$newStyle = clone $style; $newStyle = clone $style;
$newStyle->applyFromArray($pStyles); $newStyle->applyFromArray($styleArray);
// Look for similar style in workbook to reduce memory usage // Look for similar style in workbook to reduce memory usage
$existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode());
@ -428,7 +426,7 @@ class Style extends Supervisor
// $newStyle should always be defined. // $newStyle should always be defined.
// This block might not be needed in the future // This block might not be needed in the future
$newStyle = clone $style; $newStyle = clone $style;
$newStyle->applyFromArray($pStyles); $newStyle->applyFromArray($styleArray);
} }
// we don't have such a cell Xf, need to add // we don't have such a cell Xf, need to add
@ -475,33 +473,33 @@ class Style extends Supervisor
} }
} else { } else {
// not a supervisor, just apply the style array directly on style object // not a supervisor, just apply the style array directly on style object
if (isset($pStyles['fill'])) { if (isset($styleArray['fill'])) {
$this->getFill()->applyFromArray($pStyles['fill']); $this->getFill()->applyFromArray($styleArray['fill']);
} }
if (isset($pStyles['font'])) { if (isset($styleArray['font'])) {
$this->getFont()->applyFromArray($pStyles['font']); $this->getFont()->applyFromArray($styleArray['font']);
} }
if (isset($pStyles['borders'])) { if (isset($styleArray['borders'])) {
$this->getBorders()->applyFromArray($pStyles['borders']); $this->getBorders()->applyFromArray($styleArray['borders']);
} }
if (isset($pStyles['alignment'])) { if (isset($styleArray['alignment'])) {
$this->getAlignment()->applyFromArray($pStyles['alignment']); $this->getAlignment()->applyFromArray($styleArray['alignment']);
} }
if (isset($pStyles['numberFormat'])) { if (isset($styleArray['numberFormat'])) {
$this->getNumberFormat()->applyFromArray($pStyles['numberFormat']); $this->getNumberFormat()->applyFromArray($styleArray['numberFormat']);
} }
if (isset($pStyles['protection'])) { if (isset($styleArray['protection'])) {
$this->getProtection()->applyFromArray($pStyles['protection']); $this->getProtection()->applyFromArray($styleArray['protection']);
} }
if (isset($pStyles['quotePrefix'])) { if (isset($styleArray['quotePrefix'])) {
$this->quotePrefix = $pStyles['quotePrefix']; $this->quotePrefix = $styleArray['quotePrefix'];
} }
} }
return $this; return $this;
} }
private function getOldXfIndexes(string $selectionType, array $rangeStart, array $rangeEnd, string $columnStart, string $columnEnd, array $pStyles): array private function getOldXfIndexes(string $selectionType, array $rangeStart, array $rangeEnd, string $columnStart, string $columnEnd, array $styleArray): array
{ {
$oldXfIndexes = []; $oldXfIndexes = [];
switch ($selectionType) { switch ($selectionType) {
@ -514,7 +512,7 @@ class Style extends Supervisor
$cellIterator->setIterateOnlyExistingCells(true); $cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $columnCell) { foreach ($cellIterator as $columnCell) {
if ($columnCell !== null) { if ($columnCell !== null) {
$columnCell->getStyle()->applyFromArray($pStyles); $columnCell->getStyle()->applyFromArray($styleArray);
} }
} }
} }
@ -533,7 +531,7 @@ class Style extends Supervisor
$cellIterator->setIterateOnlyExistingCells(true); $cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $rowCell) { foreach ($cellIterator as $rowCell) {
if ($rowCell !== null) { if ($rowCell !== null) {
$rowCell->getStyle()->applyFromArray($pStyles); $rowCell->getStyle()->applyFromArray($styleArray);
} }
} }
} }
@ -627,13 +625,13 @@ class Style extends Supervisor
/** /**
* Set Conditional Styles. Only used on supervisor. * Set Conditional Styles. Only used on supervisor.
* *
* @param Conditional[] $pValue Array of conditional styles * @param Conditional[] $conditionalStyleArray Array of conditional styles
* *
* @return $this * @return $this
*/ */
public function setConditionalStyles(array $pValue) public function setConditionalStyles(array $conditionalStyleArray)
{ {
$this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $pValue); $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $conditionalStyleArray);
return $this; return $this;
} }
@ -665,20 +663,20 @@ class Style extends Supervisor
/** /**
* Set quote prefix. * Set quote prefix.
* *
* @param bool $pValue * @param bool $quotePrefix
* *
* @return $this * @return $this
*/ */
public function setQuotePrefix($pValue) public function setQuotePrefix($quotePrefix)
{ {
if ($pValue == '') { if ($quotePrefix == '') {
$pValue = false; $quotePrefix = false;
} }
if ($this->isSupervisor) { if ($this->isSupervisor) {
$styleArray = ['quotePrefix' => $pValue]; $styleArray = ['quotePrefix' => $quotePrefix];
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else { } else {
$this->quotePrefix = (bool) $pValue; $this->quotePrefix = (bool) $quotePrefix;
} }
return $this; return $this;
@ -716,11 +714,11 @@ class Style extends Supervisor
/** /**
* Set own index in style collection. * Set own index in style collection.
* *
* @param int $pValue * @param int $index
*/ */
public function setIndex($pValue): void public function setIndex($index): void
{ {
$this->index = $pValue; $this->index = $index;
} }
protected function exportArray1(): array protected function exportArray1(): array

View File

@ -39,12 +39,12 @@ class AutoFilter
* Create a new AutoFilter. * Create a new AutoFilter.
* *
* @param string $pRange Cell range (i.e. A1:E10) * @param string $pRange Cell range (i.e. A1:E10)
* @param Worksheet $pSheet * @param Worksheet $worksheet
*/ */
public function __construct($pRange = '', ?Worksheet $pSheet = null) public function __construct($pRange = '', ?Worksheet $worksheet = null)
{ {
$this->range = $pRange; $this->range = $pRange;
$this->workSheet = $pSheet; $this->workSheet = $worksheet;
} }
/** /**
@ -60,13 +60,13 @@ class AutoFilter
/** /**
* Set AutoFilter Parent Worksheet. * Set AutoFilter Parent Worksheet.
* *
* @param Worksheet $pSheet * @param Worksheet $worksheet
* *
* @return $this * @return $this
*/ */
public function setParent(?Worksheet $pSheet = null) public function setParent(?Worksheet $worksheet = null)
{ {
$this->workSheet = $pSheet; $this->workSheet = $worksheet;
return $this; return $this;
} }

View File

@ -50,9 +50,9 @@ abstract class BaseWriter implements IWriter
return $this->includeCharts; return $this->includeCharts;
} }
public function setIncludeCharts($pValue) public function setIncludeCharts($includeCharts)
{ {
$this->includeCharts = (bool) $pValue; $this->includeCharts = (bool) $includeCharts;
return $this; return $this;
} }
@ -62,9 +62,9 @@ abstract class BaseWriter implements IWriter
return $this->preCalculateFormulas; return $this->preCalculateFormulas;
} }
public function setPreCalculateFormulas($pValue) public function setPreCalculateFormulas($precalculateFormulas)
{ {
$this->preCalculateFormulas = (bool) $pValue; $this->preCalculateFormulas = (bool) $precalculateFormulas;
return $this; return $this;
} }
@ -74,15 +74,15 @@ abstract class BaseWriter implements IWriter
return $this->useDiskCaching; return $this->useDiskCaching;
} }
public function setUseDiskCaching($pValue, $pDirectory = null) public function setUseDiskCaching($useDiskCache, $cacheDirectory = null)
{ {
$this->useDiskCaching = $pValue; $this->useDiskCaching = $useDiskCache;
if ($pDirectory !== null) { if ($cacheDirectory !== null) {
if (is_dir($pDirectory)) { if (is_dir($cacheDirectory)) {
$this->diskCachingDirectory = $pDirectory; $this->diskCachingDirectory = $cacheDirectory;
} else { } else {
throw new Exception("Directory does not exist: $pDirectory"); throw new Exception("Directory does not exist: $cacheDirectory");
} }
} }

View File

@ -84,9 +84,9 @@ class Csv extends BaseWriter
/** /**
* Save PhpSpreadsheet to file. * Save PhpSpreadsheet to file.
* *
* @param resource|string $pFilename * @param resource|string $filename
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -99,7 +99,7 @@ class Csv extends BaseWriter
Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
// Open file // Open file
$this->openFileHandle($pFilename); $this->openFileHandle($filename);
if ($this->excelCompatibility) { if ($this->excelCompatibility) {
$this->setUseBOM(true); // Enforce UTF-8 BOM Header $this->setUseBOM(true); // Enforce UTF-8 BOM Header

View File

@ -152,14 +152,14 @@ class Html extends BaseWriter
/** /**
* Save Spreadsheet to file. * Save Spreadsheet to file.
* *
* @param resource|string $pFilename * @param resource|string $filename
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
$this->processFlags($flags); $this->processFlags($flags);
// Open file // Open file
$this->openFileHandle($pFilename); $this->openFileHandle($filename);
// Write html // Write html
fwrite($this->fileHandle, $this->generateHTMLAll()); fwrite($this->fileHandle, $this->generateHTMLAll());
@ -551,20 +551,19 @@ class Html extends BaseWriter
* Jpgraph code issuing warnings. So, don't measure * Jpgraph code issuing warnings. So, don't measure
* code coverage for this function till that is fixed. * code coverage for this function till that is fixed.
* *
* @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param int $row Row to check for charts * @param int $row Row to check for charts
* *
* @return array * @return array
* *
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
private function extendRowsForCharts(Worksheet $pSheet, int $row) private function extendRowsForCharts(Worksheet $worksheet, int $row)
{ {
$rowMax = $row; $rowMax = $row;
$colMax = 'A'; $colMax = 'A';
$anyfound = false; $anyfound = false;
if ($this->includeCharts) { if ($this->includeCharts) {
foreach ($pSheet->getChartCollection() as $chart) { foreach ($worksheet->getChartCollection() as $chart) {
if ($chart instanceof Chart) { if ($chart instanceof Chart) {
$anyfound = true; $anyfound = true;
$chartCoordinates = $chart->getTopLeftPosition(); $chartCoordinates = $chart->getTopLeftPosition();
@ -583,11 +582,11 @@ class Html extends BaseWriter
return [$rowMax, $colMax, $anyfound]; return [$rowMax, $colMax, $anyfound];
} }
private function extendRowsForChartsAndImages(Worksheet $pSheet, int $row): string private function extendRowsForChartsAndImages(Worksheet $worksheet, int $row): string
{ {
[$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($pSheet, $row); [$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($worksheet, $row);
foreach ($pSheet->getDrawingCollection() as $drawing) { foreach ($worksheet->getDrawingCollection() as $drawing) {
$anyfound = true; $anyfound = true;
$imageTL = Coordinate::coordinateFromString($drawing->getCoordinates()); $imageTL = Coordinate::coordinateFromString($drawing->getCoordinates());
$imageCol = Coordinate::columnIndexFromString($imageTL[0]); $imageCol = Coordinate::columnIndexFromString($imageTL[0]);
@ -610,8 +609,8 @@ class Html extends BaseWriter
while ($row <= $rowMax) { while ($row <= $rowMax) {
$html .= '<tr>'; $html .= '<tr>';
for ($col = 'A'; $col != $colMax; ++$col) { for ($col = 'A'; $col != $colMax; ++$col) {
$htmlx = $this->writeImageInCell($pSheet, $col . $row); $htmlx = $this->writeImageInCell($worksheet, $col . $row);
$htmlx .= $this->includeCharts ? $this->writeChartInCell($pSheet, $col . $row) : ''; $htmlx .= $this->includeCharts ? $this->writeChartInCell($worksheet, $col . $row) : '';
if ($htmlx) { if ($htmlx) {
$html .= "<td class='style0' style='position: relative;'>$htmlx</td>"; $html .= "<td class='style0' style='position: relative;'>$htmlx</td>";
} else { } else {
@ -645,18 +644,18 @@ class Html extends BaseWriter
/** /**
* Generate image tag in cell. * Generate image tag in cell.
* *
* @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param Worksheet $worksheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param string $coordinates Cell coordinates * @param string $coordinates Cell coordinates
* *
* @return string * @return string
*/ */
private function writeImageInCell(Worksheet $pSheet, $coordinates) private function writeImageInCell(Worksheet $worksheet, $coordinates)
{ {
// Construct HTML // Construct HTML
$html = ''; $html = '';
// Write images // Write images
foreach ($pSheet->getDrawingCollection() as $drawing) { foreach ($worksheet->getDrawingCollection() as $drawing) {
if ($drawing->getCoordinates() != $coordinates) { if ($drawing->getCoordinates() != $coordinates) {
continue; continue;
} }
@ -724,20 +723,15 @@ class Html extends BaseWriter
* Jpgraph code issuing warnings. So, don't measure * Jpgraph code issuing warnings. So, don't measure
* code coverage for this function till that is fixed. * code coverage for this function till that is fixed.
* *
* @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param string $coordinates Cell coordinates
*
* @return string
*
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
private function writeChartInCell(Worksheet $pSheet, $coordinates) private function writeChartInCell(Worksheet $worksheet, string $coordinates): string
{ {
// Construct HTML // Construct HTML
$html = ''; $html = '';
// Write charts // Write charts
foreach ($pSheet->getChartCollection() as $chart) { foreach ($worksheet->getChartCollection() as $chart) {
if ($chart instanceof Chart) { if ($chart instanceof Chart) {
$chartCoordinates = $chart->getTopLeftPosition(); $chartCoordinates = $chart->getTopLeftPosition();
if ($chartCoordinates['cell'] == $coordinates) { if ($chartCoordinates['cell'] == $coordinates) {
@ -1117,13 +1111,13 @@ class Html extends BaseWriter
return $html; return $html;
} }
private function generateTableTagInline($pSheet, $id) private function generateTableTagInline(Worksheet $worksheet, $id)
{ {
$style = isset($this->cssStyles['table']) ? $style = isset($this->cssStyles['table']) ?
$this->assembleCSS($this->cssStyles['table']) : ''; $this->assembleCSS($this->cssStyles['table']) : '';
$prntgrid = $pSheet->getPrintGridlines(); $prntgrid = $worksheet->getPrintGridlines();
$viewgrid = $this->isPdf ? $prntgrid : $pSheet->getShowGridlines(); $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines();
if ($viewgrid && $prntgrid) { if ($viewgrid && $prntgrid) {
$html = " <table border='1' cellpadding='1' $id cellspacing='1' style='$style' class='gridlines gridlinesp'>" . PHP_EOL; $html = " <table border='1' cellpadding='1' $id cellspacing='1' style='$style' class='gridlines gridlinesp'>" . PHP_EOL;
} elseif ($viewgrid) { } elseif ($viewgrid) {
@ -1137,28 +1131,28 @@ class Html extends BaseWriter
return $html; return $html;
} }
private function generateTableTag($pSheet, $id, &$html, $sheetIndex): void private function generateTableTag(Worksheet $worksheet, $id, &$html, $sheetIndex): void
{ {
if (!$this->useInlineCss) { if (!$this->useInlineCss) {
$gridlines = $pSheet->getShowGridlines() ? ' gridlines' : ''; $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : '';
$gridlinesp = $pSheet->getPrintGridlines() ? ' gridlinesp' : ''; $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : '';
$html .= " <table border='0' cellpadding='0' cellspacing='0' $id class='sheet$sheetIndex$gridlines$gridlinesp'>" . PHP_EOL; $html .= " <table border='0' cellpadding='0' cellspacing='0' $id class='sheet$sheetIndex$gridlines$gridlinesp'>" . PHP_EOL;
} else { } else {
$html .= $this->generateTableTagInline($pSheet, $id); $html .= $this->generateTableTagInline($worksheet, $id);
} }
} }
/** /**
* Generate table header. * Generate table header.
* *
* @param Worksheet $pSheet The worksheet for the table we are writing * @param Worksheet $worksheet The worksheet for the table we are writing
* @param bool $showid whether or not to add id to table tag * @param bool $showid whether or not to add id to table tag
* *
* @return string * @return string
*/ */
private function generateTableHeader($pSheet, $showid = true) private function generateTableHeader(Worksheet $worksheet, $showid = true)
{ {
$sheetIndex = $pSheet->getParent()->getIndex($pSheet); $sheetIndex = $worksheet->getParent()->getIndex($worksheet);
// Construct HTML // Construct HTML
$html = ''; $html = '';
@ -1169,10 +1163,10 @@ class Html extends BaseWriter
$html .= "<div style='page: page$sheetIndex' class='scrpgbrk'>\n"; $html .= "<div style='page: page$sheetIndex' class='scrpgbrk'>\n";
} }
$this->generateTableTag($pSheet, $id, $html, $sheetIndex); $this->generateTableTag($worksheet, $id, $html, $sheetIndex);
// Write <col> elements // Write <col> elements
$highestColumnIndex = Coordinate::columnIndexFromString($pSheet->getHighestColumn()) - 1; $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1;
$i = -1; $i = -1;
while ($i++ < $highestColumnIndex) { while ($i++ < $highestColumnIndex) {
if (!$this->useInlineCss) { if (!$this->useInlineCss) {
@ -1198,17 +1192,16 @@ class Html extends BaseWriter
/** /**
* Generate row start. * Generate row start.
* *
* @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param int $sheetIndex Sheet index (0-based) * @param int $sheetIndex Sheet index (0-based)
* @param int $pRow row number * @param int $pRow row number
* *
* @return string * @return string
*/ */
private function generateRowStart(Worksheet $pSheet, $sheetIndex, $pRow) private function generateRowStart(Worksheet $worksheet, $sheetIndex, $pRow)
{ {
$html = ''; $html = '';
if (count($pSheet->getBreaks()) > 0) { if (count($worksheet->getBreaks()) > 0) {
$breaks = $pSheet->getBreaks(); $breaks = $worksheet->getBreaks();
// check if a break is needed before this row // check if a break is needed before this row
if (isset($breaks['A' . $pRow])) { if (isset($breaks['A' . $pRow])) {
@ -1219,7 +1212,7 @@ class Html extends BaseWriter
} }
// open table again: <table> + <col> etc. // open table again: <table> + <col> etc.
$html .= $this->generateTableHeader($pSheet, false); $html .= $this->generateTableHeader($worksheet, false);
$html .= '<tbody>' . PHP_EOL; $html .= '<tbody>' . PHP_EOL;
} }
} }
@ -1237,9 +1230,9 @@ class Html extends BaseWriter
return $html; return $html;
} }
private function generateRowCellCss($pSheet, $cellAddress, $pRow, $colNum) private function generateRowCellCss(Worksheet $worksheet, $cellAddress, $pRow, $colNum)
{ {
$cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : ''; $cell = ($cellAddress > '') ? $worksheet->getCell($cellAddress) : '';
$coordinate = Coordinate::stringFromColumnIndex($colNum + 1) . ($pRow + 1); $coordinate = Coordinate::stringFromColumnIndex($colNum + 1) . ($pRow + 1);
if (!$this->useInlineCss) { if (!$this->useInlineCss) {
$cssClass = 'column' . $colNum; $cssClass = 'column' . $colNum;
@ -1296,39 +1289,43 @@ class Html extends BaseWriter
} }
} }
private function generateRowCellDataValue($pSheet, $cell, &$cellData): void private function generateRowCellDataValue(Worksheet $worksheet, $cell, &$cellData): void
{ {
if ($cell->getValue() instanceof RichText) { if ($cell->getValue() instanceof RichText) {
$this->generateRowCellDataValueRich($cell, $cellData); $this->generateRowCellDataValueRich($cell, $cellData);
} else { } else {
$origData = $this->preCalculateFormulas ? $cell->getCalculatedValue() : $cell->getValue(); $origData = $this->preCalculateFormulas ? $cell->getCalculatedValue() : $cell->getValue();
$formatCode = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode();
if ($formatCode !== null) {
$cellData = NumberFormat::toFormattedString( $cellData = NumberFormat::toFormattedString(
$origData, $origData,
$pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(), $formatCode,
[$this, 'formatColor'] [$this, 'formatColor']
); );
}
if ($cellData === $origData) { if ($cellData === $origData) {
$cellData = htmlspecialchars($cellData ?? '', Settings::htmlEntityFlags()); $cellData = htmlspecialchars($cellData ?? '', Settings::htmlEntityFlags());
} }
if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) { if ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) {
$cellData = '<sup>' . $cellData . '</sup>'; $cellData = '<sup>' . $cellData . '</sup>';
} elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) { } elseif ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) {
$cellData = '<sub>' . $cellData . '</sub>'; $cellData = '<sub>' . $cellData . '</sub>';
} }
} }
} }
private function generateRowCellData($pSheet, $cell, &$cssClass, $cellType) private function generateRowCellData(Worksheet $worksheet, $cell, &$cssClass, $cellType)
{ {
$cellData = '&nbsp;'; $cellData = '&nbsp;';
if ($cell instanceof Cell) { if ($cell instanceof Cell) {
$cellData = ''; $cellData = '';
// Don't know what this does, and no test cases. // Don't know what this does, and no test cases.
//if ($cell->getParent() === null) { //if ($cell->getParent() === null) {
// $cell->attach($pSheet); // $cell->attach($worksheet);
//} //}
// Value // Value
$this->generateRowCellDataValue($pSheet, $cell, $cellData); $this->generateRowCellDataValue($worksheet, $cell, $cellData);
// Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp; // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
// Example: " Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world" // Example: " Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
@ -1353,7 +1350,7 @@ class Html extends BaseWriter
} }
// General horizontal alignment: Actual horizontal alignment depends on dataType // General horizontal alignment: Actual horizontal alignment depends on dataType
$sharedStyle = $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex()); $sharedStyle = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex());
if ( if (
$sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL $sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL
&& isset($this->cssStyles['.' . $cell->getDataType()]['text-align']) && isset($this->cssStyles['.' . $cell->getDataType()]['text-align'])
@ -1371,9 +1368,9 @@ class Html extends BaseWriter
return $cellData; return $cellData;
} }
private function generateRowIncludeCharts($pSheet, $coordinate) private function generateRowIncludeCharts(Worksheet $worksheet, $coordinate)
{ {
return $this->includeCharts ? $this->writeChartInCell($pSheet, $coordinate) : ''; return $this->includeCharts ? $this->writeChartInCell($worksheet, $coordinate) : '';
} }
private function generateRowSpans($html, $rowSpan, $colSpan) private function generateRowSpans($html, $rowSpan, $colSpan)
@ -1384,12 +1381,12 @@ class Html extends BaseWriter
return $html; return $html;
} }
private function generateRowWriteCell(&$html, $pSheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow): void private function generateRowWriteCell(&$html, Worksheet $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow): void
{ {
// Image? // Image?
$htmlx = $this->writeImageInCell($pSheet, $coordinate); $htmlx = $this->writeImageInCell($worksheet, $coordinate);
// Chart? // Chart?
$htmlx .= $this->generateRowIncludeCharts($pSheet, $coordinate); $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate);
// Column start // Column start
$html .= ' <' . $cellType; $html .= ' <' . $cellType;
if (!$this->useInlineCss && !$this->isPdf) { if (!$this->useInlineCss && !$this->isPdf) {
@ -1435,7 +1432,7 @@ class Html extends BaseWriter
$html .= '>'; $html .= '>';
$html .= $htmlx; $html .= $htmlx;
$html .= $this->writeComment($pSheet, $coordinate); $html .= $this->writeComment($worksheet, $coordinate);
// Cell data // Cell data
$html .= $cellData; $html .= $cellData;
@ -1447,44 +1444,43 @@ class Html extends BaseWriter
/** /**
* Generate row. * Generate row.
* *
* @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param array $pValues Array containing cells in a row * @param array $pValues Array containing cells in a row
* @param int $pRow Row number (0-based) * @param int $pRow Row number (0-based)
* @param string $cellType eg: 'td' * @param string $cellType eg: 'td'
* *
* @return string * @return string
*/ */
private function generateRow(Worksheet $pSheet, array $pValues, $pRow, $cellType) private function generateRow(Worksheet $worksheet, array $pValues, $pRow, $cellType)
{ {
// Sheet index // Sheet index
$sheetIndex = $pSheet->getParent()->getIndex($pSheet); $sheetIndex = $worksheet->getParent()->getIndex($worksheet);
$html = $this->generateRowStart($pSheet, $sheetIndex, $pRow); $html = $this->generateRowStart($worksheet, $sheetIndex, $pRow);
// Write cells // Write cells
$colNum = 0; $colNum = 0;
foreach ($pValues as $cellAddress) { foreach ($pValues as $cellAddress) {
[$cell, $cssClass, $coordinate] = $this->generateRowCellCss($pSheet, $cellAddress, $pRow, $colNum); [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $pRow, $colNum);
$colSpan = 1; $colSpan = 1;
$rowSpan = 1; $rowSpan = 1;
// Cell Data // Cell Data
$cellData = $this->generateRowCellData($pSheet, $cell, $cssClass, $cellType); $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass, $cellType);
// Hyperlink? // Hyperlink?
if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) { if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) {
$cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl(), Settings::htmlEntityFlags()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip(), Settings::htmlEntityFlags()) . '">' . $cellData . '</a>'; $cellData = '<a href="' . htmlspecialchars($worksheet->getHyperlink($coordinate)->getUrl(), Settings::htmlEntityFlags()) . '" title="' . htmlspecialchars($worksheet->getHyperlink($coordinate)->getTooltip(), Settings::htmlEntityFlags()) . '">' . $cellData . '</a>';
} }
// Should the cell be written or is it swallowed by a rowspan or colspan? // Should the cell be written or is it swallowed by a rowspan or colspan?
$writeCell = !(isset($this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]) $writeCell = !(isset($this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum])
&& $this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]); && $this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum]);
// Colspan and Rowspan // Colspan and Rowspan
$colspan = 1; $colspan = 1;
$rowspan = 1; $rowspan = 1;
if (isset($this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) { if (isset($this->isBaseCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum])) {
$spans = $this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]; $spans = $this->isBaseCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum];
$rowSpan = $spans['rowspan']; $rowSpan = $spans['rowspan'];
$colSpan = $spans['colspan']; $colSpan = $spans['colspan'];
@ -1492,13 +1488,13 @@ class Html extends BaseWriter
// relies on !important for non-none border declarations in createCSSStyleBorder // relies on !important for non-none border declarations in createCSSStyleBorder
$endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($pRow + $rowSpan); $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($pRow + $rowSpan);
if (!$this->useInlineCss) { if (!$this->useInlineCss) {
$cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex(); $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex();
} }
} }
// Write // Write
if ($writeCell) { if ($writeCell) {
$this->generateRowWriteCell($html, $pSheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow); $this->generateRowWriteCell($html, $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow);
} }
// Next column // Next column
@ -1770,12 +1766,12 @@ class Html extends BaseWriter
* *
* @return string * @return string
*/ */
private function writeComment(Worksheet $pSheet, $coordinate) private function writeComment(Worksheet $worksheet, $coordinate)
{ {
$result = ''; $result = '';
if (!$this->isPdf && isset($pSheet->getComments()[$coordinate])) { if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) {
$sanitizer = new HTMLPurifier(); $sanitizer = new HTMLPurifier();
$sanitizedString = $sanitizer->purify($pSheet->getComment($coordinate)->getText()->getPlainText()); $sanitizedString = $sanitizer->purify($worksheet->getComment($coordinate)->getText()->getPlainText());
if ($sanitizedString !== '') { if ($sanitizedString !== '') {
$result .= '<a class="comment-indicator"></a>'; $result .= '<a class="comment-indicator"></a>';
$result .= '<div class="comment">' . nl2br($sanitizedString) . '</div>'; $result .= '<div class="comment">' . nl2br($sanitizedString) . '</div>';
@ -1811,17 +1807,17 @@ class Html extends BaseWriter
// Loop all sheets // Loop all sheets
$sheetId = 0; $sheetId = 0;
foreach ($sheets as $pSheet) { foreach ($sheets as $worksheet) {
$htmlPage .= "@page page$sheetId { "; $htmlPage .= "@page page$sheetId { ";
$left = StringHelper::formatNumber($pSheet->getPageMargins()->getLeft()) . 'in; '; $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; ';
$htmlPage .= 'margin-left: ' . $left; $htmlPage .= 'margin-left: ' . $left;
$right = StringHelper::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; '; $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; ';
$htmlPage .= 'margin-right: ' . $right; $htmlPage .= 'margin-right: ' . $right;
$top = StringHelper::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; '; $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; ';
$htmlPage .= 'margin-top: ' . $top; $htmlPage .= 'margin-top: ' . $top;
$bottom = StringHelper::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; '; $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; ';
$htmlPage .= 'margin-bottom: ' . $bottom; $htmlPage .= 'margin-bottom: ' . $bottom;
$orientation = $pSheet->getPageSetup()->getOrientation(); $orientation = $worksheet->getPageSetup()->getOrientation();
if ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE) { if ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE) {
$htmlPage .= 'size: landscape; '; $htmlPage .= 'size: landscape; ';
} elseif ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_PORTRAIT) { } elseif ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_PORTRAIT) {

View File

@ -10,6 +10,8 @@ interface IWriter
/** /**
* IWriter constructor. * IWriter constructor.
*
* @param Spreadsheet $spreadsheet The spreadsheet that we want to save using this Writer
*/ */
public function __construct(Spreadsheet $spreadsheet); public function __construct(Spreadsheet $spreadsheet);
@ -27,11 +29,11 @@ interface IWriter
* Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object. * 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. * Set to false (the default) to ignore charts.
* *
* @param bool $pValue * @param bool $includeCharts
* *
* @return IWriter * @return IWriter
*/ */
public function setIncludeCharts($pValue); public function setIncludeCharts($includeCharts);
/** /**
* Get Pre-Calculate Formulas flag * Get Pre-Calculate Formulas flag
@ -50,18 +52,18 @@ interface IWriter
* Set to true (the default) to advise the Writer to calculate all formulae on save * 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. * Set to false to prevent precalculation of formulae on save.
* *
* @param bool $pValue Pre-Calculate Formulas? * @param bool $precalculateFormulas Pre-Calculate Formulas?
* *
* @return IWriter * @return IWriter
*/ */
public function setPreCalculateFormulas($pValue); public function setPreCalculateFormulas($precalculateFormulas);
/** /**
* Save PhpSpreadsheet to file. * Save PhpSpreadsheet to file.
* *
* @param resource|string $pFilename Name of the file to save * @param resource|string $filename Name of the file to save
*/ */
public function save($pFilename, int $flags = 0): void; public function save($filename, int $flags = 0): void;
/** /**
* Get use disk caching where possible? * Get use disk caching where possible?
@ -73,12 +75,12 @@ interface IWriter
/** /**
* Set use disk caching where possible? * Set use disk caching where possible?
* *
* @param bool $pValue * @param bool $useDiskCache
* @param string $pDirectory Disk caching directory * @param string $cacheDirectory Disk caching directory
* *
* @return IWriter * @return IWriter
*/ */
public function setUseDiskCaching($pValue, $pDirectory = null); public function setUseDiskCaching($useDiskCache, $cacheDirectory = null);
/** /**
* Get disk caching directory. * Get disk caching directory.

View File

@ -113,9 +113,9 @@ class Ods extends BaseWriter
/** /**
* Save PhpSpreadsheet to file. * Save PhpSpreadsheet to file.
* *
* @param resource|string $pFilename * @param resource|string $filename
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
if (!$this->spreadSheet) { if (!$this->spreadSheet) {
throw new WriterException('PhpSpreadsheet object unassigned.'); throw new WriterException('PhpSpreadsheet object unassigned.');
@ -126,7 +126,7 @@ class Ods extends BaseWriter
// garbage collect // garbage collect
$this->spreadSheet->garbageCollect(); $this->spreadSheet->garbageCollect();
$this->openFileHandle($pFilename); $this->openFileHandle($filename);
$zip = $this->createZip(); $zip = $this->createZip();

View File

@ -165,13 +165,13 @@ abstract class Pdf extends Html
/** /**
* Set Paper Size. * Set Paper Size.
* *
* @param int $pValue Paper size see PageSetup::PAPERSIZE_* * @param int $paperSize Paper size see PageSetup::PAPERSIZE_*
* *
* @return self * @return self
*/ */
public function setPaperSize($pValue) public function setPaperSize($paperSize)
{ {
$this->paperSize = $pValue; $this->paperSize = $paperSize;
return $this; return $this;
} }
@ -189,13 +189,13 @@ abstract class Pdf extends Html
/** /**
* Set Orientation. * Set Orientation.
* *
* @param string $pValue Page orientation see PageSetup::ORIENTATION_* * @param string $orientation Page orientation see PageSetup::ORIENTATION_*
* *
* @return self * @return self
*/ */
public function setOrientation($pValue) public function setOrientation($orientation)
{ {
$this->orientation = $pValue; $this->orientation = $orientation;
return $this; return $this;
} }
@ -213,16 +213,16 @@ abstract class Pdf extends Html
/** /**
* Set temporary storage directory. * Set temporary storage directory.
* *
* @param string $pValue Temporary storage directory * @param string $temporaryDirectory Temporary storage directory
* *
* @return self * @return self
*/ */
public function setTempDir($pValue) public function setTempDir($temporaryDirectory)
{ {
if (is_dir($pValue)) { if (is_dir($temporaryDirectory)) {
$this->tempDir = $pValue; $this->tempDir = $temporaryDirectory;
} else { } else {
throw new WriterException("Directory does not exist: $pValue"); throw new WriterException("Directory does not exist: $temporaryDirectory");
} }
return $this; return $this;
@ -231,14 +231,14 @@ abstract class Pdf extends Html
/** /**
* Save Spreadsheet to PDF file, pre-save. * Save Spreadsheet to PDF file, pre-save.
* *
* @param string $pFilename Name of the file to save as * @param string $filename Name of the file to save as
* *
* @return resource * @return resource
*/ */
protected function prepareForSave($pFilename) protected function prepareForSave($filename)
{ {
// Open file // Open file
$this->openFileHandle($pFilename); $this->openFileHandle($filename);
return $this->fileHandle; return $this->fileHandle;
} }

View File

@ -20,11 +20,11 @@ class Dompdf extends Pdf
/** /**
* Save Spreadsheet to file. * Save Spreadsheet to file.
* *
* @param string $pFilename Name of the file to save as * @param string $filename Name of the file to save as
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
$fileHandle = parent::prepareForSave($pFilename); $fileHandle = parent::prepareForSave($filename);
// Default PDF paper size // Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)

View File

@ -22,11 +22,11 @@ class Mpdf extends Pdf
/** /**
* Save Spreadsheet to file. * Save Spreadsheet to file.
* *
* @param string $pFilename Name of the file to save as * @param string $filename Name of the file to save as
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
$fileHandle = parent::prepareForSave($pFilename); $fileHandle = parent::prepareForSave($filename);
// Default PDF paper size // Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)

View File

@ -36,11 +36,11 @@ class Tcpdf extends Pdf
/** /**
* Save Spreadsheet to file. * Save Spreadsheet to file.
* *
* @param string $pFilename Name of the file to save as * @param string $filename Name of the file to save as
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
$fileHandle = parent::prepareForSave($pFilename); $fileHandle = parent::prepareForSave($filename);
// Default PDF paper size // Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
@ -97,7 +97,7 @@ class Tcpdf extends Pdf
$pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator());
// Write to file // Write to file
fwrite($fileHandle, $pdf->output($pFilename, 'S')); fwrite($fileHandle, $pdf->output($filename, 'S'));
parent::restoreStateAfterSave(); parent::restoreStateAfterSave();
} }

View File

@ -117,9 +117,9 @@ class Xls extends BaseWriter
/** /**
* Save Spreadsheet to file. * Save Spreadsheet to file.
* *
* @param resource|string $pFilename * @param resource|string $filename
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -224,7 +224,7 @@ class Xls extends BaseWriter
$time = $this->spreadsheet->getProperties()->getModified(); $time = $this->spreadsheet->getProperties()->getModified();
$root = new Root($time, $time, $arrRootData); $root = new Root($time, $time, $arrRootData);
// save the OLE file // save the OLE file
$this->openFileHandle($pFilename); $this->openFileHandle($filename);
$root->save($this->fileHandle); $root->save($this->fileHandle);
$this->maybeCloseFileHandle(); $this->maybeCloseFileHandle();

View File

@ -600,7 +600,11 @@ class Workbook extends BIFFwriter
} }
if ($definedName->getLocalOnly()) { if ($definedName->getLocalOnly()) {
// local scope /**
* local scope.
*
* @phpstan-ignore-next-line
*/
$scope = $this->spreadsheet->getIndex($definedName->getScope()) + 1; $scope = $this->spreadsheet->getIndex($definedName->getScope()) + 1;
} else { } else {
// global scope // global scope

View File

@ -284,9 +284,9 @@ class Xlsx extends BaseWriter
/** /**
* Save PhpSpreadsheet to file. * Save PhpSpreadsheet to file.
* *
* @param resource|string $pFilename * @param resource|string $filename
*/ */
public function save($pFilename, int $flags = 0): void public function save($filename, int $flags = 0): void
{ {
$this->processFlags($flags); $this->processFlags($flags);
@ -503,7 +503,7 @@ class Xlsx extends BaseWriter
Functions::setReturnDateType($saveDateReturnType); Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
$this->openFileHandle($pFilename); $this->openFileHandle($filename);
$options = new Archive(); $options = new Archive();
$options->setEnableZip64(false); $options->setEnableZip64(false);

View File

@ -75,7 +75,7 @@ class Chart extends WriterPart
$objWriter->writeAttribute('val', 0); $objWriter->writeAttribute('val', 0);
$objWriter->endElement(); $objWriter->endElement();
$this->writePlotArea($objWriter, $pChart->getWorksheet(), $pChart->getPlotArea(), $pChart->getXAxisLabel(), $pChart->getYAxisLabel(), $pChart->getChartAxisX(), $pChart->getChartAxisY(), $pChart->getMajorGridlines(), $pChart->getMinorGridlines()); $this->writePlotArea($objWriter, $pChart->getPlotArea(), $pChart->getXAxisLabel(), $pChart->getYAxisLabel(), $pChart->getChartAxisX(), $pChart->getChartAxisY(), $pChart->getMajorGridlines(), $pChart->getMinorGridlines());
$this->writeLegend($objWriter, $pChart->getLegend()); $this->writeLegend($objWriter, $pChart->getLegend());
@ -202,7 +202,7 @@ class Chart extends WriterPart
* @param Axis $xAxis * @param Axis $xAxis
* @param Axis $yAxis * @param Axis $yAxis
*/ */
private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pSheet, PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null): void private function writePlotArea(XMLWriter $objWriter, PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null): void
{ {
if ($plotArea === null) { if ($plotArea === null) {
return; return;

View File

@ -98,14 +98,14 @@ class DefinedNames
/** /**
* Write Defined Name for autoFilter. * Write Defined Name for autoFilter.
*/ */
private function writeNamedRangeForAutofilter(Worksheet $pSheet, int $pSheetId = 0): void private function writeNamedRangeForAutofilter(Worksheet $worksheet, int $worksheetId = 0): void
{ {
// NamedRange for autoFilter // NamedRange for autoFilter
$autoFilterRange = $pSheet->getAutoFilter()->getRange(); $autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) { if (!empty($autoFilterRange)) {
$this->objWriter->startElement('definedName'); $this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
$this->objWriter->writeAttribute('localSheetId', "$pSheetId"); $this->objWriter->writeAttribute('localSheetId', "$worksheetId");
$this->objWriter->writeAttribute('hidden', '1'); $this->objWriter->writeAttribute('hidden', '1');
// Create absolute coordinate and write as raw text // Create absolute coordinate and write as raw text
@ -118,7 +118,7 @@ class DefinedNames
$range[1] = Coordinate::absoluteCoordinate($range[1]); $range[1] = Coordinate::absoluteCoordinate($range[1]);
$range = implode(':', $range); $range = implode(':', $range);
$this->objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle() ?? '') . '\'!' . $range); $this->objWriter->writeRawData('\'' . str_replace("'", "''", $worksheet->getTitle() ?? '') . '\'!' . $range);
$this->objWriter->endElement(); $this->objWriter->endElement();
} }
@ -127,33 +127,33 @@ class DefinedNames
/** /**
* Write Defined Name for PrintTitles. * Write Defined Name for PrintTitles.
*/ */
private function writeNamedRangeForPrintTitles(Worksheet $pSheet, int $pSheetId = 0): void private function writeNamedRangeForPrintTitles(Worksheet $worksheet, int $worksheetId = 0): void
{ {
// NamedRange for PrintTitles // NamedRange for PrintTitles
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
$this->objWriter->startElement('definedName'); $this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Titles'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles');
$this->objWriter->writeAttribute('localSheetId', "$pSheetId"); $this->objWriter->writeAttribute('localSheetId', "$worksheetId");
// Setting string // Setting string
$settingString = ''; $settingString = '';
// Columns to repeat // Columns to repeat
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft(); $repeat = $worksheet->getPageSetup()->getColumnsToRepeatAtLeft();
$settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
} }
// Rows to repeat // Rows to repeat
if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { if ($worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$settingString .= ','; $settingString .= ',';
} }
$repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop(); $repeat = $worksheet->getPageSetup()->getRowsToRepeatAtTop();
$settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
} }
$this->objWriter->writeRawData($settingString); $this->objWriter->writeRawData($settingString);
@ -165,22 +165,22 @@ class DefinedNames
/** /**
* Write Defined Name for PrintTitles. * Write Defined Name for PrintTitles.
*/ */
private function writeNamedRangeForPrintArea(Worksheet $pSheet, int $pSheetId = 0): void private function writeNamedRangeForPrintArea(Worksheet $worksheet, int $worksheetId = 0): void
{ {
// NamedRange for PrintArea // NamedRange for PrintArea
if ($pSheet->getPageSetup()->isPrintAreaSet()) { if ($worksheet->getPageSetup()->isPrintAreaSet()) {
$this->objWriter->startElement('definedName'); $this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Area'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Area');
$this->objWriter->writeAttribute('localSheetId', "$pSheetId"); $this->objWriter->writeAttribute('localSheetId', "$worksheetId");
// Print area // Print area
$printArea = Coordinate::splitRange($pSheet->getPageSetup()->getPrintArea()); $printArea = Coordinate::splitRange($worksheet->getPageSetup()->getPrintArea());
$chunks = []; $chunks = [];
foreach ($printArea as $printAreaRect) { foreach ($printArea as $printAreaRect) {
$printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]);
$printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]); $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]);
$chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect); $chunks[] = '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
} }
$this->objWriter->writeRawData(implode(',', $chunks)); $this->objWriter->writeRawData(implode(',', $chunks));

View File

@ -14,12 +14,12 @@ class StringTable extends WriterPart
/** /**
* Create worksheet stringtable. * Create worksheet stringtable.
* *
* @param Worksheet $pSheet Worksheet * @param Worksheet $worksheet Worksheet
* @param string[] $pExistingTable Existing table to eventually merge with * @param string[] $existingTable Existing table to eventually merge with
* *
* @return string[] String table for worksheet * @return string[] String table for worksheet
*/ */
public function createStringTable(Worksheet $pSheet, $pExistingTable = null) public function createStringTable(Worksheet $worksheet, $existingTable = null)
{ {
// Create string lookup table // Create string lookup table
$aStringTable = []; $aStringTable = [];
@ -27,16 +27,16 @@ class StringTable extends WriterPart
$aFlippedStringTable = null; // For faster lookup $aFlippedStringTable = null; // For faster lookup
// Is an existing table given? // Is an existing table given?
if (($pExistingTable !== null) && is_array($pExistingTable)) { if (($existingTable !== null) && is_array($existingTable)) {
$aStringTable = $pExistingTable; $aStringTable = $existingTable;
} }
// Fill index array // Fill index array
$aFlippedStringTable = $this->flipStringTable($aStringTable); $aFlippedStringTable = $this->flipStringTable($aStringTable);
// Loop through cells // Loop through cells
foreach ($pSheet->getCoordinates() as $coordinate) { foreach ($worksheet->getCoordinates() as $coordinate) {
$cell = $pSheet->getCell($coordinate); $cell = $worksheet->getCell($coordinate);
$cellValue = $cell->getValue(); $cellValue = $cell->getValue();
if ( if (
!is_object($cellValue) && !is_object($cellValue) &&

View File

@ -201,22 +201,22 @@ class Workbook extends WriterPart
* Write sheet. * Write sheet.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param string $pSheetname Sheet name * @param string $worksheetName Sheet name
* @param int $pSheetId Sheet id * @param int $worksheetId Sheet id
* @param int $pRelId Relationship ID * @param int $relId Relationship ID
* @param string $sheetState Sheet state (visible, hidden, veryHidden) * @param string $sheetState Sheet state (visible, hidden, veryHidden)
*/ */
private function writeSheet(XMLWriter $objWriter, $pSheetname, $pSheetId = 1, $pRelId = 1, $sheetState = 'visible'): void private function writeSheet(XMLWriter $objWriter, $worksheetName, $worksheetId = 1, $relId = 1, $sheetState = 'visible'): void
{ {
if ($pSheetname != '') { if ($worksheetName != '') {
// Write sheet // Write sheet
$objWriter->startElement('sheet'); $objWriter->startElement('sheet');
$objWriter->writeAttribute('name', $pSheetname); $objWriter->writeAttribute('name', $worksheetName);
$objWriter->writeAttribute('sheetId', $pSheetId); $objWriter->writeAttribute('sheetId', $worksheetId);
if ($sheetState !== 'visible' && $sheetState != '') { if ($sheetState !== 'visible' && $sheetState != '') {
$objWriter->writeAttribute('state', $sheetState); $objWriter->writeAttribute('state', $sheetState);
} }
$objWriter->writeAttribute('r:id', 'rId' . $pRelId); $objWriter->writeAttribute('r:id', 'rId' . $relId);
$objWriter->endElement(); $objWriter->endElement();
} else { } else {
throw new WriterException('Invalid parameters passed.'); throw new WriterException('Invalid parameters passed.');

View File

@ -26,7 +26,7 @@ class Worksheet extends WriterPart
* *
* @return string XML Output * @return string XML Output
*/ */
public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = null, $includeCharts = false) public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, $pStringTable = null, $includeCharts = false)
{ {
// Create XML writer // Create XML writer
$objWriter = null; $objWriter = null;
@ -53,76 +53,76 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('xmlns:x14ac', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'); $objWriter->writeAttribute('xmlns:x14ac', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac');
// sheetPr // sheetPr
$this->writeSheetPr($objWriter, $pSheet); $this->writeSheetPr($objWriter, $worksheet);
// Dimension // Dimension
$this->writeDimension($objWriter, $pSheet); $this->writeDimension($objWriter, $worksheet);
// sheetViews // sheetViews
$this->writeSheetViews($objWriter, $pSheet); $this->writeSheetViews($objWriter, $worksheet);
// sheetFormatPr // sheetFormatPr
$this->writeSheetFormatPr($objWriter, $pSheet); $this->writeSheetFormatPr($objWriter, $worksheet);
// cols // cols
$this->writeCols($objWriter, $pSheet); $this->writeCols($objWriter, $worksheet);
// sheetData // sheetData
$this->writeSheetData($objWriter, $pSheet, $pStringTable); $this->writeSheetData($objWriter, $worksheet, $pStringTable);
// sheetProtection // sheetProtection
$this->writeSheetProtection($objWriter, $pSheet); $this->writeSheetProtection($objWriter, $worksheet);
// protectedRanges // protectedRanges
$this->writeProtectedRanges($objWriter, $pSheet); $this->writeProtectedRanges($objWriter, $worksheet);
// autoFilter // autoFilter
$this->writeAutoFilter($objWriter, $pSheet); $this->writeAutoFilter($objWriter, $worksheet);
// mergeCells // mergeCells
$this->writeMergeCells($objWriter, $pSheet); $this->writeMergeCells($objWriter, $worksheet);
// conditionalFormatting // conditionalFormatting
$this->writeConditionalFormatting($objWriter, $pSheet); $this->writeConditionalFormatting($objWriter, $worksheet);
// dataValidations moved to end // dataValidations
//$this->writeDataValidations($objWriter, $pSheet); $this->writeDataValidations($objWriter, $worksheet);
// hyperlinks // hyperlinks
$this->writeHyperlinks($objWriter, $pSheet); $this->writeHyperlinks($objWriter, $worksheet);
// Print options // Print options
$this->writePrintOptions($objWriter, $pSheet); $this->writePrintOptions($objWriter, $worksheet);
// Page margins // Page margins
$this->writePageMargins($objWriter, $pSheet); $this->writePageMargins($objWriter, $worksheet);
// Page setup // Page setup
$this->writePageSetup($objWriter, $pSheet); $this->writePageSetup($objWriter, $worksheet);
// Header / footer // Header / footer
$this->writeHeaderFooter($objWriter, $pSheet); $this->writeHeaderFooter($objWriter, $worksheet);
// Breaks // Breaks
$this->writeBreaks($objWriter, $pSheet); $this->writeBreaks($objWriter, $worksheet);
// Drawings and/or Charts // Drawings and/or Charts
$this->writeDrawings($objWriter, $pSheet, $includeCharts); $this->writeDrawings($objWriter, $worksheet, $includeCharts);
// LegacyDrawing // LegacyDrawing
$this->writeLegacyDrawing($objWriter, $pSheet); $this->writeLegacyDrawing($objWriter, $worksheet);
// LegacyDrawingHF // LegacyDrawingHF
$this->writeLegacyDrawingHF($objWriter, $pSheet); $this->writeLegacyDrawingHF($objWriter, $worksheet);
// AlternateContent // AlternateContent
$this->writeAlternateContent($objWriter, $pSheet); $this->writeAlternateContent($objWriter, $worksheet);
// ConditionalFormattingRuleExtensionList // ConditionalFormattingRuleExtensionList
// (Must be inserted last. Not insert last, an Excel parse error will occur) // (Must be inserted last. Not insert last, an Excel parse error will occur)
$this->writeExtLst($objWriter, $pSheet); $this->writeExtLst($objWriter, $worksheet);
// dataValidations // dataValidations
$this->writeDataValidations($objWriter, $pSheet); $this->writeDataValidations($objWriter, $worksheet);
$objWriter->endElement(); $objWriter->endElement();
@ -134,40 +134,40 @@ class Worksheet extends WriterPart
* Write SheetPr. * Write SheetPr.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// sheetPr // sheetPr
$objWriter->startElement('sheetPr'); $objWriter->startElement('sheetPr');
if ($pSheet->getParent()->hasMacros()) { if ($worksheet->getParent()->hasMacros()) {
//if the workbook have macros, we need to have codeName for the sheet //if the workbook have macros, we need to have codeName for the sheet
if (!$pSheet->hasCodeName()) { if (!$worksheet->hasCodeName()) {
$pSheet->setCodeName($pSheet->getTitle()); $worksheet->setCodeName($worksheet->getTitle());
} }
self::writeAttributeNotNull($objWriter, 'codeName', $pSheet->getCodeName()); self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName());
} }
$autoFilterRange = $pSheet->getAutoFilter()->getRange(); $autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) { if (!empty($autoFilterRange)) {
$objWriter->writeAttribute('filterMode', 1); $objWriter->writeAttribute('filterMode', 1);
$pSheet->getAutoFilter()->showHideRows(); $worksheet->getAutoFilter()->showHideRows();
} }
// tabColor // tabColor
if ($pSheet->isTabColorSet()) { if ($worksheet->isTabColorSet()) {
$objWriter->startElement('tabColor'); $objWriter->startElement('tabColor');
$objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB()); $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB());
$objWriter->endElement(); $objWriter->endElement();
} }
// outlinePr // outlinePr
$objWriter->startElement('outlinePr'); $objWriter->startElement('outlinePr');
$objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0')); $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0'));
$objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0')); $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0'));
$objWriter->endElement(); $objWriter->endElement();
// pageSetUpPr // pageSetUpPr
if ($pSheet->getPageSetup()->getFitToPage()) { if ($worksheet->getPageSetup()->getFitToPage()) {
$objWriter->startElement('pageSetUpPr'); $objWriter->startElement('pageSetUpPr');
$objWriter->writeAttribute('fitToPage', '1'); $objWriter->writeAttribute('fitToPage', '1');
$objWriter->endElement(); $objWriter->endElement();
@ -180,13 +180,12 @@ class Worksheet extends WriterPart
* Write Dimension. * Write Dimension.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// dimension // dimension
$objWriter->startElement('dimension'); $objWriter->startElement('dimension');
$objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension()); $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension());
$objWriter->endElement(); $objWriter->endElement();
} }
@ -194,16 +193,15 @@ class Worksheet extends WriterPart
* Write SheetViews. * Write SheetViews.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// sheetViews // sheetViews
$objWriter->startElement('sheetViews'); $objWriter->startElement('sheetViews');
// Sheet selected? // Sheet selected?
$sheetSelected = false; $sheetSelected = false;
if ($this->getParentWriter()->getSpreadsheet()->getIndex($pSheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) {
$sheetSelected = true; $sheetSelected = true;
} }
@ -213,50 +211,50 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('workbookViewId', '0'); $objWriter->writeAttribute('workbookViewId', '0');
// Zoom scales // Zoom scales
if ($pSheet->getSheetView()->getZoomScale() != 100) { if ($worksheet->getSheetView()->getZoomScale() != 100) {
$objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); $objWriter->writeAttribute('zoomScale', $worksheet->getSheetView()->getZoomScale());
} }
if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { if ($worksheet->getSheetView()->getZoomScaleNormal() != 100) {
$objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); $objWriter->writeAttribute('zoomScaleNormal', $worksheet->getSheetView()->getZoomScaleNormal());
} }
// Show zeros (Excel also writes this attribute only if set to false) // Show zeros (Excel also writes this attribute only if set to false)
if ($pSheet->getSheetView()->getShowZeros() === false) { if ($worksheet->getSheetView()->getShowZeros() === false) {
$objWriter->writeAttribute('showZeros', 0); $objWriter->writeAttribute('showZeros', 0);
} }
// View Layout Type // View Layout Type
if ($pSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) {
$objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView());
} }
// Gridlines // Gridlines
if ($pSheet->getShowGridlines()) { if ($worksheet->getShowGridlines()) {
$objWriter->writeAttribute('showGridLines', 'true'); $objWriter->writeAttribute('showGridLines', 'true');
} else { } else {
$objWriter->writeAttribute('showGridLines', 'false'); $objWriter->writeAttribute('showGridLines', 'false');
} }
// Row and column headers // Row and column headers
if ($pSheet->getShowRowColHeaders()) { if ($worksheet->getShowRowColHeaders()) {
$objWriter->writeAttribute('showRowColHeaders', '1'); $objWriter->writeAttribute('showRowColHeaders', '1');
} else { } else {
$objWriter->writeAttribute('showRowColHeaders', '0'); $objWriter->writeAttribute('showRowColHeaders', '0');
} }
// Right-to-left // Right-to-left
if ($pSheet->getRightToLeft()) { if ($worksheet->getRightToLeft()) {
$objWriter->writeAttribute('rightToLeft', 'true'); $objWriter->writeAttribute('rightToLeft', 'true');
} }
$topLeftCell = $pSheet->getTopLeftCell(); $topLeftCell = $worksheet->getTopLeftCell();
$activeCell = $pSheet->getActiveCell(); $activeCell = $worksheet->getActiveCell();
$sqref = $pSheet->getSelectedCells(); $sqref = $worksheet->getSelectedCells();
// Pane // Pane
$pane = ''; $pane = '';
if ($pSheet->getFreezePane()) { if ($worksheet->getFreezePane()) {
[$xSplit, $ySplit] = Coordinate::coordinateFromString($pSheet->getFreezePane() ?? ''); [$xSplit, $ySplit] = Coordinate::coordinateFromString($worksheet->getFreezePane() ?? '');
$xSplit = Coordinate::columnIndexFromString($xSplit); $xSplit = Coordinate::columnIndexFromString($xSplit);
--$xSplit; --$xSplit;
--$ySplit; --$ySplit;
@ -309,37 +307,36 @@ class Worksheet extends WriterPart
* Write SheetFormatPr. * Write SheetFormatPr.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// sheetFormatPr // sheetFormatPr
$objWriter->startElement('sheetFormatPr'); $objWriter->startElement('sheetFormatPr');
// Default row height // Default row height
if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) { if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) {
$objWriter->writeAttribute('customHeight', 'true'); $objWriter->writeAttribute('customHeight', 'true');
$objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($pSheet->getDefaultRowDimension()->getRowHeight())); $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight()));
} else { } else {
$objWriter->writeAttribute('defaultRowHeight', '14.4'); $objWriter->writeAttribute('defaultRowHeight', '14.4');
} }
// Set Zero Height row // Set Zero Height row
if ( if (
(string) $pSheet->getDefaultRowDimension()->getZeroHeight() === '1' || (string) $worksheet->getDefaultRowDimension()->getZeroHeight() === '1' ||
strtolower((string) $pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true' strtolower((string) $worksheet->getDefaultRowDimension()->getZeroHeight()) == 'true'
) { ) {
$objWriter->writeAttribute('zeroHeight', '1'); $objWriter->writeAttribute('zeroHeight', '1');
} }
// Default column width // Default column width
if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) { if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) {
$objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($pSheet->getDefaultColumnDimension()->getWidth())); $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth()));
} }
// Outline level - row // Outline level - row
$outlineLevelRow = 0; $outlineLevelRow = 0;
foreach ($pSheet->getRowDimensions() as $dimension) { foreach ($worksheet->getRowDimensions() as $dimension) {
if ($dimension->getOutlineLevel() > $outlineLevelRow) { if ($dimension->getOutlineLevel() > $outlineLevelRow) {
$outlineLevelRow = $dimension->getOutlineLevel(); $outlineLevelRow = $dimension->getOutlineLevel();
} }
@ -348,7 +345,7 @@ class Worksheet extends WriterPart
// Outline level - column // Outline level - column
$outlineLevelCol = 0; $outlineLevelCol = 0;
foreach ($pSheet->getColumnDimensions() as $dimension) { foreach ($worksheet->getColumnDimensions() as $dimension) {
if ($dimension->getOutlineLevel() > $outlineLevelCol) { if ($dimension->getOutlineLevel() > $outlineLevelCol) {
$outlineLevelCol = $dimension->getOutlineLevel(); $outlineLevelCol = $dimension->getOutlineLevel();
} }
@ -362,18 +359,18 @@ class Worksheet extends WriterPart
* Write Cols. * Write Cols.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// cols // cols
if (count($pSheet->getColumnDimensions()) > 0) { if (count($worksheet->getColumnDimensions()) > 0) {
$objWriter->startElement('cols'); $objWriter->startElement('cols');
$pSheet->calculateColumnWidths(); $worksheet->calculateColumnWidths();
// Loop through column dimensions // Loop through column dimensions
foreach ($pSheet->getColumnDimensions() as $colDimension) { foreach ($worksheet->getColumnDimensions() as $colDimension) {
// col // col
$objWriter->startElement('col'); $objWriter->startElement('col');
$objWriter->writeAttribute('min', Coordinate::columnIndexFromString($colDimension->getColumnIndex())); $objWriter->writeAttribute('min', Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
@ -398,7 +395,7 @@ class Worksheet extends WriterPart
} }
// Custom width? // Custom width?
if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) { if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) {
$objWriter->writeAttribute('customWidth', 'true'); $objWriter->writeAttribute('customWidth', 'true');
} }
@ -426,14 +423,13 @@ class Worksheet extends WriterPart
* Write SheetProtection. * Write SheetProtection.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// sheetProtection // sheetProtection
$objWriter->startElement('sheetProtection'); $objWriter->startElement('sheetProtection');
$protection = $pSheet->getProtection(); $protection = $worksheet->getProtection();
if ($protection->getAlgorithm()) { if ($protection->getAlgorithm()) {
$objWriter->writeAttribute('algorithmName', $protection->getAlgorithm()); $objWriter->writeAttribute('algorithmName', $protection->getAlgorithm());
@ -613,15 +609,14 @@ class Worksheet extends WriterPart
* Write ConditionalFormatting. * Write ConditionalFormatting.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// Conditional id // Conditional id
$id = 1; $id = 1;
// Loop through styles in the current worksheet // Loop through styles in the current worksheet
foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
foreach ($conditionalStyles as $conditional) { foreach ($conditionalStyles as $conditional) {
// WHY was this again? // WHY was this again?
// if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') { // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') {
@ -639,7 +634,7 @@ class Worksheet extends WriterPart
$objWriter, $objWriter,
($conditional->getConditionType() != Conditional::CONDITION_DATABAR), ($conditional->getConditionType() != Conditional::CONDITION_DATABAR),
'dxfId', 'dxfId',
$this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())
); );
$objWriter->writeAttribute('priority', $id++); $objWriter->writeAttribute('priority', $id++);
@ -680,12 +675,11 @@ class Worksheet extends WriterPart
* Write DataValidations. * Write DataValidations.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// Datavalidation collection // Datavalidation collection
$dataValidationCollection = $pSheet->getDataValidationCollection(); $dataValidationCollection = $worksheet->getDataValidationCollection();
// Write data validations? // Write data validations?
if (!empty($dataValidationCollection)) { if (!empty($dataValidationCollection)) {
@ -757,12 +751,11 @@ class Worksheet extends WriterPart
* Write Hyperlinks. * Write Hyperlinks.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// Hyperlink collection // Hyperlink collection
$hyperlinkCollection = $pSheet->getHyperlinkCollection(); $hyperlinkCollection = $worksheet->getHyperlinkCollection();
// Relation ID // Relation ID
$relationId = 1; $relationId = 1;
@ -798,16 +791,15 @@ class Worksheet extends WriterPart
* Write ProtectedRanges. * Write ProtectedRanges.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
if (count($pSheet->getProtectedCells()) > 0) { if (count($worksheet->getProtectedCells()) > 0) {
// protectedRanges // protectedRanges
$objWriter->startElement('protectedRanges'); $objWriter->startElement('protectedRanges');
// Loop protectedRanges // Loop protectedRanges
foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { foreach ($worksheet->getProtectedCells() as $protectedCell => $passwordHash) {
// protectedRange // protectedRange
$objWriter->startElement('protectedRange'); $objWriter->startElement('protectedRange');
$objWriter->writeAttribute('name', 'p' . md5($protectedCell)); $objWriter->writeAttribute('name', 'p' . md5($protectedCell));
@ -826,16 +818,15 @@ class Worksheet extends WriterPart
* Write MergeCells. * Write MergeCells.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
if (count($pSheet->getMergeCells()) > 0) { if (count($worksheet->getMergeCells()) > 0) {
// mergeCells // mergeCells
$objWriter->startElement('mergeCells'); $objWriter->startElement('mergeCells');
// Loop mergeCells // Loop mergeCells
foreach ($pSheet->getMergeCells() as $mergeCell) { foreach ($worksheet->getMergeCells() as $mergeCell) {
// mergeCell // mergeCell
$objWriter->startElement('mergeCell'); $objWriter->startElement('mergeCell');
$objWriter->writeAttribute('ref', $mergeCell); $objWriter->writeAttribute('ref', $mergeCell);
@ -850,21 +841,20 @@ class Worksheet extends WriterPart
* Write PrintOptions. * Write PrintOptions.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// printOptions // printOptions
$objWriter->startElement('printOptions'); $objWriter->startElement('printOptions');
$objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true' : 'false')); $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false'));
$objWriter->writeAttribute('gridLinesSet', 'true'); $objWriter->writeAttribute('gridLinesSet', 'true');
if ($pSheet->getPageSetup()->getHorizontalCentered()) { if ($worksheet->getPageSetup()->getHorizontalCentered()) {
$objWriter->writeAttribute('horizontalCentered', 'true'); $objWriter->writeAttribute('horizontalCentered', 'true');
} }
if ($pSheet->getPageSetup()->getVerticalCentered()) { if ($worksheet->getPageSetup()->getVerticalCentered()) {
$objWriter->writeAttribute('verticalCentered', 'true'); $objWriter->writeAttribute('verticalCentered', 'true');
} }
@ -875,18 +865,17 @@ class Worksheet extends WriterPart
* Write PageMargins. * Write PageMargins.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet
*/ */
private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// pageMargins // pageMargins
$objWriter->startElement('pageMargins'); $objWriter->startElement('pageMargins');
$objWriter->writeAttribute('left', StringHelper::formatNumber($pSheet->getPageMargins()->getLeft())); $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()));
$objWriter->writeAttribute('right', StringHelper::formatNumber($pSheet->getPageMargins()->getRight())); $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight()));
$objWriter->writeAttribute('top', StringHelper::formatNumber($pSheet->getPageMargins()->getTop())); $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop()));
$objWriter->writeAttribute('bottom', StringHelper::formatNumber($pSheet->getPageMargins()->getBottom())); $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom()));
$objWriter->writeAttribute('header', StringHelper::formatNumber($pSheet->getPageMargins()->getHeader())); $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader()));
$objWriter->writeAttribute('footer', StringHelper::formatNumber($pSheet->getPageMargins()->getFooter())); $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter()));
$objWriter->endElement(); $objWriter->endElement();
} }
@ -894,11 +883,11 @@ class Worksheet extends WriterPart
* Write AutoFilter. * Write AutoFilter.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
$autoFilterRange = $pSheet->getAutoFilter()->getRange(); $autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) { if (!empty($autoFilterRange)) {
// autoFilter // autoFilter
$objWriter->startElement('autoFilter'); $objWriter->startElement('autoFilter');
@ -912,13 +901,13 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('ref', str_replace('$', '', $range)); $objWriter->writeAttribute('ref', str_replace('$', '', $range));
$columns = $pSheet->getAutoFilter()->getColumns(); $columns = $worksheet->getAutoFilter()->getColumns();
if (count($columns) > 0) { if (count($columns) > 0) {
foreach ($columns as $columnID => $column) { foreach ($columns as $columnID => $column) {
$rules = $column->getRules(); $rules = $column->getRules();
if (count($rules) > 0) { if (count($rules) > 0) {
$objWriter->startElement('filterColumn'); $objWriter->startElement('filterColumn');
$objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); $objWriter->writeAttribute('colId', $worksheet->getAutoFilter()->getColumnOffset($columnID));
$objWriter->startElement($column->getFilterType()); $objWriter->startElement($column->getFilterType());
if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) { if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) {
@ -993,37 +982,37 @@ class Worksheet extends WriterPart
* Write PageSetup. * Write PageSetup.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// pageSetup // pageSetup
$objWriter->startElement('pageSetup'); $objWriter->startElement('pageSetup');
$objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize()); $objWriter->writeAttribute('paperSize', $worksheet->getPageSetup()->getPaperSize());
$objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation()); $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation());
if ($pSheet->getPageSetup()->getScale() !== null) { if ($worksheet->getPageSetup()->getScale() !== null) {
$objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale()); $objWriter->writeAttribute('scale', $worksheet->getPageSetup()->getScale());
} }
if ($pSheet->getPageSetup()->getFitToHeight() !== null) { if ($worksheet->getPageSetup()->getFitToHeight() !== null) {
$objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight()); $objWriter->writeAttribute('fitToHeight', $worksheet->getPageSetup()->getFitToHeight());
} else { } else {
$objWriter->writeAttribute('fitToHeight', '0'); $objWriter->writeAttribute('fitToHeight', '0');
} }
if ($pSheet->getPageSetup()->getFitToWidth() !== null) { if ($worksheet->getPageSetup()->getFitToWidth() !== null) {
$objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth()); $objWriter->writeAttribute('fitToWidth', $worksheet->getPageSetup()->getFitToWidth());
} else { } else {
$objWriter->writeAttribute('fitToWidth', '0'); $objWriter->writeAttribute('fitToWidth', '0');
} }
if ($pSheet->getPageSetup()->getFirstPageNumber() !== null) { if ($worksheet->getPageSetup()->getFirstPageNumber() !== null) {
$objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber()); $objWriter->writeAttribute('firstPageNumber', $worksheet->getPageSetup()->getFirstPageNumber());
$objWriter->writeAttribute('useFirstPageNumber', '1'); $objWriter->writeAttribute('useFirstPageNumber', '1');
} }
$objWriter->writeAttribute('pageOrder', $pSheet->getPageSetup()->getPageOrder()); $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder());
$getUnparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); $getUnparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData();
if (isset($getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId'])) { if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) {
$objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId']); $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']);
} }
$objWriter->endElement(); $objWriter->endElement();
@ -1033,23 +1022,23 @@ class Worksheet extends WriterPart
* Write Header / Footer. * Write Header / Footer.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// headerFooter // headerFooter
$objWriter->startElement('headerFooter'); $objWriter->startElement('headerFooter');
$objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
$objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
$objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
$objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
$objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader()); $objWriter->writeElement('oddHeader', $worksheet->getHeaderFooter()->getOddHeader());
$objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter()); $objWriter->writeElement('oddFooter', $worksheet->getHeaderFooter()->getOddFooter());
$objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader()); $objWriter->writeElement('evenHeader', $worksheet->getHeaderFooter()->getEvenHeader());
$objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter()); $objWriter->writeElement('evenFooter', $worksheet->getHeaderFooter()->getEvenFooter());
$objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader()); $objWriter->writeElement('firstHeader', $worksheet->getHeaderFooter()->getFirstHeader());
$objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter()); $objWriter->writeElement('firstFooter', $worksheet->getHeaderFooter()->getFirstFooter());
$objWriter->endElement(); $objWriter->endElement();
} }
@ -1057,14 +1046,14 @@ class Worksheet extends WriterPart
* Write Breaks. * Write Breaks.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// Get row and column breaks // Get row and column breaks
$aRowBreaks = []; $aRowBreaks = [];
$aColumnBreaks = []; $aColumnBreaks = [];
foreach ($pSheet->getBreaks() as $cell => $breakType) { foreach ($worksheet->getBreaks() as $cell => $breakType) {
if ($breakType == PhpspreadsheetWorksheet::BREAK_ROW) { if ($breakType == PhpspreadsheetWorksheet::BREAK_ROW) {
$aRowBreaks[] = $cell; $aRowBreaks[] = $cell;
} elseif ($breakType == PhpspreadsheetWorksheet::BREAK_COLUMN) { } elseif ($breakType == PhpspreadsheetWorksheet::BREAK_COLUMN) {
@ -1113,10 +1102,10 @@ class Worksheet extends WriterPart
* Write SheetData. * Write SheetData.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
* @param string[] $pStringTable String table * @param string[] $pStringTable String table
*/ */
private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, array $pStringTable): void private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $pStringTable): void
{ {
// Flipped stringtable, for faster index searching // Flipped stringtable, for faster index searching
$aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($pStringTable); $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($pStringTable);
@ -1125,14 +1114,14 @@ class Worksheet extends WriterPart
$objWriter->startElement('sheetData'); $objWriter->startElement('sheetData');
// Get column count // Get column count
$colCount = Coordinate::columnIndexFromString($pSheet->getHighestColumn()); $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn());
// Highest row number // Highest row number
$highestRow = $pSheet->getHighestRow(); $highestRow = $worksheet->getHighestRow();
// Loop through cells // Loop through cells
$cellsByRow = []; $cellsByRow = [];
foreach ($pSheet->getCoordinates() as $coordinate) { foreach ($worksheet->getCoordinates() as $coordinate) {
$cellAddress = Coordinate::coordinateFromString($coordinate); $cellAddress = Coordinate::coordinateFromString($coordinate);
$cellsByRow[$cellAddress[1]][] = $coordinate; $cellsByRow[$cellAddress[1]][] = $coordinate;
} }
@ -1140,7 +1129,7 @@ class Worksheet extends WriterPart
$currentRow = 0; $currentRow = 0;
while ($currentRow++ < $highestRow) { while ($currentRow++ < $highestRow) {
// Get row dimension // Get row dimension
$rowDimension = $pSheet->getRowDimension($currentRow); $rowDimension = $worksheet->getRowDimension($currentRow);
// Write current row? // Write current row?
$writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null; $writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null;
@ -1182,7 +1171,7 @@ class Worksheet extends WriterPart
if (isset($cellsByRow[$currentRow])) { if (isset($cellsByRow[$currentRow])) {
foreach ($cellsByRow[$currentRow] as $cellAddress) { foreach ($cellsByRow[$currentRow] as $cellAddress) {
// Write cell // Write cell
$this->writeCell($objWriter, $pSheet, $cellAddress, $aFlippedStringTable); $this->writeCell($objWriter, $worksheet, $cellAddress, $aFlippedStringTable);
} }
} }
@ -1298,14 +1287,14 @@ class Worksheet extends WriterPart
* Write Cell. * Write Cell.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
* @param string $pCellAddress Cell Address * @param string $pCellAddress Cell Address
* @param string[] $pFlippedStringTable String table (flipped), for faster index searching * @param string[] $pFlippedStringTable String table (flipped), for faster index searching
*/ */
private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, string $pCellAddress, array $pFlippedStringTable): void private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $pCellAddress, array $pFlippedStringTable): void
{ {
// Cell // Cell
$pCell = $pSheet->getCell($pCellAddress); $pCell = $worksheet->getCell($pCellAddress);
$objWriter->startElement('c'); $objWriter->startElement('c');
$objWriter->writeAttribute('r', $pCellAddress); $objWriter->writeAttribute('r', $pCellAddress);
@ -1353,15 +1342,15 @@ class Worksheet extends WriterPart
* Write Drawings. * Write Drawings.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
* @param bool $includeCharts Flag indicating if we should include drawing details for charts * @param bool $includeCharts Flag indicating if we should include drawing details for charts
*/ */
private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, $includeCharts = false): void private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, $includeCharts = false): void
{ {
$unparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData();
$hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']); $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']);
$chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0; $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0;
if ($chartCount == 0 && $pSheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) {
return; return;
} }
@ -1369,8 +1358,8 @@ class Worksheet extends WriterPart
$objWriter->startElement('drawing'); $objWriter->startElement('drawing');
$rId = 'rId1'; $rId = 'rId1';
if (isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds'])) { if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) {
$drawingOriginalIds = $unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']; $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'];
// take first. In future can be overriten // take first. In future can be overriten
// (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships) // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships)
$rId = reset($drawingOriginalIds); $rId = reset($drawingOriginalIds);
@ -1384,12 +1373,12 @@ class Worksheet extends WriterPart
* Write LegacyDrawing. * Write LegacyDrawing.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// If sheet contains comments, add the relationships // If sheet contains comments, add the relationships
if (count($pSheet->getComments()) > 0) { if (count($worksheet->getComments()) > 0) {
$objWriter->startElement('legacyDrawing'); $objWriter->startElement('legacyDrawing');
$objWriter->writeAttribute('r:id', 'rId_comments_vml1'); $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
$objWriter->endElement(); $objWriter->endElement();
@ -1400,25 +1389,25 @@ class Worksheet extends WriterPart
* Write LegacyDrawingHF. * Write LegacyDrawingHF.
* *
* @param XMLWriter $objWriter XML Writer * @param XMLWriter $objWriter XML Writer
* @param PhpspreadsheetWorksheet $pSheet Worksheet * @param PhpspreadsheetWorksheet $worksheet Worksheet
*/ */
private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
// If sheet contains images, add the relationships // If sheet contains images, add the relationships
if (count($pSheet->getHeaderFooter()->getImages()) > 0) { if (count($worksheet->getHeaderFooter()->getImages()) > 0) {
$objWriter->startElement('legacyDrawingHF'); $objWriter->startElement('legacyDrawingHF');
$objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
$objWriter->endElement(); $objWriter->endElement();
} }
} }
private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
if (empty($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'])) { if (empty($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'])) {
return; return;
} }
foreach ($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'] as $alternateContent) { foreach ($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) {
$objWriter->writeRaw($alternateContent); $objWriter->writeRaw($alternateContent);
} }
} }
@ -1429,13 +1418,14 @@ class Worksheet extends WriterPart
* *
* @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627
*/ */
private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{ {
$conditionalFormattingRuleExtList = []; $conditionalFormattingRuleExtList = [];
foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
/** @var Conditional $conditional */ /** @var Conditional $conditional */
foreach ($conditionalStyles as $conditional) { foreach ($conditionalStyles as $conditional) {
$dataBar = $conditional->getDataBar(); $dataBar = $conditional->getDataBar();
// @phpstan-ignore-next-line
if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) { if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) {
$conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt(); $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt();
} }

View File

@ -0,0 +1,86 @@
<?php
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\TextElement;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PHPUnit\Framework\TestCase;
class CommentTest extends TestCase
{
public function testCreateComment(): void
{
$comment = new Comment();
self::assertEquals('Author', $comment->getAuthor());
self::assertEquals('96pt', $comment->getWidth());
self::assertEquals('59.25pt', $comment->getMarginLeft());
self::assertEquals('1.5pt', $comment->getMarginTop());
self::assertEquals('55.5pt', $comment->getHeight());
self::assertInstanceOf(Color::class, $comment->getFillColor());
self::assertEquals('FFFFFFE1', $comment->getFillColor()->getARGB());
self::assertInstanceOf(RichText::class, $comment->getText());
self::assertEquals(Alignment::HORIZONTAL_GENERAL, $comment->getAlignment());
self::assertFalse($comment->getVisible());
}
public function testSetAuthor(): void
{
$comment = new Comment();
$comment->setAuthor('Mark Baker');
self::assertEquals('Mark Baker', $comment->getAuthor());
}
public function testSetMarginLeft(): void
{
$comment = new Comment();
$comment->setMarginLeft('20pt');
self::assertEquals('20pt', $comment->getMarginLeft());
}
public function testSetMarginTop(): void
{
$comment = new Comment();
$comment->setMarginTop('2.5pt');
self::assertEquals('2.5pt', $comment->getMarginTop());
}
public function testSetWidth(): void
{
$comment = new Comment();
$comment->setWidth('120pt');
self::assertEquals('120pt', $comment->getWidth());
}
public function testSetHeight(): void
{
$comment = new Comment();
$comment->setHeight('60px');
self::assertEquals('60px', $comment->getHeight());
}
public function testSetFillColor(): void
{
$comment = new Comment();
$comment->setFillColor(new Color('RED'));
self::assertEquals('RED', $comment->getFillColor()->getARGB());
}
public function testSetAlignment(): void
{
$comment = new Comment();
$comment->setAlignment(Alignment::HORIZONTAL_CENTER);
self::assertEquals(Alignment::HORIZONTAL_CENTER, $comment->getAlignment());
}
public function testSetText(): void
{
$comment = new Comment();
$test = new RichText();
$test->addText(new TextElement('This is a test comment'));
$comment->setText($test);
self::assertEquals('This is a test comment', (string) $comment);
}
}

View File

@ -55,7 +55,7 @@ class CsvContiguousFilter implements IReadFilter
return false; return false;
} }
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
if ($this->filterType == 1) { if ($this->filterType == 1) {
return $this->filter1($row); return $this->filter1($row);

View File

@ -7,7 +7,7 @@ use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
/** Define a Read Filter class implementing IReadFilter */ /** Define a Read Filter class implementing IReadFilter */
class GnumericFilter implements IReadFilter class GnumericFilter implements IReadFilter
{ {
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
return $row !== 4; return $row !== 4;
} }

View File

@ -9,8 +9,8 @@ use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
*/ */
class OddColumnReadFilter implements IReadFilter class OddColumnReadFilter implements IReadFilter
{ {
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
return (\ord(\substr($column, -1, 1)) % 2) === 1; return (\ord(\substr($columnAddress, -1, 1)) % 2) === 1;
} }
} }

View File

@ -7,7 +7,7 @@ use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
/** Define a Read Filter class implementing IReadFilter */ /** Define a Read Filter class implementing IReadFilter */
class XmlFilter implements IReadFilter class XmlFilter implements IReadFilter
{ {
public function readCell($column, $row, $worksheetName = '') public function readCell($columnAddress, $row, $worksheetName = '')
{ {
return $row !== 4; return $row !== 4;
} }

View File

@ -7,6 +7,73 @@ use PHPUnit\Framework\TestCase;
class ColorTest extends TestCase class ColorTest extends TestCase
{ {
public function testNewColor(): void
{
$color = new Color('FF123456');
self::assertEquals('FF123456', $color->getARGB());
self::assertEquals('123456', $color->getRGB());
}
public function testARGBSetter(): void
{
$color = new Color();
$color->setARGB('80123456');
self::assertEquals('80123456', $color->getARGB());
self::assertEquals('123456', $color->getRGB());
}
public function testARGBSetterEmpty(): void
{
$color = new Color();
$color->setARGB();
self::assertEquals(Color::COLOR_BLACK, $color->getARGB());
}
public function testARGBSetterInvalid(): void
{
$color = new Color('80123456');
$color->setARGB('INVALID COLOR');
self::assertEquals('80123456', $color->getARGB());
}
public function testRGBSetter(): void
{
$color = new Color();
$color->setRGB('123456');
self::assertEquals('123456', $color->getRGB());
self::assertEquals('FF123456', $color->getARGB());
}
public function testRGBSetterEmpty(): void
{
$color = new Color();
$color->setRGB();
self::assertEquals(Color::COLOR_BLACK, $color->getARGB());
}
public function testRGBSetterInvalid(): void
{
$color = new Color('80123456');
$color->setRGB('INVALID COLOR');
self::assertEquals('123456', $color->getRGB());
}
public function testARGBFromArray(): void
{
$color = new Color();
$color->applyFromArray(['argb' => '80123456']);
self::assertEquals('80123456', $color->getARGB());
self::assertEquals('123456', $color->getRGB());
}
public function testRGBFromArray(): void
{
$color = new Color();
$color->applyFromArray(['rgb' => '123456']);
self::assertEquals('123456', $color->getRGB());
self::assertEquals('FF123456', $color->getARGB());
}
/** /**
* @dataProvider providerColorGetRed * @dataProvider providerColorGetRed
* *
@ -21,7 +88,7 @@ class ColorTest extends TestCase
public function providerColorGetRed(): array public function providerColorGetRed(): array
{ {
return require 'tests/data/Style/ColorGetRed.php'; return require 'tests/data/Style/Color/ColorGetRed.php';
} }
/** /**
@ -38,7 +105,7 @@ class ColorTest extends TestCase
public function providerColorGetGreen(): array public function providerColorGetGreen(): array
{ {
return require 'tests/data/Style/ColorGetGreen.php'; return require 'tests/data/Style/Color/ColorGetGreen.php';
} }
/** /**
@ -55,7 +122,7 @@ class ColorTest extends TestCase
public function providerColorGetBlue(): array public function providerColorGetBlue(): array
{ {
return require 'tests/data/Style/ColorGetBlue.php'; return require 'tests/data/Style/Color/ColorGetBlue.php';
} }
/** /**
@ -71,7 +138,7 @@ class ColorTest extends TestCase
public function providerColorChangeBrightness(): array public function providerColorChangeBrightness(): array
{ {
return require 'tests/data/Style/ColorChangeBrightness.php'; return require 'tests/data/Style/Color/ColorChangeBrightness.php';
} }
public function testDefaultColor(): void public function testDefaultColor(): void

View File

@ -42,10 +42,10 @@ class XlsGifBmpTest extends AbstractFunctional
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$creationDatestamp = $reloadedSpreadsheet->getProperties()->getCreated(); $creationDatestamp = $reloadedSpreadsheet->getProperties()->getCreated();
$filstart = $creationDatestamp; $filstart = $creationDatestamp;
$pSheet = $reloadedSpreadsheet->getActiveSheet(); $worksheet = $reloadedSpreadsheet->getActiveSheet();
$drawings = $pSheet->getDrawingCollection(); $drawings = $worksheet->getDrawingCollection();
self::assertCount(1, $drawings); self::assertCount(1, $drawings);
foreach ($pSheet->getDrawingCollection() as $drawing) { foreach ($worksheet->getDrawingCollection() as $drawing) {
// See if Scrutinizer approves this // See if Scrutinizer approves this
$mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing'; $mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing';
self::assertEquals('image/png', $mimeType); self::assertEquals('image/png', $mimeType);
@ -71,10 +71,10 @@ class XlsGifBmpTest extends AbstractFunctional
$drawing->setCoordinates('A1'); $drawing->setCoordinates('A1');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$pSheet = $reloadedSpreadsheet->getActiveSheet(); $worksheet = $reloadedSpreadsheet->getActiveSheet();
$drawings = $pSheet->getDrawingCollection(); $drawings = $worksheet->getDrawingCollection();
self::assertCount(1, $drawings); self::assertCount(1, $drawings);
foreach ($pSheet->getDrawingCollection() as $drawing) { foreach ($worksheet->getDrawingCollection() as $drawing) {
$mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing'; $mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing';
self::assertEquals('image/png', $mimeType); self::assertEquals('image/png', $mimeType);
} }

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