diff --git a/CHANGELOG.md b/CHANGELOG.md index 83239f45bb..80e9788589 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) - Ability to stream to an Amazon S3 bucket [Issue #2249](https://github.com/PHPOffice/PhpSpreadsheet/issues/2249) +- Provided a Size Helper class to validate size values (pt, px, em) ### Changed diff --git a/docs/topics/reading-and-writing-to-file.md b/docs/topics/reading-and-writing-to-file.md index cb1e0e77b9..8bb48cc5ce 100644 --- a/docs/topics/reading-and-writing-to-file.md +++ b/docs/topics/reading-and-writing-to-file.md @@ -124,7 +124,7 @@ the Excel file: ```php 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 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; @@ -249,7 +249,7 @@ in the Excel file: ```php 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 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; @@ -308,7 +308,7 @@ in the Excel file: ```php 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 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; @@ -359,7 +359,7 @@ in the SYLK file: ```php 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 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; @@ -404,7 +404,7 @@ in the Calc file: ```php 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 if ($row == 1 || ($row >= 20 && $row <= 30)) { return true; diff --git a/docs/topics/reading-files.md b/docs/topics/reading-files.md index e1a1a179c9..6c30f266ba 100644 --- a/docs/topics/reading-files.md +++ b/docs/topics/reading-files.md @@ -256,7 +256,7 @@ $sheetname = 'Data Sheet #3'; /** Define a Read Filter class implementing \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 if ($row >= 1 && $row <= 7) { if (in_array($column,range('A','E'))) { @@ -301,7 +301,7 @@ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter $this->columns = $columns; } - public function readCell($column, $row, $worksheetName = '') { + public function readCell($columnAddress, $row, $worksheetName = '') { // Only read the rows and columns that were configured if ($row >= $this->startRow && $row <= $this->endRow) { if (in_array($column,$this->columns)) { @@ -344,7 +344,7 @@ class ChunkReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter $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 if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { return true; diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 82cfeb1d7b..4423b5940c 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -211,7 +211,7 @@ parameters: 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 path: src/PhpSpreadsheet/Calculation/Calculation.php @@ -231,7 +231,7 @@ parameters: 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 path: src/PhpSpreadsheet/Calculation/Calculation.php @@ -816,7 +816,7 @@ parameters: 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 path: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php @@ -1246,7 +1246,7 @@ parameters: 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 path: src/PhpSpreadsheet/Cell/DataType.php @@ -1451,12 +1451,7 @@ parameters: path: src/PhpSpreadsheet/Chart/GridLines.php - - message: "#^Parameter \\#3 \\$type 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\\.$#" + message: "#^Parameter \\#3 \\$colorType of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects string, string\\|null given\\.$#" count: 1 path: src/PhpSpreadsheet/Chart/GridLines.php @@ -1511,7 +1506,7 @@ parameters: 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 path: src/PhpSpreadsheet/Chart/Properties.php @@ -1521,12 +1516,12 @@ parameters: 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 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 path: src/PhpSpreadsheet/Chart/Properties.php @@ -1536,7 +1531,7 @@ parameters: 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 path: src/PhpSpreadsheet/Chart/Properties.php @@ -1895,11 +1890,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -2020,16 +2010,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -2381,17 +2361,17 @@ parameters: 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 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 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 path: src/PhpSpreadsheet/Reader/Xls.php @@ -2566,7 +2546,7 @@ parameters: 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 path: src/PhpSpreadsheet/Reader/Xlsx.php @@ -3221,7 +3201,7 @@ parameters: 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 path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php @@ -3271,7 +3251,7 @@ parameters: 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 path: src/PhpSpreadsheet/Reader/Xml.php @@ -3326,7 +3306,7 @@ parameters: 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 path: src/PhpSpreadsheet/Shared/Date.php @@ -3336,7 +3316,7 @@ parameters: 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 path: src/PhpSpreadsheet/Shared/Date.php @@ -3466,7 +3446,7 @@ parameters: 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 path: src/PhpSpreadsheet/Shared/Font.php @@ -3866,7 +3846,7 @@ parameters: 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 path: src/PhpSpreadsheet/Shared/StringHelper.php @@ -4096,7 +4076,7 @@ parameters: 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 path: src/PhpSpreadsheet/Spreadsheet.php @@ -4140,11 +4120,6 @@ parameters: count: 1 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\\.$#" count: 10 @@ -4681,7 +4656,7 @@ parameters: 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 path: src/PhpSpreadsheet/Worksheet/Worksheet.php @@ -4915,11 +4890,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -4930,11 +4900,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -4965,11 +4930,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -5005,11 +4965,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -5030,11 +4985,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -5045,11 +4995,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -5110,11 +5055,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -5171,7 +5111,7 @@ parameters: 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 path: src/PhpSpreadsheet/Writer/Ods/Content.php @@ -5291,7 +5231,7 @@ parameters: 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 path: src/PhpSpreadsheet/Writer/Xls/Font.php @@ -5311,7 +5251,7 @@ parameters: 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 path: src/PhpSpreadsheet/Writer/Xls/Font.php @@ -5370,11 +5310,6 @@ parameters: count: 1 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\\.$#" count: 1 @@ -5701,7 +5636,7 @@ parameters: path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php - - message: "#^Parameter \\#1 \\$text of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:writeRawData\\(\\) expects array\\\\|string, int given\\.$#" + message: "#^Parameter \\#1 \\$rawTextData of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:writeRawData\\(\\) expects array\\\\|string\\|null, int given\\.$#" count: 1 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\\.$#" - count: 4 + count: 5 path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php - @@ -5871,7 +5806,7 @@ parameters: 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 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\\.$#" - count: 4 + count: 9 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\\.$#" count: 1 @@ -6002,16 +5942,11 @@ parameters: - 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 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 path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php @@ -6056,7 +5991,7 @@ parameters: 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 path: tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php @@ -6101,7 +6036,7 @@ parameters: 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 path: tests/PhpSpreadsheetTests/Functional/StreamTest.php @@ -6201,7 +6136,7 @@ parameters: 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 path: tests/PhpSpreadsheetTests/Shared/StringHelperTest.php @@ -6216,12 +6151,12 @@ parameters: 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 path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php - - message: "#^Parameter \\#1 \\$pValue of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:setConditions\\(\\) expects array\\\\|bool\\|float\\|int\\|string, array\\ given\\.$#" + message: "#^Parameter \\#1 \\$conditions of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:setConditions\\(\\) expects array\\\\|bool\\|float\\|int\\|string, array\\ given\\.$#" count: 1 path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php diff --git a/samples/Basic/24_Readfilter.php b/samples/Basic/24_Readfilter.php index ab1c2e411c..e5b613a67e 100644 --- a/samples/Basic/24_Readfilter.php +++ b/samples/Basic/24_Readfilter.php @@ -18,7 +18,7 @@ class MyReadFilter implements IReadFilter { - public function readCell($column, $row, $worksheetName = '') + public function readCell($columnAddress, $row, $worksheetName = '') { // Read title row and rows 20 - 30 if ($row == 1 || ($row >= 20 && $row <= 30)) { diff --git a/samples/Reader/09_Simple_file_reader_using_a_read_filter.php b/samples/Reader/09_Simple_file_reader_using_a_read_filter.php index 6e0eda14b7..04c47c64f1 100644 --- a/samples/Reader/09_Simple_file_reader_using_a_read_filter.php +++ b/samples/Reader/09_Simple_file_reader_using_a_read_filter.php @@ -13,11 +13,11 @@ 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 if ($row >= 1 && $row <= 7) { - if (in_array($column, range('A', 'E'))) { + if (in_array($columnAddress, range('A', 'E'))) { return true; } } diff --git a/samples/Reader/10_Simple_file_reader_using_a_configurable_read_filter.php b/samples/Reader/10_Simple_file_reader_using_a_configurable_read_filter.php index 7b3fc440d1..6a600d43d9 100644 --- a/samples/Reader/10_Simple_file_reader_using_a_configurable_read_filter.php +++ b/samples/Reader/10_Simple_file_reader_using_a_configurable_read_filter.php @@ -26,10 +26,10 @@ public function __construct($startRow, $endRow, $columns) $this->columns = $columns; } - public function readCell($column, $row, $worksheetName = '') + public function readCell($columnAddress, $row, $worksheetName = '') { if ($row >= $this->startRow && $row <= $this->endRow) { - if (in_array($column, $this->columns)) { + if (in_array($columnAddress, $this->columns)) { return true; } } diff --git a/samples/Reader/11_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_1).php b/samples/Reader/11_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_1).php index 18562217b6..6c9087033b 100644 --- a/samples/Reader/11_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_1).php +++ b/samples/Reader/11_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_1).php @@ -29,7 +29,7 @@ public function __construct($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 if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { diff --git a/samples/Reader/12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_2).php b/samples/Reader/12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_2).php index 61f624b2be..c594c7983f 100644 --- a/samples/Reader/12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_2).php +++ b/samples/Reader/12_Reading_a_workbook_in_chunks_using_a_configurable_read_filter_(version_2).php @@ -29,7 +29,7 @@ public function setRows($startRow, $chunkSize): void $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 if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { diff --git a/samples/Reader/14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php b/samples/Reader/14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php index 02d3d939b1..87fbb2256c 100644 --- a/samples/Reader/14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php +++ b/samples/Reader/14_Reading_a_large_CSV_file_in_chunks_to_split_across_multiple_worksheets.php @@ -30,7 +30,7 @@ public function setRows($startRow, $chunkSize): void $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 if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { diff --git a/src/PhpSpreadsheet/Calculation/Calculation.php b/src/PhpSpreadsheet/Calculation/Calculation.php index 98eec28831..15bb8100b7 100644 --- a/src/PhpSpreadsheet/Calculation/Calculation.php +++ b/src/PhpSpreadsheet/Calculation/Calculation.php @@ -3893,15 +3893,15 @@ private function internalParseFormula($formula, ?Cell $pCell = null) $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null; $regexpMatchString = '/^(' . self::CALCULATION_REGEXP_FUNCTION . - '|' . self::CALCULATION_REGEXP_CELLREF . + '|' . self::CALCULATION_REGEXP_CELLREF . '|' . self::CALCULATION_REGEXP_COLUMN_RANGE . '|' . self::CALCULATION_REGEXP_ROW_RANGE . - '|' . self::CALCULATION_REGEXP_NUMBER . - '|' . self::CALCULATION_REGEXP_STRING . - '|' . self::CALCULATION_REGEXP_OPENBRACE . - '|' . self::CALCULATION_REGEXP_DEFINEDNAME . - '|' . self::CALCULATION_REGEXP_ERROR . - ')/sui'; + '|' . self::CALCULATION_REGEXP_NUMBER . + '|' . self::CALCULATION_REGEXP_STRING . + '|' . self::CALCULATION_REGEXP_OPENBRACE . + '|' . self::CALCULATION_REGEXP_DEFINEDNAME . + '|' . self::CALCULATION_REGEXP_ERROR . + ')/sui'; // Start with initialisation $index = 0; @@ -4333,7 +4333,7 @@ private function internalParseFormula($formula, ?Cell $pCell = null) ((preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/Ui', substr($formula, $index), $match)) && ($output[count($output) - 1]['type'] == 'Cell Reference') || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match)) && - ($output[count($output) - 1]['type'] == 'Defined Name' || $output[count($output) - 1]['type'] == 'Value') + ($output[count($output) - 1]['type'] == 'Defined Name' || $output[count($output) - 1]['type'] == 'Value') ) ) { while ( @@ -4724,7 +4724,7 @@ private function processTokenStack($tokens, $cellID = null, ?Cell $pCell = null) } } else { if ($pCell === null) { - // We can't access the cell, so return a REF error + // We can't access the cell, so return a REF error $cellValue = Functions::REF(); } else { $cellRef = $matches[6] . $matches[7]; @@ -5242,34 +5242,34 @@ protected function raiseFormulaError($errorMessage) * Extract range values. * * @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 * * @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 $returnValue = []; - if ($pSheet !== null) { - $pSheetName = $pSheet->getTitle(); + if ($worksheet !== null) { + $worksheetName = $worksheet->getTitle(); if (strpos($pRange, '!') !== false) { - [$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); - $pSheet = $this->spreadsheet->getSheetByName($pSheetName); + [$worksheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); + $worksheet = $this->spreadsheet->getSheetByName($worksheetName); } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($pRange); - $pRange = "'" . $pSheetName . "'" . '!' . $pRange; + $pRange = "'" . $worksheetName . "'" . '!' . $pRange; if (!isset($aReferences[1])) { $currentCol = ''; $currentRow = 0; // Single cell in range sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); - if ($pSheet->cellExists($aReferences[0])) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + if ($worksheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -5280,8 +5280,8 @@ public function extractCellRange(&$pRange = 'A1', ?Worksheet $pSheet = null, $re $currentRow = 0; // Extract range sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); - if ($pSheet->cellExists($reference)) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + if ($worksheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -5295,47 +5295,46 @@ public function extractCellRange(&$pRange = 'A1', ?Worksheet $pSheet = null, $re /** * Extract range values. * - * @param string $pRange String based range representation - * @param Worksheet $pSheet Worksheet + * @param string $range String based range representation + * @param null|Worksheet $worksheet Worksheet * @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. */ - public function extractNamedRange(&$pRange = 'A1', ?Worksheet $pSheet = null, $resetLog = true) + public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true) { // Return value $returnValue = []; - if ($pSheet !== null) { - $pSheetName = $pSheet->getTitle(); - if (strpos($pRange, '!') !== false) { - [$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); - $pSheet = $this->spreadsheet->getSheetByName($pSheetName); + if ($worksheet !== null) { + if (strpos($range, '!') !== false) { + [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); + $worksheet = $this->spreadsheet->getSheetByName($worksheetName); } // Named range? - $namedRange = DefinedName::resolveName($pRange, $pSheet); + $namedRange = DefinedName::resolveName($range, $worksheet); if ($namedRange === null) { return Functions::REF(); } - $pSheet = $namedRange->getWorksheet(); - $pRange = $namedRange->getValue(); - $splitRange = Coordinate::splitRange($pRange); + $worksheet = $namedRange->getWorksheet(); + $range = $namedRange->getValue(); + $splitRange = Coordinate::splitRange($range); // Convert row and column references 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])) { - $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1]; + $range = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1]; } // Extract range - $aReferences = Coordinate::extractAllCellReferencesInRange($pRange); + $aReferences = Coordinate::extractAllCellReferencesInRange($range); if (!isset($aReferences[1])) { // Single cell (or single column or row) in range [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]); - if ($pSheet->cellExists($aReferences[0])) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + if ($worksheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -5344,8 +5343,8 @@ public function extractNamedRange(&$pRange = 'A1', ?Worksheet $pSheet = null, $r foreach ($aReferences as $reference) { // Extract range [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference); - if ($pSheet->cellExists($reference)) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + if ($worksheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php b/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php index 87ea738147..f38e5da801 100644 --- a/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php @@ -65,10 +65,10 @@ public static function extractWorksheet(string $cellAddress, Cell $pCell): array $sheetName = trim($sheetName, "'"); } - $pSheet = ($sheetName !== '') + $worksheet = ($sheetName !== '') ? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName) : $pCell->getWorksheet(); - return [$cellAddress, $pSheet, $sheetName]; + return [$cellAddress, $worksheet, $sheetName]; } } diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php b/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php index d3314ff460..3a76bb0f94 100644 --- a/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php @@ -69,7 +69,7 @@ public static function INDIRECT($cellAddress, $a1fmt, Cell $pCell) 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); @@ -80,7 +80,7 @@ public static function INDIRECT($cellAddress, $a1fmt, Cell $pCell) return Functions::REF(); } - return self::extractRequiredCells($pSheet, $cellAddress); + return self::extractRequiredCells($worksheet, $cellAddress); } /** @@ -89,9 +89,9 @@ public static function INDIRECT($cellAddress, $a1fmt, Cell $pCell) * @return mixed Array of values in range if range contains more than one element. * 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) - ->extractCellRange($cellAddress, $pSheet, false); + return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) + ->extractCellRange($cellAddress, $worksheet, false); } } diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php b/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php index c027d83c79..0e45831fc6 100644 --- a/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php @@ -55,7 +55,7 @@ public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $hei return Functions::REF(); } - [$cellAddress, $pSheet] = self::extractWorksheet($cellAddress, $pCell); + [$cellAddress, $worksheet] = self::extractWorksheet($cellAddress, $pCell); $startCell = $endCell = $cellAddress; if (strpos($cellAddress, ':')) { @@ -87,13 +87,13 @@ public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $hei $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) - ->extractCellRange($cellAddress, $pSheet, false); + return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) + ->extractCellRange($cellAddress, $worksheet, false); } private static function extractWorksheet($cellAddress, Cell $pCell): array @@ -104,11 +104,11 @@ private static function extractWorksheet($cellAddress, Cell $pCell): array $sheetName = trim($sheetName, "'"); } - $pSheet = ($sheetName !== '') + $worksheet = ($sheetName !== '') ? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName) : $pCell->getWorksheet(); - return [$cellAddress, $pSheet]; + return [$cellAddress, $worksheet]; } private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns) diff --git a/src/PhpSpreadsheet/Cell/Cell.php b/src/PhpSpreadsheet/Cell/Cell.php index 8ca2709735..56604f1e49 100644 --- a/src/PhpSpreadsheet/Cell/Cell.php +++ b/src/PhpSpreadsheet/Cell/Cell.php @@ -90,24 +90,24 @@ public function attach(Cells $parent): void /** * Create a new Cell. * - * @param mixed $pValue - * @param string $pDataType + * @param mixed $value + * @param string $dataType */ - public function __construct($pValue, $pDataType, Worksheet $pSheet) + public function __construct($value, $dataType, Worksheet $worksheet) { // Initialise cell value - $this->value = $pValue; + $this->value = $value; // Set worksheet cache - $this->parent = $pSheet->getCellCollection(); + $this->parent = $worksheet->getCellCollection(); // Set datatype? - if ($pDataType !== null) { - if ($pDataType == DataType::TYPE_STRING2) { - $pDataType = DataType::TYPE_STRING; + if ($dataType !== null) { + if ($dataType == DataType::TYPE_STRING2) { + $dataType = DataType::TYPE_STRING; } - $this->dataType = $pDataType; - } elseif (!self::getValueBinder()->bindValue($this, $pValue)) { + $this->dataType = $dataType; + } elseif (!self::getValueBinder()->bindValue($this, $value)) { throw new Exception('Value could not be bound to cell.'); } } @@ -171,13 +171,13 @@ public function getFormattedValue() * * Sets the value for a cell, automatically determining the datatype using the value binder * - * @param mixed $pValue Value + * @param mixed $value Value * * @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.'); } @@ -187,56 +187,56 @@ public function setValue($pValue) /** * 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 string $pDataType Explicit data type, see DataType::TYPE_* + * @param mixed $value Value + * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return Cell */ - public function setValueExplicit($pValue, $pDataType) + public function setValueExplicit($value, $dataType) { // set the value according to data type - switch ($pDataType) { + switch ($dataType) { case DataType::TYPE_NULL: - $this->value = $pValue; + $this->value = $value; break; case DataType::TYPE_STRING2: - $pDataType = DataType::TYPE_STRING; - // no break + $dataType = DataType::TYPE_STRING; + // no break case DataType::TYPE_STRING: // Synonym for string case DataType::TYPE_INLINE: // Rich text - $this->value = DataType::checkString($pValue); + $this->value = DataType::checkString($value); break; 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'); } - $this->value = 0 + $pValue; + $this->value = 0 + $value; break; case DataType::TYPE_FORMULA: - $this->value = (string) $pValue; + $this->value = (string) $value; break; case DataType::TYPE_BOOL: - $this->value = (bool) $pValue; + $this->value = (bool) $value; break; case DataType::TYPE_ERROR: - $this->value = DataType::checkErrorCode($pValue); + $this->value = DataType::checkErrorCode($value); break; default: - throw new Exception('Invalid datatype: ' . $pDataType); + throw new Exception('Invalid datatype: ' . $dataType); break; } // set the datatype - $this->dataType = $pDataType; + $this->dataType = $dataType; return $this->updateInCollection(); } @@ -292,14 +292,14 @@ public function getCalculatedValue($resetLog = true) /** * Set old calculated value (cached). * - * @param mixed $pValue Value + * @param mixed $originalValue Value * * @return Cell */ - public function setCalculatedValue($pValue) + public function setCalculatedValue($originalValue) { - if ($pValue !== null) { - $this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; + if ($originalValue !== null) { + $this->calculatedValue = (is_numeric($originalValue)) ? (float) $originalValue : $originalValue; } return $this->updateInCollection(); @@ -333,16 +333,16 @@ public function getDataType() /** * Set cell data type. * - * @param string $pDataType see DataType::TYPE_* + * @param string $dataType see DataType::TYPE_* * * @return Cell */ - public function setDataType($pDataType) + public function setDataType($dataType) { - if ($pDataType == DataType::TYPE_STRING2) { - $pDataType = DataType::TYPE_STRING; + if ($dataType == DataType::TYPE_STRING2) { + $dataType = DataType::TYPE_STRING; } - $this->dataType = $pDataType; + $this->dataType = $dataType; return $this->updateInCollection(); } @@ -388,17 +388,17 @@ public function getDataValidation() /** * Set Data validation rules. * - * @param DataValidation $pDataValidation + * @param DataValidation $dataValidation * * @return Cell */ - public function setDataValidation(?DataValidation $pDataValidation = null) + public function setDataValidation(?DataValidation $dataValidation = null) { if (!isset($this->parent)) { 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(); } @@ -446,17 +446,17 @@ public function getHyperlink() /** * Set Hyperlink. * - * @param Hyperlink $pHyperlink + * @param Hyperlink $hyperlink * * @return Cell */ - public function setHyperlink(?Hyperlink $pHyperlink = null) + public function setHyperlink(?Hyperlink $hyperlink = null) { if (!isset($this->parent)) { 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(); } @@ -550,13 +550,13 @@ public function rebindParent(Worksheet $parent) /** * 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 */ - public function isInRange($pRange) + public function isInRange($range) { - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); // Translate properties $myColumn = Coordinate::columnIndexFromString($this->getColumn()); @@ -564,7 +564,7 @@ public function isInRange($pRange) // Verify if cell is in range return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && - ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow); + ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow); } /** @@ -638,13 +638,13 @@ public function getXfIndex() /** * Set index to cellXf. * - * @param int $pValue + * @param int $indexValue * * @return Cell */ - public function setXfIndex($pValue) + public function setXfIndex($indexValue) { - $this->xfIndex = $pValue; + $this->xfIndex = $indexValue; return $this->updateInCollection(); } @@ -652,13 +652,13 @@ public function setXfIndex($pValue) /** * Set the formula attributes. * - * @param mixed $pAttributes + * @param mixed $attributes * * @return $this */ - public function setFormulaAttributes($pAttributes) + public function setFormulaAttributes($attributes) { - $this->formulaAttributes = $pAttributes; + $this->formulaAttributes = $attributes; return $this; } diff --git a/src/PhpSpreadsheet/Cell/Coordinate.php b/src/PhpSpreadsheet/Cell/Coordinate.php index 58d2573e66..df64c55706 100644 --- a/src/PhpSpreadsheet/Cell/Coordinate.php +++ b/src/PhpSpreadsheet/Cell/Coordinate.php @@ -25,21 +25,21 @@ abstract class Coordinate /** * 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) */ - 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']]; - } elseif (self::coordinateIsRange($pCoordinateString)) { + } elseif (self::coordinateIsRange($cellAddress)) { 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('Invalid cell coordinate ' . $pCoordinateString); + throw new Exception('Invalid cell coordinate ' . $cellAddress); } /** @@ -60,68 +60,68 @@ public static function indexesFromString(string $coordinates): array } /** - * 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 */ - 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. * - * @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 * * @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'); } // Split out any worksheet name from the reference - [$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true); + [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate - if (ctype_digit($pCoordinateString)) { - return $worksheet . '$' . $pCoordinateString; - } elseif (ctype_alpha($pCoordinateString)) { - return $worksheet . '$' . strtoupper($pCoordinateString); + if (ctype_digit($cellAddress)) { + return $worksheet . '$' . $cellAddress; + } elseif (ctype_alpha($cellAddress)) { + return $worksheet . '$' . strtoupper($cellAddress); } - return $worksheet . self::absoluteCoordinate($pCoordinateString); + return $worksheet . self::absoluteCoordinate($cellAddress); } /** * Make string coordinate absolute. * - * @param string $pCoordinateString e.g. 'A1' + * @param string $cellAddress e.g. 'A1' * * @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'); } // Split out any worksheet name from the coordinate - [$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true); + [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate - [$column, $row] = self::coordinateFromString($pCoordinateString); + [$column, $row] = self::coordinateFromString($cellAddress); $column = ltrim($column, '$'); $row = ltrim($row, '$'); @@ -131,20 +131,20 @@ public static function absoluteCoordinate($pCoordinateString) /** * 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 * e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']] * or ['B4'] */ - public static function splitRange($pRange) + public static function splitRange($range) { // Ensure $pRange is a valid range - if (empty($pRange)) { - $pRange = self::DEFAULT_RANGE; + if (empty($range)) { + $range = self::DEFAULT_RANGE; } - $exploded = explode(',', $pRange); + $exploded = explode(',', $range); $counter = count($exploded); for ($i = 0; $i < $counter; ++$i) { $exploded[$i] = explode(':', $exploded[$i]); @@ -156,49 +156,49 @@ public static function splitRange($pRange) /** * 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 */ - public static function buildRange(array $pRange) + public static function buildRange(array $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'); } // Build range - $counter = count($pRange); + $counter = count($range); 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. * - * @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] * 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 - if (empty($pRange)) { - $pRange = self::DEFAULT_RANGE; + if (empty($range)) { + $range = self::DEFAULT_RANGE; } // Uppercase coordinate - $pRange = strtoupper($pRange); + $range = strtoupper($range); // Extract range - if (strpos($pRange, ':') === false) { - $rangeA = $rangeB = $pRange; + if (strpos($range, ':') === false) { + $rangeA = $rangeB = $range; } else { - [$rangeA, $rangeB] = explode(':', $pRange); + [$rangeA, $rangeB] = explode(':', $range); } // Calculate range outer borders @@ -215,14 +215,14 @@ public static function rangeBoundaries($pRange) /** * 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) */ - public static function rangeDimension($pRange) + public static function rangeDimension($range) { // 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)]; } @@ -230,26 +230,26 @@ public static function rangeDimension($pRange) /** * 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] * 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 - if (empty($pRange)) { - $pRange = self::DEFAULT_RANGE; + if (empty($range)) { + $range = self::DEFAULT_RANGE; } // Uppercase coordinate - $pRange = strtoupper($pRange); + $range = strtoupper($range); // Extract range - if (strpos($pRange, ':') === false) { - $rangeA = $rangeB = $pRange; + if (strpos($range, ':') === false) { + $rangeA = $rangeB = $range; } else { - [$rangeA, $rangeB] = explode(':', $pRange); + [$rangeA, $rangeB] = explode(':', $range); } return [self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)]; @@ -258,19 +258,19 @@ public static function getRangeBoundaries($pRange) /** * Column index from string. * - * @param string $pString eg 'A' + * @param string $columnAddress eg 'A' * * @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 // caching using a static within the method is faster than a class static, // though it's additional memory overhead static $indexCache = []; - if (isset($indexCache[$pString])) { - return $indexCache[$pString]; + if (isset($indexCache[$columnAddress])) { + 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() // 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 @@ public static function columnIndexFromString($pString) // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString // for improved performance - if (isset($pString[0])) { - if (!isset($pString[1])) { - $indexCache[$pString] = $columnLookup[$pString]; + if (isset($columnAddress[0])) { + if (!isset($columnAddress[1])) { + $indexCache[$columnAddress] = $columnLookup[$columnAddress]; - return $indexCache[$pString]; - } elseif (!isset($pString[2])) { - $indexCache[$pString] = $columnLookup[$pString[0]] * 26 + $columnLookup[$pString[1]]; + return $indexCache[$columnAddress]; + } elseif (!isset($columnAddress[2])) { + $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26 + $columnLookup[$columnAddress[1]]; - return $indexCache[$pString]; - } elseif (!isset($pString[3])) { - $indexCache[$pString] = $columnLookup[$pString[0]] * 676 + $columnLookup[$pString[1]] * 26 + $columnLookup[$pString[2]]; + return $indexCache[$columnAddress]; + } elseif (!isset($columnAddress[3])) { + $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 @@ private static function getReferencesForCellBlock($cellBlock) * * [ '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 */ - public static function mergeRangesInCollection(array $pCoordCollection) + public static function mergeRangesInCollection(array $coordinateCollection) { $hashedValues = []; $mergedCoordCollection = []; - foreach ($pCoordCollection as $coord => $value) { + foreach ($coordinateCollection as $coord => $value) { if (self::coordinateIsRange($coord)) { $mergedCoordCollection[$coord] = $value; diff --git a/src/PhpSpreadsheet/Cell/DataType.php b/src/PhpSpreadsheet/Cell/DataType.php index ba03579178..cee3e1e5eb 100644 --- a/src/PhpSpreadsheet/Cell/DataType.php +++ b/src/PhpSpreadsheet/Cell/DataType.php @@ -45,41 +45,41 @@ public static function getErrorCodes() /** * 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 */ - 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) - return $pValue; + return $textValue; } // 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" - $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. * - * @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 */ - public static function checkErrorCode($pValue) + public static function checkErrorCode($value) { - $pValue = (string) $pValue; + $value = (string) $value; - if (!isset(self::$errorCodes[$pValue])) { - $pValue = '#NULL!'; + if (!isset(self::$errorCodes[$value])) { + $value = '#NULL!'; } - return $pValue; + return $value; } } diff --git a/src/PhpSpreadsheet/Cell/DataValidation.php b/src/PhpSpreadsheet/Cell/DataValidation.php index 2ff52f3260..79d70a989c 100644 --- a/src/PhpSpreadsheet/Cell/DataValidation.php +++ b/src/PhpSpreadsheet/Cell/DataValidation.php @@ -140,13 +140,13 @@ public function getFormula1() /** * Set Formula 1. * - * @param string $value + * @param string $formula * * @return $this */ - public function setFormula1($value) + public function setFormula1($formula) { - $this->formula1 = $value; + $this->formula1 = $formula; return $this; } @@ -164,13 +164,13 @@ public function getFormula2() /** * Set Formula 2. * - * @param string $value + * @param string $formula * * @return $this */ - public function setFormula2($value) + public function setFormula2($formula) { - $this->formula2 = $value; + $this->formula2 = $formula; return $this; } @@ -188,13 +188,13 @@ public function getType() /** * Set Type. * - * @param string $value + * @param string $type * * @return $this */ - public function setType($value) + public function setType($type) { - $this->type = $value; + $this->type = $type; return $this; } @@ -212,13 +212,13 @@ public function getErrorStyle() /** * Set Error style. * - * @param string $value see self::STYLE_* + * @param string $errorStyle see self::STYLE_* * * @return $this */ - public function setErrorStyle($value) + public function setErrorStyle($errorStyle) { - $this->errorStyle = $value; + $this->errorStyle = $errorStyle; return $this; } @@ -236,13 +236,13 @@ public function getOperator() /** * Set Operator. * - * @param string $value + * @param string $operator * * @return $this */ - public function setOperator($value) + public function setOperator($operator) { - $this->operator = $value; + $this->operator = $operator; return $this; } @@ -260,13 +260,13 @@ public function getAllowBlank() /** * Set Allow Blank. * - * @param bool $value + * @param bool $allowBlank * * @return $this */ - public function setAllowBlank($value) + public function setAllowBlank($allowBlank) { - $this->allowBlank = $value; + $this->allowBlank = $allowBlank; return $this; } @@ -284,13 +284,13 @@ public function getShowDropDown() /** * Set Show DropDown. * - * @param bool $value + * @param bool $showDropDown * * @return $this */ - public function setShowDropDown($value) + public function setShowDropDown($showDropDown) { - $this->showDropDown = $value; + $this->showDropDown = $showDropDown; return $this; } @@ -308,13 +308,13 @@ public function getShowInputMessage() /** * Set Show InputMessage. * - * @param bool $value + * @param bool $showInputMessage * * @return $this */ - public function setShowInputMessage($value) + public function setShowInputMessage($showInputMessage) { - $this->showInputMessage = $value; + $this->showInputMessage = $showInputMessage; return $this; } @@ -332,13 +332,13 @@ public function getShowErrorMessage() /** * Set Show ErrorMessage. * - * @param bool $value + * @param bool $showErrorMessage * * @return $this */ - public function setShowErrorMessage($value) + public function setShowErrorMessage($showErrorMessage) { - $this->showErrorMessage = $value; + $this->showErrorMessage = $showErrorMessage; return $this; } @@ -356,13 +356,13 @@ public function getErrorTitle() /** * Set Error title. * - * @param string $value + * @param string $errorTitle * * @return $this */ - public function setErrorTitle($value) + public function setErrorTitle($errorTitle) { - $this->errorTitle = $value; + $this->errorTitle = $errorTitle; return $this; } @@ -380,13 +380,13 @@ public function getError() /** * Set Error. * - * @param string $value + * @param string $error * * @return $this */ - public function setError($value) + public function setError($error) { - $this->error = $value; + $this->error = $error; return $this; } @@ -404,13 +404,13 @@ public function getPromptTitle() /** * Set Prompt title. * - * @param string $value + * @param string $promptTitle * * @return $this */ - public function setPromptTitle($value) + public function setPromptTitle($promptTitle) { - $this->promptTitle = $value; + $this->promptTitle = $promptTitle; return $this; } @@ -428,13 +428,13 @@ public function getPrompt() /** * Set Prompt. * - * @param string $value + * @param string $prompt * * @return $this */ - public function setPrompt($value) + public function setPrompt($prompt) { - $this->prompt = $value; + $this->prompt = $prompt; return $this; } diff --git a/src/PhpSpreadsheet/Cell/Hyperlink.php b/src/PhpSpreadsheet/Cell/Hyperlink.php index 003d51014d..ffdcbacd27 100644 --- a/src/PhpSpreadsheet/Cell/Hyperlink.php +++ b/src/PhpSpreadsheet/Cell/Hyperlink.php @@ -21,14 +21,14 @@ class Hyperlink /** * Create a new Hyperlink. * - * @param string $pUrl Url to link the cell to - * @param string $pTooltip Tooltip to display on the hyperlink + * @param string $url Url to link the cell to + * @param string $tooltip Tooltip to display on the hyperlink */ - public function __construct($pUrl = '', $pTooltip = '') + public function __construct($url = '', $tooltip = '') { // Initialise member variables - $this->url = $pUrl; - $this->tooltip = $pTooltip; + $this->url = $url; + $this->tooltip = $tooltip; } /** @@ -44,13 +44,13 @@ public function getUrl() /** * Set URL. * - * @param string $value + * @param string $url * * @return $this */ - public function setUrl($value) + public function setUrl($url) { - $this->url = $value; + $this->url = $url; return $this; } @@ -68,13 +68,13 @@ public function getTooltip() /** * Set tooltip. * - * @param string $value + * @param string $tooltip * * @return $this */ - public function setTooltip($value) + public function setTooltip($tooltip) { - $this->tooltip = $value; + $this->tooltip = $tooltip; return $this; } diff --git a/src/PhpSpreadsheet/Chart/Axis.php b/src/PhpSpreadsheet/Chart/Axis.php index 27e6106061..eeed326db8 100644 --- a/src/PhpSpreadsheet/Chart/Axis.php +++ b/src/PhpSpreadsheet/Chart/Axis.php @@ -165,30 +165,30 @@ public function getAxisNumberSourceLinked() /** * Set Axis Options Properties. * - * @param string $axis_labels - * @param string $horizontal_crosses_value - * @param string $horizontal_crosses - * @param string $axis_orientation - * @param string $major_tmt - * @param string $minor_tmt + * @param string $axisLabels + * @param string $horizontalCrossesValue + * @param string $horizontalCrosses + * @param string $axisOrientation + * @param string $majorTmt + * @param string $minorTmt * @param string $minimum * @param string $maximum - * @param string $major_unit - * @param string $minor_unit + * @param string $majorUnit + * @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; - ($horizontal_crosses_value !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null; - ($horizontal_crosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontal_crosses : null; - ($axis_orientation !== null) ? $this->axisOptions['orientation'] = (string) $axis_orientation : null; - ($major_tmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $major_tmt : null; - ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; - ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; + $this->axisOptions['axis_labels'] = (string) $axisLabels; + ($horizontalCrossesValue !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontalCrossesValue : null; + ($horizontalCrosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontalCrosses : null; + ($axisOrientation !== null) ? $this->axisOptions['orientation'] = (string) $axisOrientation : null; + ($majorTmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $majorTmt : null; + ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null; + ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null; ($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null; ($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null; - ($major_unit !== null) ? $this->axisOptions['major_unit'] = (string) $major_unit : null; - ($minor_unit !== null) ? $this->axisOptions['minor_unit'] = (string) $minor_unit : null; + ($majorUnit !== null) ? $this->axisOptions['major_unit'] = (string) $majorUnit : null; + ($minorUnit !== null) ? $this->axisOptions['minor_unit'] = (string) $minorUnit : null; } /** @@ -218,11 +218,11 @@ public function setAxisOrientation($orientation): void * * @param string $color * @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 @@ public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_ * * @param string $color * @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 @@ public function getLineProperty($property) /** * Set Line Style Properties. * - * @param float $line_width - * @param string $compound_type - * @param string $dash_type - * @param string $cap_type - * @param string $join_type - * @param string $head_arrow_type - * @param string $head_arrow_size - * @param string $end_arrow_type - * @param string $end_arrow_size - */ - public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null): void + * @param float $lineWidth + * @param string $compoundType + * @param string $dashType + * @param string $capType + * @param string $joinType + * @param string $headArrowType + * @param string $headArrowSize + * @param string $endArrowType + * @param string $endArrowSize + */ + 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; - ($compound_type !== null) ? $this->lineStyleProperties['compound'] = (string) $compound_type : null; - ($dash_type !== null) ? $this->lineStyleProperties['dash'] = (string) $dash_type : null; - ($cap_type !== null) ? $this->lineStyleProperties['cap'] = (string) $cap_type : null; - ($join_type !== null) ? $this->lineStyleProperties['join'] = (string) $join_type : null; - ($head_arrow_type !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $head_arrow_type : null; - ($head_arrow_size !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $head_arrow_size : null; - ($end_arrow_type !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $end_arrow_type : null; - ($end_arrow_size !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $end_arrow_size : null; + ($lineWidth !== null) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $lineWidth) : null; + ($compoundType !== null) ? $this->lineStyleProperties['compound'] = (string) $compoundType : null; + ($dashType !== null) ? $this->lineStyleProperties['dash'] = (string) $dashType : null; + ($capType !== null) ? $this->lineStyleProperties['cap'] = (string) $capType : null; + ($joinType !== null) ? $this->lineStyleProperties['join'] = (string) $joinType : null; + ($headArrowType !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $headArrowType : null; + ($headArrowSize !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $headArrowSize : null; + ($endArrowType !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $endArrowType : null; + ($endArrowSize !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $endArrowSize : null; } /** @@ -326,38 +326,38 @@ public function getLineStyleArrowLength($arrow) /** * Set Shadow Properties. * - * @param int $sh_presets - * @param string $sh_color_value - * @param string $sh_color_type - * @param string $sh_color_alpha - * @param float $sh_blur - * @param int $sh_angle - * @param float $sh_distance + * @param int $shadowPresets + * @param string $colorValue + * @param string $colorType + * @param string $colorAlpha + * @param float $blur + * @param int $angle + * @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( - $sh_color_value ?? $this->shadowProperties['color']['value'], - $sh_color_alpha ?? (int) $this->shadowProperties['color']['alpha'], - $sh_color_type ?? $this->shadowProperties['color']['type'] + $colorValue ?? $this->shadowProperties['color']['value'], + $colorAlpha ?? (int) $this->shadowProperties['color']['alpha'], + $colorType ?? $this->shadowProperties['color']['type'] ) - ->setShadowBlur($sh_blur) - ->setShadowAngle($sh_angle) - ->setShadowDistance($sh_distance); + ->setShadowBlur($blur) + ->setShadowAngle($angle) + ->setShadowDistance($distance); } /** * Set Shadow Color. * - * @param int $shadow_presets + * @param int $presets * * @return $this */ - private function setShadowPresetsProperties($shadow_presets) + private function setShadowPresetsProperties($presets) { - $this->shadowProperties['presets'] = $shadow_presets; - $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + $this->shadowProperties['presets'] = $presets; + $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets)); return $this; } @@ -369,17 +369,17 @@ private function setShadowPresetsProperties($shadow_presets) * * @return $this */ - private function setShadowProperiesMapValues(array $properties_map, &$reference = null) + private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null) { $base_reference = $reference; - foreach ($properties_map as $property_key => $property_val) { + foreach ($propertiesMap as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { $reference = &$this->shadowProperties[$property_key]; } else { $reference = &$reference[$property_key]; } - $this->setShadowProperiesMapValues($property_val, $reference); + $this->setShadowPropertiesMapValues($property_val, $reference); } else { if ($base_reference === null) { $this->shadowProperties[$property_key] = $property_val; @@ -397,13 +397,13 @@ private function setShadowProperiesMapValues(array $properties_map, &$reference * * @param string $color * @param int $alpha - * @param string $type + * @param string $alphaType * * @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; } @@ -472,17 +472,17 @@ public function getShadowProperty($elements) * Set Glow Properties. * * @param float $size - * @param string $color_value - * @param int $color_alpha - * @param string $color_type + * @param string $colorValue + * @param int $colorAlpha + * @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) ->setGlowColor( - $color_value ?? $this->glowProperties['color']['value'], - $color_alpha ?? (int) $this->glowProperties['color']['alpha'], - $color_type ?? $this->glowProperties['color']['type'] + $colorValue ?? $this->glowProperties['color']['value'], + $colorAlpha ?? (int) $this->glowProperties['color']['alpha'], + $colorType ?? $this->glowProperties['color']['type'] ); } @@ -519,13 +519,13 @@ private function setGlowSize($size) * * @param string $color * @param int $alpha - * @param string $type + * @param string $colorType * * @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; } diff --git a/src/PhpSpreadsheet/Chart/Chart.php b/src/PhpSpreadsheet/Chart/Chart.php index 4fdff6ffd9..106e44c6c6 100644 --- a/src/PhpSpreadsheet/Chart/Chart.php +++ b/src/PhpSpreadsheet/Chart/Chart.php @@ -186,13 +186,13 @@ public function getWorksheet() /** * Set Worksheet. * - * @param Worksheet $pValue + * @param Worksheet $worksheet * * @return $this */ - public function setWorksheet(?Worksheet $pValue = null) + public function setWorksheet(?Worksheet $worksheet = null) { - $this->worksheet = $pValue; + $this->worksheet = $worksheet; return $this; } diff --git a/src/PhpSpreadsheet/Chart/GridLines.php b/src/PhpSpreadsheet/Chart/GridLines.php index c388f2c988..84af3ada5a 100644 --- a/src/PhpSpreadsheet/Chart/GridLines.php +++ b/src/PhpSpreadsheet/Chart/GridLines.php @@ -105,73 +105,73 @@ private function activateObject() * * @param string $value * @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() ->lineProperties['color'] = $this->setColorProperties( $value, $alpha, - $type + $colorType ); } /** * Set Line Color Properties. * - * @param float $line_width - * @param string $compound_type - * @param string $dash_type - * @param string $cap_type - * @param string $join_type - * @param string $head_arrow_type - * @param string $head_arrow_size - * @param string $end_arrow_type - * @param string $end_arrow_size + * @param float $lineWidth + * @param string $compoundType + * @param string $dashType + * @param string $capType + * @param string $joinType + * @param string $headArrowType + * @param string $headArrowSize + * @param string $endArrowType + * @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(); - ($line_width !== null) - ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $line_width) + ($lineWidth !== null) + ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $lineWidth) : null; - ($compound_type !== null) - ? $this->lineProperties['style']['compound'] = (string) $compound_type + ($compoundType !== null) + ? $this->lineProperties['style']['compound'] = (string) $compoundType : null; - ($dash_type !== null) - ? $this->lineProperties['style']['dash'] = (string) $dash_type + ($dashType !== null) + ? $this->lineProperties['style']['dash'] = (string) $dashType : null; - ($cap_type !== null) - ? $this->lineProperties['style']['cap'] = (string) $cap_type + ($capType !== null) + ? $this->lineProperties['style']['cap'] = (string) $capType : null; - ($join_type !== null) - ? $this->lineProperties['style']['join'] = (string) $join_type + ($joinType !== null) + ? $this->lineProperties['style']['join'] = (string) $joinType : null; - ($head_arrow_type !== null) - ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $head_arrow_type + ($headArrowType !== null) + ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $headArrowType : null; - ($head_arrow_size !== null) - ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $head_arrow_size + ($headArrowSize !== null) + ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $headArrowSize : null; - ($end_arrow_type !== null) - ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $end_arrow_type + ($endArrowType !== null) + ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $endArrowType : null; - ($end_arrow_size !== null) - ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $end_arrow_size + ($endArrowSize !== null) + ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $endArrowSize : null; } /** * Get Line Color Property. * - * @param string $parameter + * @param string $propertyName * * @return string */ - public function getLineColorProperty($parameter) + public function getLineColorProperty($propertyName) { - return $this->lineProperties['color'][$parameter]; + return $this->lineProperties['color'][$propertyName]; } /** @@ -190,28 +190,28 @@ public function getLineStyleProperty($elements) * Set Glow Properties. * * @param float $size - * @param string $color_value - * @param int $color_alpha - * @param string $color_type + * @param string $colorValue + * @param int $colorAlpha + * @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 ->activateObject() ->setGlowSize($size) - ->setGlowColor($color_value, $color_alpha, $color_type); + ->setGlowColor($colorValue, $colorAlpha, $colorType); } /** * Get Glow Color Property. * - * @param string $property + * @param string $propertyName * * @return string */ - public function getGlowColor($property) + public function getGlowColor($propertyName) { - return $this->glowProperties['color'][$property]; + return $this->glowProperties['color'][$propertyName]; } /** @@ -243,11 +243,11 @@ private function setGlowSize($size) * * @param string $color * @param int $alpha - * @param string $type + * @param string $colorType * * @return $this */ - private function setGlowColor($color, $alpha, $type) + private function setGlowColor($color, $alpha, $colorType) { if ($color !== null) { $this->glowProperties['color']['value'] = (string) $color; @@ -255,8 +255,8 @@ private function setGlowColor($color, $alpha, $type) if ($alpha !== null) { $this->glowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); } - if ($type !== null) { - $this->glowProperties['color']['type'] = (string) $type; + if ($colorType !== null) { + $this->glowProperties['color']['type'] = (string) $colorType; } return $this; @@ -265,52 +265,52 @@ private function setGlowColor($color, $alpha, $type) /** * Get Line Style Arrow Parameters. * - * @param string $arrow_selector - * @param string $property_selector + * @param string $arrowSelector + * @param string $propertySelector * * @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. * - * @param int $sh_presets - * @param string $sh_color_value - * @param string $sh_color_type - * @param int $sh_color_alpha - * @param string $sh_blur - * @param int $sh_angle - * @param float $sh_distance + * @param int $presets + * @param string $colorValue + * @param string $colorType + * @param string $colorAlpha + * @param string $blur + * @param int $angle + * @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() - ->setShadowPresetsProperties((int) $sh_presets) + ->setShadowPresetsProperties((int) $presets) ->setShadowColor( - $sh_color_value ?? $this->shadowProperties['color']['value'], - $sh_color_alpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($sh_color_alpha), - $sh_color_type ?? $this->shadowProperties['color']['type'] + $colorValue ?? $this->shadowProperties['color']['value'], + $colorAlpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($colorAlpha), + $colorType ?? $this->shadowProperties['color']['type'] ) - ->setShadowBlur($sh_blur) - ->setShadowAngle($sh_angle) - ->setShadowDistance($sh_distance); + ->setShadowBlur((float) $blur) + ->setShadowAngle($angle) + ->setShadowDistance($distance); } /** * Set Shadow Presets Properties. * - * @param int $shadow_presets + * @param int $presets * * @return $this */ - private function setShadowPresetsProperties($shadow_presets) + private function setShadowPresetsProperties($presets) { - $this->shadowProperties['presets'] = $shadow_presets; - $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + $this->shadowProperties['presets'] = $presets; + $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets)); return $this; } @@ -322,17 +322,17 @@ private function setShadowPresetsProperties($shadow_presets) * * @return $this */ - private function setShadowProperiesMapValues(array $properties_map, &$reference = null) + private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null) { $base_reference = $reference; - foreach ($properties_map as $property_key => $property_val) { + foreach ($propertiesMap as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { $reference = &$this->shadowProperties[$property_key]; } else { $reference = &$reference[$property_key]; } - $this->setShadowProperiesMapValues($property_val, $reference); + $this->setShadowPropertiesMapValues($property_val, $reference); } else { if ($base_reference === null) { $this->shadowProperties[$property_key] = $property_val; @@ -350,11 +350,11 @@ private function setShadowProperiesMapValues(array $properties_map, &$reference * * @param string $color * @param int $alpha - * @param string $type + * @param string $colorType * * @return $this */ - private function setShadowColor($color, $alpha, $type) + private function setShadowColor($color, $alpha, $colorType) { if ($color !== null) { $this->shadowProperties['color']['value'] = (string) $color; @@ -362,8 +362,8 @@ private function setShadowColor($color, $alpha, $type) if ($alpha !== null) { $this->shadowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); } - if ($type !== null) { - $this->shadowProperties['color']['type'] = (string) $type; + if ($colorType !== null) { + $this->shadowProperties['color']['type'] = (string) $colorType; } return $this; diff --git a/src/PhpSpreadsheet/Chart/Layout.php b/src/PhpSpreadsheet/Chart/Layout.php index 51c8995b06..cea96557d8 100644 --- a/src/PhpSpreadsheet/Chart/Layout.php +++ b/src/PhpSpreadsheet/Chart/Layout.php @@ -149,13 +149,13 @@ public function getLayoutTarget() /** * Set Layout Target. * - * @param string $value + * @param string $target * * @return $this */ - public function setLayoutTarget($value) + public function setLayoutTarget($target) { - $this->layoutTarget = $value; + $this->layoutTarget = $target; return $this; } @@ -173,13 +173,13 @@ public function getXMode() /** * Set X-Mode. * - * @param string $value + * @param string $mode * * @return $this */ - public function setXMode($value) + public function setXMode($mode) { - $this->xMode = (string) $value; + $this->xMode = (string) $mode; return $this; } @@ -197,13 +197,13 @@ public function getYMode() /** * Set Y-Mode. * - * @param string $value + * @param string $mode * * @return $this */ - public function setYMode($value) + public function setYMode($mode) { - $this->yMode = (string) $value; + $this->yMode = (string) $mode; return $this; } @@ -221,13 +221,13 @@ public function getXPosition() /** * Set X-Position. * - * @param float $value + * @param float $position * * @return $this */ - public function setXPosition($value) + public function setXPosition($position) { - $this->xPos = (float) $value; + $this->xPos = (float) $position; return $this; } @@ -245,13 +245,13 @@ public function getYPosition() /** * Set Y-Position. * - * @param float $value + * @param float $position * * @return $this */ - public function setYPosition($value) + public function setYPosition($position) { - $this->yPos = (float) $value; + $this->yPos = (float) $position; return $this; } @@ -269,13 +269,13 @@ public function getWidth() /** * Set Width. * - * @param float $value + * @param float $width * * @return $this */ - public function setWidth($value) + public function setWidth($width) { - $this->width = $value; + $this->width = $width; return $this; } @@ -293,13 +293,13 @@ public function getHeight() /** * Set Height. * - * @param float $value + * @param float $height * * @return $this */ - public function setHeight($value) + public function setHeight($height) { - $this->height = $value; + $this->height = $height; return $this; } @@ -318,13 +318,13 @@ public function getShowLegendKey() * Set show legend key * Specifies that legend keys should be shown in data labels. * - * @param bool $value Show legend key + * @param bool $showLegendKey Show legend key * * @return $this */ - public function setShowLegendKey($value) + public function setShowLegendKey($showLegendKey) { - $this->showLegendKey = $value; + $this->showLegendKey = $showLegendKey; return $this; } @@ -343,13 +343,13 @@ public function getShowVal() * Set show val * Specifies that the value should be shown in data labels. * - * @param bool $value Show val + * @param bool $showDataLabelValues Show val * * @return $this */ - public function setShowVal($value) + public function setShowVal($showDataLabelValues) { - $this->showVal = $value; + $this->showVal = $showDataLabelValues; return $this; } @@ -368,13 +368,13 @@ public function getShowCatName() * Set show cat name * 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 */ - public function setShowCatName($value) + public function setShowCatName($showCategoryName) { - $this->showCatName = $value; + $this->showCatName = $showCategoryName; return $this; } @@ -393,13 +393,13 @@ public function getShowSerName() * Set show ser name * 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 */ - public function setShowSerName($value) + public function setShowSerName($showSeriesName) { - $this->showSerName = $value; + $this->showSerName = $showSeriesName; return $this; } @@ -418,13 +418,13 @@ public function getShowPercent() * Set show percentage * Specifies that the percentage should be shown in data labels. * - * @param bool $value Show percentage + * @param bool $showPercentage Show percentage * * @return $this */ - public function setShowPercent($value) + public function setShowPercent($showPercentage) { - $this->showPercent = $value; + $this->showPercent = $showPercentage; return $this; } @@ -443,13 +443,13 @@ public function getShowBubbleSize() * Set show bubble size * 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 */ - public function setShowBubbleSize($value) + public function setShowBubbleSize($showBubbleSize) { - $this->showBubbleSize = $value; + $this->showBubbleSize = $showBubbleSize; return $this; } @@ -468,13 +468,13 @@ public function getShowLeaderLines() * Set show leader lines * Specifies that leader lines should be shown in data labels. * - * @param bool $value Show leader lines + * @param bool $showLeaderLines Show leader lines * * @return $this */ - public function setShowLeaderLines($value) + public function setShowLeaderLines($showLeaderLines) { - $this->showLeaderLines = $value; + $this->showLeaderLines = $showLeaderLines; return $this; } diff --git a/src/PhpSpreadsheet/Chart/Properties.php b/src/PhpSpreadsheet/Chart/Properties.php index 98095f0d13..ef22fb5290 100644 --- a/src/PhpSpreadsheet/Chart/Properties.php +++ b/src/PhpSpreadsheet/Chart/Properties.php @@ -135,16 +135,16 @@ protected function getTrueAlpha($alpha) return (string) 100 - $alpha . '000'; } - protected function setColorProperties($color, $alpha, $type) + protected function setColorProperties($color, $alpha, $colorType) { return [ - 'type' => (string) $type, + 'type' => (string) $colorType, 'value' => (string) $color, 'alpha' => (string) $this->getTrueAlpha($alpha), ]; } - protected function getLineStyleArrowSize($array_selector, $array_kay_selector) + protected function getLineStyleArrowSize($arraySelector, $arrayKaySelector) { $sizes = [ 1 => ['w' => 'sm', 'len' => 'sm'], @@ -158,10 +158,10 @@ protected function getLineStyleArrowSize($array_selector, $array_kay_selector) 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 = [ //OUTER @@ -350,7 +350,7 @@ protected function getShadowPresetsMap($shadow_presets_option) ], ]; - return $presets_options[$shadow_presets_option]; + return $presets_options[$presetsOption]; } protected function getArrayElementsValue($properties, $elements) diff --git a/src/PhpSpreadsheet/Collection/Cells.php b/src/PhpSpreadsheet/Collection/Cells.php index c524709008..3bbf76fc44 100644 --- a/src/PhpSpreadsheet/Collection/Cells.php +++ b/src/PhpSpreadsheet/Collection/Cells.php @@ -86,18 +86,18 @@ public function getParent() /** * 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 */ - public function has($pCoord) + public function has($cellCoordinate) { - if ($pCoord === $this->currentCoordinate) { + if ($cellCoordinate === $this->currentCoordinate) { return true; } // Check if the requested entry exists in the index - return isset($this->index[$pCoord]); + return isset($this->index[$cellCoordinate]); } /** @@ -115,21 +115,21 @@ public function update(Cell $cell) /** * 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->currentCoordinate = null; $this->currentCell = null; $this->currentCellIsDirty = false; } - unset($this->index[$pCoord]); + unset($this->index[$cellCoordinate]); // Delete the entry from cache - $this->cache->delete($this->cachePrefix . $pCoord); + $this->cache->delete($this->cachePrefix . $cellCoordinate); } /** @@ -304,16 +304,16 @@ private function getUniqueID() /** * 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 */ - public function cloneCellCollection(Worksheet $parent) + public function cloneCellCollection(Worksheet $worksheet) { $this->storeCurrentCell(); $newCollection = clone $this; - $newCollection->parent = $parent; + $newCollection->parent = $worksheet; if (($newCollection->currentCell !== null) && (is_object($newCollection->currentCell))) { $newCollection->currentCell->attach($this); } @@ -402,19 +402,19 @@ private function storeCurrentCell(): void /** * 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 * * @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->index[$pCoord] = true; + $this->index[$cellCoordinate] = true; - $this->currentCoordinate = $pCoord; + $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; $this->currentCellIsDirty = true; @@ -424,30 +424,30 @@ public function add($pCoord, Cell $cell) /** * 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 */ - public function get($pCoord) + public function get($cellCoordinate) { - if ($pCoord === $this->currentCoordinate) { + if ($cellCoordinate === $this->currentCoordinate) { return $this->currentCell; } $this->storeCurrentCell(); // Return null if requested entry doesn't exist in collection - if (!$this->has($pCoord)) { + if (!$this->has($cellCoordinate)) { return null; } // 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) { - 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 - $this->currentCoordinate = $pCoord; + $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; // Re-attach this as the cell's parent $this->currentCell->attach($this); diff --git a/src/PhpSpreadsheet/Collection/CellsFactory.php b/src/PhpSpreadsheet/Collection/CellsFactory.php index 7f34c2315c..26f18dfc52 100644 --- a/src/PhpSpreadsheet/Collection/CellsFactory.php +++ b/src/PhpSpreadsheet/Collection/CellsFactory.php @@ -10,12 +10,12 @@ abstract class CellsFactory /** * Initialise the cache storage. * - * @param Worksheet $parent Enable cell caching for this worksheet + * @param Worksheet $worksheet Enable cell caching for this worksheet * * @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()); } } diff --git a/src/PhpSpreadsheet/Comment.php b/src/PhpSpreadsheet/Comment.php index 31f7664053..7aaf975970 100644 --- a/src/PhpSpreadsheet/Comment.php +++ b/src/PhpSpreadsheet/Comment.php @@ -2,7 +2,10 @@ namespace PhpOffice\PhpSpreadsheet; +use PhpOffice\PhpSpreadsheet\Helper\Size; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Style\Alignment; +use PhpOffice\PhpSpreadsheet\Style\Color; class Comment implements IComparable { @@ -58,7 +61,7 @@ class Comment implements IComparable /** * Comment fill color. * - * @var Style\Color + * @var Color */ private $fillColor; @@ -77,28 +80,22 @@ public function __construct() // Initialise variables $this->author = 'Author'; $this->text = new RichText(); - $this->fillColor = new Style\Color('FFFFFFE1'); - $this->alignment = Style\Alignment::HORIZONTAL_GENERAL; + $this->fillColor = new Color('FFFFFFE1'); + $this->alignment = Alignment::HORIZONTAL_GENERAL; } /** * Get Author. - * - * @return string */ - public function getAuthor() + public function getAuthor(): string { return $this->author; } /** * Set Author. - * - * @param string $author - * - * @return $this */ - public function setAuthor($author) + public function setAuthor(string $author): self { $this->author = $author; @@ -107,164 +104,146 @@ public function setAuthor($author) /** * Get Rich text comment. - * - * @return RichText */ - public function getText() + public function getText(): RichText { return $this->text; } /** * 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; } /** * Get comment width (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getWidth() + public function getWidth(): string { return $this->width; } /** - * Set comment width (CSS style, i.e. XXpx or YYpt). - * - * @param string $width - * - * @return $this + * Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - 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; } /** * Get comment height (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getHeight() + public function getHeight(): string { return $this->height; } /** - * Set comment height (CSS style, i.e. XXpx or YYpt). - * - * @param string $value - * - * @return $this + * Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - 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; } /** * Get left margin (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getMarginLeft() + public function getMarginLeft(): string { return $this->marginLeft; } /** - * Set left margin (CSS style, i.e. XXpx or YYpt). - * - * @param string $value - * - * @return $this + * Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - 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; } /** * Get top margin (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getMarginTop() + public function getMarginTop(): string { return $this->marginTop; } /** - * Set top margin (CSS style, i.e. XXpx or YYpt). - * - * @param string $value - * - * @return $this + * Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - 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; } /** * Is the comment visible by default? - * - * @return bool */ - public function getVisible() + public function getVisible(): bool { return $this->visible; } /** * Set comment default visibility. - * - * @param bool $value - * - * @return $this */ - public function setVisible($value) + public function setVisible(bool $visibility): self + { + $this->visible = $visibility; + + return $this; + } + + /** + * Set fill color. + */ + public function setFillColor(Color $color): self { - $this->visible = $value; + $this->fillColor = $color; return $this; } /** * Get fill color. - * - * @return Style\Color */ - public function getFillColor() + public function getFillColor(): Color { return $this->fillColor; } /** * Set Alignment. - * - * @param string $alignment see Style\Alignment::HORIZONTAL_* - * - * @return $this */ - public function setAlignment($alignment) + public function setAlignment(string $alignment): self { $this->alignment = $alignment; @@ -273,20 +252,16 @@ public function setAlignment($alignment) /** * Get Alignment. - * - * @return string */ - public function getAlignment() + public function getAlignment(): string { return $this->alignment; } /** * Get hash code. - * - * @return string Hash code */ - public function getHashCode() + public function getHashCode(): string { return md5( $this->author . @@ -319,10 +294,8 @@ public function __clone() /** * Convert to string. - * - * @return string */ - public function __toString() + public function __toString(): string { return $this->text->getPlainText(); } diff --git a/src/PhpSpreadsheet/DefinedName.php b/src/PhpSpreadsheet/DefinedName.php index 89ee01bec0..3b874b435b 100644 --- a/src/PhpSpreadsheet/DefinedName.php +++ b/src/PhpSpreadsheet/DefinedName.php @@ -167,9 +167,9 @@ public function getWorksheet(): ?Worksheet /** * Set worksheet. */ - public function setWorksheet(?Worksheet $value): self + public function setWorksheet(?Worksheet $worksheet): self { - $this->worksheet = $value; + $this->worksheet = $worksheet; return $this; } @@ -203,10 +203,10 @@ public function getLocalOnly(): bool /** * Set localOnly. */ - public function setLocalOnly(bool $value): self + public function setLocalOnly(bool $localScope): self { - $this->localOnly = $value; - $this->scope = $value ? $this->worksheet : null; + $this->localOnly = $localScope; + $this->scope = $localScope ? $this->worksheet : null; return $this; } @@ -222,10 +222,10 @@ public function getScope(): ?Worksheet /** * Set scope. */ - public function setScope(?Worksheet $value): self + public function setScope(?Worksheet $worksheet): self { - $this->scope = $value; - $this->localOnly = $value !== null; + $this->scope = $worksheet; + $this->localOnly = $worksheet !== null; return $this; } @@ -241,18 +241,18 @@ public function isFormula(): bool /** * 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 === '') { - $pSheet2 = $pSheet; + $worksheet2 = $worksheet; } else { - $pSheet2 = $pSheet->getParent()->getSheetByName($sheetName); - if ($pSheet2 === null) { + $worksheet2 = $worksheet->getParent()->getSheetByName($sheetName); + if ($worksheet2 === null) { return null; } } - return $pSheet->getParent()->getDefinedName($pDefinedName, $pSheet2); + return $worksheet->getParent()->getDefinedName($definedName, $worksheet2); } /** diff --git a/src/PhpSpreadsheet/Document/Properties.php b/src/PhpSpreadsheet/Document/Properties.php index 99e66756c2..3be5a67a85 100644 --- a/src/PhpSpreadsheet/Document/Properties.php +++ b/src/PhpSpreadsheet/Document/Properties.php @@ -151,9 +151,9 @@ public function getLastModifiedBy(): string * * @return $this */ - public function setLastModifiedBy(string $modifier): self + public function setLastModifiedBy(string $modifiedBy): self { - $this->lastModifiedBy = $modifier; + $this->lastModifiedBy = $modifiedBy; return $this; } @@ -434,7 +434,7 @@ private function identifyPropertyType($propertyValue): string * * @param mixed $propertyValue * @param string $propertyType - * 'i' : Integer + * 'i' : Integer * 'f' : Floating Point * 's' : String * 'd' : Date/Time diff --git a/src/PhpSpreadsheet/Document/Security.php b/src/PhpSpreadsheet/Document/Security.php index bdcc239373..279aed4372 100644 --- a/src/PhpSpreadsheet/Document/Security.php +++ b/src/PhpSpreadsheet/Document/Security.php @@ -63,10 +63,10 @@ public function getLockRevision(): bool return $this->lockRevision; } - public function setLockRevision(?bool $pValue): self + public function setLockRevision(?bool $locked): self { - if ($pValue !== null) { - $this->lockRevision = $pValue; + if ($locked !== null) { + $this->lockRevision = $locked; } return $this; @@ -77,10 +77,10 @@ public function getLockStructure(): bool return $this->lockStructure; } - public function setLockStructure(?bool $pValue): self + public function setLockStructure(?bool $locked): self { - if ($pValue !== null) { - $this->lockStructure = $pValue; + if ($locked !== null) { + $this->lockStructure = $locked; } return $this; @@ -91,10 +91,10 @@ public function getLockWindows(): bool return $this->lockWindows; } - public function setLockWindows(?bool $pValue): self + public function setLockWindows(?bool $locked): self { - if ($pValue !== null) { - $this->lockWindows = $pValue; + if ($locked !== null) { + $this->lockWindows = $locked; } return $this; @@ -105,13 +105,21 @@ public function getRevisionsPassword(): string 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 (!$pAlreadyHashed) { - $pValue = PasswordHasher::hashPassword($pValue); + if ($password !== null) { + if (!$alreadyHashed) { + $password = PasswordHasher::hashPassword($password); } - $this->revisionsPassword = $pValue; + $this->revisionsPassword = $password; } return $this; @@ -122,13 +130,21 @@ public function getWorkbookPassword(): string 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 (!$pAlreadyHashed) { - $pValue = PasswordHasher::hashPassword($pValue); + if ($password !== null) { + if (!$alreadyHashed) { + $password = PasswordHasher::hashPassword($password); } - $this->workbookPassword = $pValue; + $this->workbookPassword = $password; } return $this; diff --git a/src/PhpSpreadsheet/HashTable.php b/src/PhpSpreadsheet/HashTable.php index 8cf8281e0f..59209eed96 100644 --- a/src/PhpSpreadsheet/HashTable.php +++ b/src/PhpSpreadsheet/HashTable.php @@ -10,43 +10,43 @@ class HashTable /** * HashTable elements. * - * @var T[] + * @var array */ protected $items = []; /** * HashTable key map. * - * @var string[] + * @var array */ 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 - $this->addFromSource($pSource); + $this->addFromSource($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 - if ($pSource == null) { + if ($source === null) { return; } - foreach ($pSource as $item) { + foreach ($source as $item) { $this->add($item); } } @@ -54,13 +54,13 @@ public function addFromSource(?array $pSource = null): void /** * 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])) { - $this->items[$hash] = $pSource; + $this->items[$hash] = $source; $this->keyMap[count($this->items) - 1] = $hash; } } @@ -68,11 +68,11 @@ public function add(IComparable $pSource): void /** * 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])) { unset($this->items[$hash]); @@ -112,26 +112,22 @@ public function count() /** * Get index for hash code. * - * @param string $pHashCode - * - * @return int Index + * @return false|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. * - * @param int $pIndex - * * @return null|T */ - public function getByIndex($pIndex) + public function getByIndex(int $index) { - if (isset($this->keyMap[$pIndex])) { - return $this->getByHashCode($this->keyMap[$pIndex]); + if (isset($this->keyMap[$index])) { + return $this->getByHashCode($this->keyMap[$index]); } return null; @@ -140,14 +136,12 @@ public function getByIndex($pIndex) /** * Get by hashcode. * - * @param string $pHashCode - * * @return null|T */ - public function getByHashCode($pHashCode) + public function getByHashCode(string $hashCode) { - if (isset($this->items[$pHashCode])) { - return $this->items[$pHashCode]; + if (isset($this->items[$hashCode])) { + return $this->items[$hashCode]; } return null; diff --git a/src/PhpSpreadsheet/Helper/Html.php b/src/PhpSpreadsheet/Helper/Html.php index f07bc961c5..73a3308c24 100644 --- a/src/PhpSpreadsheet/Helper/Html.php +++ b/src/PhpSpreadsheet/Helper/Html.php @@ -684,9 +684,9 @@ protected function buildTextRun(): void $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) { $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); } @@ -694,9 +694,9 @@ protected function rgbToColour($rgb) 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 diff --git a/src/PhpSpreadsheet/Helper/Size.php b/src/PhpSpreadsheet/Helper/Size.php new file mode 100644 index 0000000000..12ba4ef732 --- /dev/null +++ b/src/PhpSpreadsheet/Helper/Size.php @@ -0,0 +1,52 @@ +\d*\.?\d+)(?Ppt|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; + } +} diff --git a/src/PhpSpreadsheet/IOFactory.php b/src/PhpSpreadsheet/IOFactory.php index 6ed1fd82f2..91613cb440 100644 --- a/src/PhpSpreadsheet/IOFactory.php +++ b/src/PhpSpreadsheet/IOFactory.php @@ -2,7 +2,9 @@ namespace PhpOffice\PhpSpreadsheet; +use PhpOffice\PhpSpreadsheet\Reader\IReader; use PhpOffice\PhpSpreadsheet\Shared\File; +use PhpOffice\PhpSpreadsheet\Writer\IWriter; /** * Factory to create readers and writers easily. @@ -36,12 +38,8 @@ abstract class IOFactory /** * 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])) { throw new Writer\Exception("No writer found for type $writerType"); @@ -54,13 +52,9 @@ public static function createWriter(Spreadsheet $spreadsheet, $writerType) } /** - * Create Reader\IReader. - * - * @param string $readerType Example: Xlsx - * - * @return Reader\IReader + * Create IReader. */ - public static function createReader($readerType) + public static function createReader(string $readerType): IReader { if (!isset(self::$readers[$readerType])) { throw new Reader\Exception("No reader found for type $readerType"); @@ -76,10 +70,8 @@ public static function createReader($readerType) * Loads Spreadsheet from file using automatic Reader\IReader resolution. * * @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); @@ -87,15 +79,11 @@ public static function load(string $filename, int $flags = 0) } /** - * Identify file type using automatic Reader\IReader resolution. - * - * @param string $pFilename The name of the spreadsheet file to identify - * - * @return string + * Identify file type using automatic IReader resolution. */ - public static function identify($pFilename) + public static function identify(string $filename): string { - $reader = self::createReaderForFile($pFilename); + $reader = self::createReaderForFile($filename); $className = get_class($reader); $classType = explode('\\', $className); unset($reader); @@ -104,13 +92,9 @@ public static function identify($pFilename) } /** - * Create Reader\IReader for file using automatic Reader\IReader resolution. - * - * @param string $filename The name of the spreadsheet file - * - * @return Reader\IReader + * Create Reader\IReader for file using automatic IReader resolution. */ - public static function createReaderForFile($filename) + public static function createReaderForFile(string $filename): IReader { File::assertFile($filename); @@ -142,12 +126,8 @@ public static function createReaderForFile($filename) /** * 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); if (!isset($pathinfo['extension'])) { @@ -187,14 +167,11 @@ private static function getReaderTypeFromExtension($filename) /** * 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)) { - throw new Writer\Exception('Registered writers must implement ' . Writer\IWriter::class); + if (!is_a($writerClass, IWriter::class, true)) { + throw new Writer\Exception('Registered writers must implement ' . IWriter::class); } self::$writers[$writerType] = $writerClass; @@ -202,14 +179,11 @@ public static function registerWriter($writerType, $writerClass): void /** * 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)) { - throw new Reader\Exception('Registered readers must implement ' . Reader\IReader::class); + if (!is_a($readerClass, IReader::class, true)) { + throw new Reader\Exception('Registered readers must implement ' . IReader::class); } self::$readers[$readerType] = $readerClass; diff --git a/src/PhpSpreadsheet/Reader/BaseReader.php b/src/PhpSpreadsheet/Reader/BaseReader.php index 1f18484ff7..2ad8e6b20a 100644 --- a/src/PhpSpreadsheet/Reader/BaseReader.php +++ b/src/PhpSpreadsheet/Reader/BaseReader.php @@ -66,9 +66,9 @@ public function getReadDataOnly() return $this->readDataOnly; } - public function setReadDataOnly($pValue) + public function setReadDataOnly($readCellValuesOnly) { - $this->readDataOnly = (bool) $pValue; + $this->readDataOnly = (bool) $readCellValuesOnly; return $this; } @@ -78,9 +78,9 @@ public function getReadEmptyCells() return $this->readEmptyCells; } - public function setReadEmptyCells($pValue) + public function setReadEmptyCells($readEmptyCells) { - $this->readEmptyCells = (bool) $pValue; + $this->readEmptyCells = (bool) $readEmptyCells; return $this; } @@ -90,9 +90,9 @@ public function getIncludeCharts() return $this->includeCharts; } - public function setIncludeCharts($pValue) + public function setIncludeCharts($includeCharts) { - $this->includeCharts = (bool) $pValue; + $this->includeCharts = (bool) $includeCharts; return $this; } @@ -102,13 +102,13 @@ public function getLoadSheetsOnly() return $this->loadSheetsOnly; } - public function setLoadSheetsOnly($value) + public function setLoadSheetsOnly($sheetList) { - if ($value === null) { + if ($sheetList === null) { return $this->setLoadAllSheets(); } - $this->loadSheetsOnly = is_array($value) ? $value : [$value]; + $this->loadSheetsOnly = is_array($sheetList) ? $sheetList : [$sheetList]; return $this; } @@ -125,9 +125,9 @@ public function getReadFilter() return $this->readFilter; } - public function setReadFilter(IReadFilter $pValue) + public function setReadFilter(IReadFilter $readFilter) { - $this->readFilter = $pValue; + $this->readFilter = $readFilter; return $this; } @@ -147,22 +147,22 @@ protected function processFlags(int $flags): void /** * Open file for reading. * - * @param string $pFilename + * @param string $filename */ - protected function openFile($pFilename): void + protected function openFile($filename): void { - if ($pFilename) { - File::assertFile($pFilename); + if ($filename) { + File::assertFile($filename); // Open file - $fileHandle = fopen($pFilename, 'rb'); + $fileHandle = fopen($filename, 'rb'); } else { $fileHandle = false; } if ($fileHandle !== false) { $this->fileHandle = $fileHandle; } else { - throw new ReaderException('Could not open file ' . $pFilename . ' for reading.'); + throw new ReaderException('Could not open file ' . $filename . ' for reading.'); } } } diff --git a/src/PhpSpreadsheet/Reader/Csv.php b/src/PhpSpreadsheet/Reader/Csv.php index a8567bea05..50426c4fb1 100644 --- a/src/PhpSpreadsheet/Reader/Csv.php +++ b/src/PhpSpreadsheet/Reader/Csv.php @@ -111,9 +111,9 @@ public static function getConstructorCallback(): ?callable return self::$constructorCallback; } - public function setInputEncoding(string $pValue): self + public function setInputEncoding(string $encoding): self { - $this->inputEncoding = $pValue; + $this->inputEncoding = $encoding; return $this; } @@ -198,10 +198,10 @@ protected function inferSeparator(): void /** * 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 - $this->openFileOrMemory($pFilename); + $this->openFileOrMemory($filename); $fileHandle = $this->fileHandle; // Skip BOM, if any @@ -238,7 +238,7 @@ public function listWorksheetInfo(string $pFilename): array * * @return Spreadsheet */ - public function load(string $pFilename, int $flags = 0) + public function load(string $filename, int $flags = 0) { $this->processFlags($flags); @@ -246,23 +246,23 @@ public function load(string $pFilename, int $flags = 0) $spreadsheet = new Spreadsheet(); // 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 - $fhandle = $this->canRead($pFilename); + $fhandle = $this->canRead($filename); 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) { - $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') { fclose($this->fileHandle); - $entireFile = file_get_contents($pFilename); + $entireFile = file_get_contents($filename); $this->fileHandle = fopen('php://memory', 'r+b'); if ($this->fileHandle !== false && $entireFile !== false) { $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); @@ -288,13 +288,13 @@ private static function setAutoDetect(?string $value): ?string /** * 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 $iniset = self::setAutoDetect('1'); // Open file - $this->openFileOrMemory($pFilename); + $this->openFileOrMemory($filename); $fileHandle = $this->fileHandle; // Skip BOM, if any @@ -396,9 +396,9 @@ public function getSheetIndex(): int return $this->sheetIndex; } - public function setSheetIndex(int $pValue): self + public function setSheetIndex(int $indexValue): self { - $this->sheetIndex = $pValue; + $this->sheetIndex = $indexValue; return $this; } @@ -427,27 +427,14 @@ public function getEscapeCharacter(): string 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? */ - public function canRead(string $pFilename): bool + public function canRead(string $filename): bool { // Check if file exists try { - $this->openFile($pFilename); + $this->openFile($filename); } catch (ReaderException $e) { return false; } @@ -455,13 +442,13 @@ public function canRead(string $pFilename): bool fclose($this->fileHandle); // Trust file extension if any - $extension = self::extractStringLower(pathinfo($pFilename, PATHINFO_EXTENSION)); + $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (in_array($extension, ['csv', 'tsv'])) { return true; } // Attempt to guess mimetype - $type = mime_content_type($pFilename); + $type = mime_content_type($filename); $supportedTypes = [ 'application/csv', 'text/csv', diff --git a/src/PhpSpreadsheet/Reader/DefaultReadFilter.php b/src/PhpSpreadsheet/Reader/DefaultReadFilter.php index e104186abb..8fdb162b4c 100644 --- a/src/PhpSpreadsheet/Reader/DefaultReadFilter.php +++ b/src/PhpSpreadsheet/Reader/DefaultReadFilter.php @@ -7,13 +7,13 @@ class DefaultReadFilter implements IReadFilter /** * 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 string $worksheetName Optional worksheet name * * @return bool */ - public function readCell($column, $row, $worksheetName = '') + public function readCell($columnAddress, $row, $worksheetName = '') { return true; } diff --git a/src/PhpSpreadsheet/Reader/Gnumeric.php b/src/PhpSpreadsheet/Reader/Gnumeric.php index 42838c6120..673a8a073f 100644 --- a/src/PhpSpreadsheet/Reader/Gnumeric.php +++ b/src/PhpSpreadsheet/Reader/Gnumeric.php @@ -78,20 +78,19 @@ public function __construct() /** * 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 - if (File::testFileNoThrow($pFilename) && function_exists('gzread')) { + if (File::testFileNoThrow($filename) && function_exists('gzread')) { // Read signature data (first 3 bytes) - $fh = fopen($pFilename, 'rb'); + $fh = fopen($filename, 'rb'); if ($fh !== false) { $data = fread($fh, 2); 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 @@ -231,7 +230,7 @@ private static function testSimpleXml($value): SimpleXMLElement * * @return Spreadsheet */ - public function load(string $pFilename, int $flags = 0) + public function load(string $filename, int $flags = 0) { $this->processFlags($flags); @@ -240,7 +239,7 @@ public function load(string $pFilename, int $flags = 0) $spreadsheet->removeSheetByIndex(0); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } /** diff --git a/src/PhpSpreadsheet/Reader/Html.php b/src/PhpSpreadsheet/Reader/Html.php index 7bd1b31df3..ac763c92b5 100644 --- a/src/PhpSpreadsheet/Reader/Html.php +++ b/src/PhpSpreadsheet/Reader/Html.php @@ -138,11 +138,11 @@ public function __construct() /** * 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 try { - $this->openFile($pFilename); + $this->openFile($filename); } catch (Exception $e) { return false; } @@ -204,7 +204,7 @@ private static function containsTags(string $data): bool * * @return Spreadsheet */ - public function load(string $pFilename, int $flags = 0) + public function load(string $filename, int $flags = 0) { $this->processFlags($flags); @@ -212,7 +212,7 @@ public function load(string $pFilename, int $flags = 0) $spreadsheet = new Spreadsheet(); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } /** @@ -630,7 +630,7 @@ protected function processDomElement(DOMNode $element, Worksheet $sheet, int &$r $cellContent .= $domText; } // but if we have a rich text run instead, we need to append it correctly - // TODO + // TODO } elseif ($child instanceof DOMElement) { $this->processDomElementBody($sheet, $row, $column, $cellContent, $child); } @@ -948,8 +948,8 @@ public function getStyleColor($value) } /** - * @param string $column - * @param int $row + * @param string $column + * @param int $row */ private function insertImage(Worksheet $sheet, $column, $row, array $attributes): void { @@ -1016,7 +1016,7 @@ public static function getBorderMappings(): array /** * Map html border style to PhpSpreadsheet border style. * - * @param string $style + * @param string $style * * @return null|string */ diff --git a/src/PhpSpreadsheet/Reader/IReadFilter.php b/src/PhpSpreadsheet/Reader/IReadFilter.php index ccfe05ada6..9f68a7f360 100644 --- a/src/PhpSpreadsheet/Reader/IReadFilter.php +++ b/src/PhpSpreadsheet/Reader/IReadFilter.php @@ -7,11 +7,11 @@ interface IReadFilter /** * 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 string $worksheetName Optional worksheet name * * @return bool */ - public function readCell($column, $row, $worksheetName = ''); + public function readCell($columnAddress, $row, $worksheetName = ''); } diff --git a/src/PhpSpreadsheet/Reader/IReader.php b/src/PhpSpreadsheet/Reader/IReader.php index 447123cc96..63059693e2 100644 --- a/src/PhpSpreadsheet/Reader/IReader.php +++ b/src/PhpSpreadsheet/Reader/IReader.php @@ -14,7 +14,7 @@ public function __construct(); /** * Can the current IReader read the file? */ - public function canRead(string $pFilename): bool; + public function canRead(string $filename): bool; /** * Read data only? @@ -125,5 +125,5 @@ public function setReadFilter(IReadFilter $pValue); * * @return \PhpOffice\PhpSpreadsheet\Spreadsheet */ - public function load(string $pFilename, int $flags = 0); + public function load(string $filename, int $flags = 0); } diff --git a/src/PhpSpreadsheet/Reader/Ods.php b/src/PhpSpreadsheet/Reader/Ods.php index 16b4a3467f..80ad43c63d 100644 --- a/src/PhpSpreadsheet/Reader/Ods.php +++ b/src/PhpSpreadsheet/Reader/Ods.php @@ -41,15 +41,15 @@ public function __construct() /** * Can the current IReader read the file? */ - public function canRead(string $pFilename): bool + public function canRead(string $filename): bool { $mimeType = 'UNKNOWN'; // Load file - if (File::testFileNoThrow($pFilename)) { + if (File::testFileNoThrow($filename)) { $zip = new ZipArchive(); - if ($zip->open($pFilename) === true) { + if ($zip->open($filename) === true) { // check if it is an OOXML archive $stat = $zip->statName('mimetype'); if ($stat && ($stat['size'] <= 255)) { @@ -220,7 +220,7 @@ public function listWorksheetInfo($pFilename) * * @return Spreadsheet */ - public function load(string $pFilename, int $flags = 0) + public function load(string $filename, int $flags = 0) { $this->processFlags($flags); @@ -228,7 +228,7 @@ public function load(string $pFilename, int $flags = 0) $spreadsheet = new Spreadsheet(); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } /** diff --git a/src/PhpSpreadsheet/Reader/Slk.php b/src/PhpSpreadsheet/Reader/Slk.php index 794180c788..5e1525d6bb 100644 --- a/src/PhpSpreadsheet/Reader/Slk.php +++ b/src/PhpSpreadsheet/Reader/Slk.php @@ -65,10 +65,10 @@ public function __construct() /** * Validate that the current file is a SYLK file. */ - public function canRead(string $pFilename): bool + public function canRead(string $filename): bool { try { - $this->openFile($pFilename); + $this->openFile($filename); } catch (ReaderException $e) { return false; } @@ -194,7 +194,7 @@ public function listWorksheetInfo($pFilename) * * @return Spreadsheet */ - public function load(string $pFilename, int $flags = 0) + public function load(string $filename, int $flags = 0) { $this->processFlags($flags); @@ -202,7 +202,7 @@ public function load(string $pFilename, int $flags = 0) $spreadsheet = new Spreadsheet(); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } private const COLOR_ARRAY = [ diff --git a/src/PhpSpreadsheet/Reader/Xls.php b/src/PhpSpreadsheet/Reader/Xls.php index 13af96889a..aa8a5bc534 100644 --- a/src/PhpSpreadsheet/Reader/Xls.php +++ b/src/PhpSpreadsheet/Reader/Xls.php @@ -420,9 +420,9 @@ public function __construct() /** * 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; } @@ -431,7 +431,7 @@ public function canRead(string $pFilename): bool $ole = new OLERead(); // get excel data - $ole->read($pFilename); + $ole->read($filename); return true; } catch (PhpSpreadsheetException $e) { @@ -623,12 +623,12 @@ public function listWorksheetInfo($pFilename) * * @return Spreadsheet */ - public function load(string $pFilename, int $flags = 0) + public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Read the OLE file - $this->loadOLE($pFilename); + $this->loadOLE($filename); // Initialisations $this->spreadsheet = new Spreadsheet(); @@ -1297,7 +1297,7 @@ public function load(string $pFilename, int $flags = 0) } } // Named Value - // TODO Provide support for named values + // TODO Provide support for named values } } $this->data = ''; @@ -3032,7 +3032,7 @@ private function readSst(): void $len = min($charsLeft, $limitpos - $pos); for ($j = 0; $j < $len; ++$j) { $retstr .= $recordData[$pos + $j] - . chr(0); + . chr(0); } $charsLeft -= $len; $isCompressed = false; diff --git a/src/PhpSpreadsheet/Reader/Xlsx.php b/src/PhpSpreadsheet/Reader/Xlsx.php index df1941fb1b..59403c6424 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx.php +++ b/src/PhpSpreadsheet/Reader/Xlsx.php @@ -75,16 +75,16 @@ public function __construct() /** * 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; } $result = false; $this->zip = $zip = new ZipArchive(); - if ($zip->open($pFilename) === true) { + if ($zip->open($filename) === true) { [$workbookBasename] = $this->getWorkbookBaseName(); $result = !empty($workbookBasename); @@ -162,18 +162,18 @@ private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElem /** * 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 */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename, self::INITIAL_FILE); + File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $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 $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); @@ -201,18 +201,18 @@ public function listWorksheetNames($pFilename) /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename, self::INITIAL_FILE); + File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; $this->zip = $zip = new ZipArchive(); - $zip->open($pFilename); + $zip->open($filename); $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); foreach ($rels->Relationship as $relx) { @@ -252,7 +252,7 @@ public function listWorksheetInfo($pFilename) $xml = new XMLReader(); $xml->xml( $this->securityScanner->scanFile( - 'zip://' . File::realpath($pFilename) . '#' . $fileWorksheetPath + 'zip://' . File::realpath($filename) . '#' . $fileWorksheetPath ), null, Settings::getLibXmlLoaderOptions() @@ -387,9 +387,9 @@ private function getFromZipArchive(ZipArchive $archive, $fileName = '') /** * 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); // Initialisations @@ -401,7 +401,7 @@ public function load(string $pFilename, int $flags = 0): Spreadsheet $unparsedLoadedData = []; $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 [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName(); @@ -1106,7 +1106,7 @@ public function load(string $pFilename, int $flags = 0): Spreadsheet $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']]->setWidth($style['width']); $hfImages[(string) $shape['id']]->setHeight($style['height']); @@ -1124,12 +1124,12 @@ public function load(string $pFilename, int $flags = 0): Spreadsheet } // TODO: Autoshapes from twoCellAnchors! - $filename = dirname("$dir/$fileWorksheet") + $drawingFilename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; - if ($zip->locateName($filename)) { - $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); + if ($zip->locateName($drawingFilename)) { + $relsWorksheet = $this->loadZipNoNamespace($drawingFilename, Namespaces::RELATIONSHIPS); $drawings = []; foreach ($relsWorksheet->Relationship as $ele) { if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { @@ -1142,8 +1142,8 @@ public function load(string $pFilename, int $flags = 0): Spreadsheet foreach ($xmlSheet->drawing as $drawing) { $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); $fileDrawing = $drawings[$drawingRelId]; - $filename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels'; - $relsDrawing = $this->loadZipNoNamespace($filename, $xmlNamespaceBase); + $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels'; + $relsDrawing = $this->loadZipNoNamespace($drawingFilename, $xmlNamespaceBase); $images = []; $hyperlinks = []; if ($relsDrawing && $relsDrawing->Relationship) { @@ -1188,7 +1188,7 @@ public function load(string $pFilename, int $flags = 0): Spreadsheet ); if (isset($images[$embedImageKey])) { $objDrawing->setPath( - 'zip://' . File::realpath($pFilename) . '#' . + 'zip://' . File::realpath($filename) . '#' . $images[$embedImageKey], false ); @@ -1267,7 +1267,7 @@ public function load(string $pFilename, int $flags = 0): Spreadsheet ); if (isset($images[$embedImageKey])) { $objDrawing->setPath( - 'zip://' . File::realpath($pFilename) . '#' . + 'zip://' . File::realpath($filename) . '#' . $images[$embedImageKey], false ); diff --git a/src/PhpSpreadsheet/Reader/Xml.php b/src/PhpSpreadsheet/Reader/Xml.php index cee7a5e050..7d9188a96a 100644 --- a/src/PhpSpreadsheet/Reader/Xml.php +++ b/src/PhpSpreadsheet/Reader/Xml.php @@ -54,7 +54,7 @@ public static function xmlMappings(): array /** * 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" // Excel xmlns:x="urn:schemas-microsoft-com:office:excel" @@ -72,7 +72,7 @@ public function canRead(string $pFilename): bool ]; // Open file - $data = file_get_contents($pFilename); + $data = file_get_contents($filename); // Why? //$data = str_replace("'", '"', $data); // fix headers with single quote @@ -234,7 +234,7 @@ public function listWorksheetInfo($filename) * * @return Spreadsheet */ - public function load(string $pFilename, int $flags = 0) + public function load(string $filename, int $flags = 0) { $this->processFlags($flags); @@ -243,7 +243,7 @@ public function load(string $pFilename, int $flags = 0) $spreadsheet->removeSheetByIndex(0); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } /** diff --git a/src/PhpSpreadsheet/ReferenceHelper.php b/src/PhpSpreadsheet/ReferenceHelper.php index 660a877849..31f5ecef82 100644 --- a/src/PhpSpreadsheet/ReferenceHelper.php +++ b/src/PhpSpreadsheet/ReferenceHelper.php @@ -119,26 +119,26 @@ public static function cellReverseSort($a, $b) * * @param string $cellAddress Address of the cell we're testing * @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 $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 */ - private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) + private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfCols) { [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); // Is cell within the range of rows/columns if we're deleting if ( - $pNumRows < 0 && - ($cellRow >= ($beforeRow + $pNumRows)) && + $numberOfRows < 0 && + ($cellRow >= ($beforeRow + $numberOfRows)) && ($cellRow < $beforeRow) ) { return true; } elseif ( - $pNumCols < 0 && - ($cellColumnIndex >= ($beforeColumnIndex + $pNumCols)) && + $numberOfCols < 0 && + ($cellColumnIndex >= ($beforeColumnIndex + $numberOfCols)) && ($cellColumnIndex < $beforeColumnIndex) ) { return true; @@ -150,30 +150,30 @@ private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNum /** * Update page breaks when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param Worksheet $worksheet The worksheet that we're editing + * @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 $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 $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(); - ($pNumCols > 0 || $pNumRows > 0) ? + $aBreaks = $worksheet->getBreaks(); + ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aBreaks, ['self', 'cellReverseSort']) : uksort($aBreaks, ['self', 'cellSort']); 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 // of rows/columns that we're deleting - $pSheet->setBreak($key, Worksheet::BREAK_NONE); + $worksheet->setBreak($key, Worksheet::BREAK_NONE); } else { // Otherwise update any affected breaks by inserting a new break at the appropriate point // and removing the old affected break - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($key != $newReference) { - $pSheet->setBreak($newReference, $value) + $worksheet->setBreak($newReference, $value) ->setBreak($key, Worksheet::BREAK_NONE); } } @@ -183,51 +183,49 @@ protected function adjustPageBreaks(Worksheet $pSheet, $pBefore, $beforeColumnIn /** * Update cell comments when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param Worksheet $worksheet The worksheet that we're editing + * @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 $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 $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 foreach ($aComments as $key => &$value) { // 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 - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); $aNewComments[$newReference] = $value; } } // Replace the comments array with the new set of comments - $pSheet->setComments($aNewComments); + $worksheet->setComments($aNewComments); } /** * Update hyperlinks when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @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 $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows 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(); - ($pNumCols > 0 || $pNumRows > 0) ? + $aHyperlinkCollection = $worksheet->getHyperlinkCollection(); + ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : uksort($aHyperlinkCollection, ['self', 'cellSort']); foreach ($aHyperlinkCollection as $key => $value) { - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($key != $newReference) { - $pSheet->setHyperlink($newReference, $value); - $pSheet->setHyperlink($key, null); + $worksheet->setHyperlink($newReference, $value); + $worksheet->setHyperlink($key, null); } } } @@ -235,24 +233,22 @@ protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNum /** * 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 int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ - protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void + protected function adjustDataValidations(Worksheet $worksheet, $pBefore, $pNumCols, $pNumRows): void { - $aDataValidationCollection = $pSheet->getDataValidationCollection(); + $aDataValidationCollection = $worksheet->getDataValidationCollection(); ($pNumCols > 0 || $pNumRows > 0) ? uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']); foreach ($aDataValidationCollection as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); if ($key != $newReference) { - $pSheet->setDataValidation($newReference, $value); - $pSheet->setDataValidation($key, null); + $worksheet->setDataValidation($newReference, $value); + $worksheet->setDataValidation($key, null); } } } @@ -260,44 +256,40 @@ protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, /** * Update merged cells when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @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 $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows 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 foreach ($aMergeCells as $key => &$value) { - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); $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. * - * @param Worksheet $pSheet The worksheet that we're editing - * @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 $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows 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(); - ($pNumCols > 0 || $pNumRows > 0) ? + $aProtectedCells = $worksheet->getProtectedCells(); + ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aProtectedCells, ['self', 'cellReverseSort']) : uksort($aProtectedCells, ['self', 'cellSort']); foreach ($aProtectedCells as $key => $value) { - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($key != $newReference) { - $pSheet->protectCells($newReference, $value, true); - $pSheet->unprotectCells($key); + $worksheet->protectCells($newReference, $value, true); + $worksheet->unprotectCells($key); } } } @@ -305,54 +297,51 @@ protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $ /** * Update column dimensions when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @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 $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows 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)) { 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); if ($objColumnDimension->getColumnIndex() != $newReference) { $objColumnDimension->setColumnIndex($newReference); } } - $pSheet->refreshColumnDimensions(); + $worksheet->refreshColumnDimensions(); } } /** * Update row dimensions when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @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 Worksheet $worksheet The worksheet that we're editing + * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') + * @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 $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)) { 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); if ($objRowDimension->getRowIndex() != $newReference) { $objRowDimension->setRowIndex($newReference); } } - $pSheet->refreshRowDimensions(); + $worksheet->refreshRowDimensions(); - $copyDimension = $pSheet->getRowDimension($beforeRow - 1); - for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) { - $newDimension = $pSheet->getRowDimension($i); + $copyDimension = $worksheet->getRowDimension($beforeRow - 1); + for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) { + $newDimension = $worksheet->getRowDimension($i); $newDimension->setRowHeight($copyDimension->getRowHeight()); $newDimension->setVisible($copyDimension->getVisible()); $newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); @@ -364,46 +353,46 @@ protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $p /** * Insert a new column or row, updating all possible related data. * - * @param string $pBefore Insert before this cell address (e.g. 'A1') - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) - * @param Worksheet $pSheet The worksheet that we're editing + * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1') + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) + * @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); - $allCoordinates = $pSheet->getCoordinates(); + $remove = ($numberOfColumns < 0 || $numberOfRows < 0); + $allCoordinates = $worksheet->getCoordinates(); - // Get coordinate of $pBefore - [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($pBefore); + // Get coordinate of $beforeCellAddress + [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress); // Clear cells if we are removing columns or rows - $highestColumn = $pSheet->getHighestColumn(); - $highestRow = $pSheet->getHighestRow(); + $highestColumn = $worksheet->getHighestColumn(); + $highestRow = $worksheet->getHighestRow(); // 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 ($j = $beforeColumn - 1 + $pNumCols; $j <= $beforeColumn - 2; ++$j) { + for ($j = $beforeColumn - 1 + $numberOfColumns; $j <= $beforeColumn - 2; ++$j) { $coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i; - $pSheet->removeConditionalStyles($coordinate); - if ($pSheet->cellExists($coordinate)) { - $pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); - $pSheet->getCell($coordinate)->setXfIndex(0); + $worksheet->removeConditionalStyles($coordinate); + if ($worksheet->cellExists($coordinate)) { + $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); + $worksheet->getCell($coordinate)->setXfIndex(0); } } } } // 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 ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) { + for ($j = $beforeRow + $numberOfRows; $j <= $beforeRow - 1; ++$j) { $coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j; - $pSheet->removeConditionalStyles($coordinate); - if ($pSheet->cellExists($coordinate)) { - $pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); - $pSheet->getCell($coordinate)->setXfIndex(0); + $worksheet->removeConditionalStyles($coordinate); + if ($worksheet->cellExists($coordinate)) { + $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); + $worksheet->getCell($coordinate)->setXfIndex(0); } } } @@ -415,85 +404,85 @@ public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pShee $allCoordinates = array_reverse($allCoordinates); } while ($coordinate = array_pop($allCoordinates)) { - $cell = $pSheet->getCell($coordinate); + $cell = $worksheet->getCell($coordinate); $cellIndex = Coordinate::columnIndexFromString($cell->getColumn()); - if ($cellIndex - 1 + $pNumCols < 0) { + if ($cellIndex - 1 + $numberOfColumns < 0) { continue; } // 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. if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { // Update cell styles - $pSheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); + $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); // Insert this cell at its new location if ($cell->getDataType() == DataType::TYPE_FORMULA) { // Formula should be adjusted - $pSheet->getCell($newCoordinate) - ->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + $worksheet->getCell($newCoordinate) + ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle())); } else { // Formula should not be adjusted - $pSheet->getCell($newCoordinate)->setValue($cell->getValue()); + $worksheet->getCell($newCoordinate)->setValue($cell->getValue()); } // Clear the original cell - $pSheet->getCellCollection()->delete($coordinate); + $worksheet->getCellCollection()->delete($coordinate); } else { /* 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 */ if ($cell->getDataType() == DataType::TYPE_FORMULA) { // 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 - $highestColumn = $pSheet->getHighestColumn(); - $highestRow = $pSheet->getHighestRow(); + $highestColumn = $worksheet->getHighestColumn(); + $highestRow = $worksheet->getHighestRow(); - if ($pNumCols > 0 && $beforeColumn - 2 > 0) { + if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) { for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { // Style $coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i; - if ($pSheet->cellExists($coordinate)) { - $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); - $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? - $pSheet->getConditionalStyles($coordinate) : false; - for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $pNumCols; ++$j) { - $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); + if ($worksheet->cellExists($coordinate)) { + $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); + $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ? + $worksheet->getConditionalStyles($coordinate) : false; + for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) { + $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); if ($conditionalStyles) { $cloned = []; foreach ($conditionalStyles as $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) { // Style $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); - if ($pSheet->cellExists($coordinate)) { - $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); - $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? - $pSheet->getConditionalStyles($coordinate) : false; - for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) { - $pSheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); + if ($worksheet->cellExists($coordinate)) { + $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); + $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ? + $worksheet->getConditionalStyles($coordinate) : false; + for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) { + $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); if ($conditionalStyles) { $cloned = []; foreach ($conditionalStyles as $conditionalStyle) { $cloned[] = clone $conditionalStyle; } - $pSheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned); + $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned); } } } @@ -501,47 +490,47 @@ public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pShee } // Update worksheet: column dimensions - $this->adjustColumnDimensions($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustColumnDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: row dimensions - $this->adjustRowDimensions($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: page breaks - $this->adjustPageBreaks($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: comments - $this->adjustComments($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: hyperlinks - $this->adjustHyperlinks($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: data validations - $this->adjustDataValidations($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustDataValidations($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: merge cells - $this->adjustMergeCells($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustMergeCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: protected cells - $this->adjustProtectedCells($pSheet, $pBefore, $beforeColumn, $pNumCols, $beforeRow, $pNumRows); + $this->adjustProtectedCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: autofilter - $autoFilter = $pSheet->getAutoFilter(); + $autoFilter = $worksheet->getAutoFilter(); $autoFilterRange = $autoFilter->getRange(); if (!empty($autoFilterRange)) { - if ($pNumCols != 0) { + if ($numberOfColumns != 0) { $autoFilterColumns = $autoFilter->getColumns(); if (count($autoFilterColumns) > 0) { $column = ''; $row = 0; - sscanf($pBefore, '%[A-Z]%d', $column, $row); + sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); $columnIndex = Coordinate::columnIndexFromString($column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange); if ($columnIndex <= $rangeEnd[0]) { - if ($pNumCols < 0) { + if ($numberOfColumns < 0) { // If we're actually deleting any columns that fall within the autofilter range, // then we delete any rules for those columns - $deleteColumn = $columnIndex + $pNumCols - 1; - $deleteCount = abs($pNumCols); + $deleteColumn = $columnIndex + $numberOfColumns - 1; + $deleteCount = abs($numberOfColumns); for ($i = 1; $i <= $deleteCount; ++$i) { if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) { $autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1)); @@ -552,10 +541,10 @@ public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pShee $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in autofilter range - if ($pNumCols > 0) { + if ($numberOfColumns > 0) { $startColRef = $startCol; $endColRef = $rangeEnd[0]; - $toColRef = $rangeEnd[0] + $pNumCols; + $toColRef = $rangeEnd[0] + $numberOfColumns; do { $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); @@ -565,7 +554,7 @@ public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pShee } else { // For delete, we shuffle from beginning to end to avoid overwriting $startColID = Coordinate::stringFromColumnIndex($startCol); - $toColID = Coordinate::stringFromColumnIndex($startCol + $pNumCols); + $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1); do { $autoFilter->shiftColumn($startColID, $toColID); @@ -576,62 +565,62 @@ public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pShee } } } - $pSheet->setAutoFilter($this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows)); + $worksheet->setAutoFilter($this->updateCellReference($autoFilterRange, $beforeCellAddress, $numberOfColumns, $numberOfRows)); } // Update worksheet: freeze pane - if ($pSheet->getFreezePane()) { - $splitCell = $pSheet->getFreezePane() ?? ''; - $topLeftCell = $pSheet->getTopLeftCell() ?? ''; + if ($worksheet->getFreezePane()) { + $splitCell = $worksheet->getFreezePane() ?? ''; + $topLeftCell = $worksheet->getTopLeftCell() ?? ''; - $splitCell = $this->updateCellReference($splitCell, $pBefore, $pNumCols, $pNumRows); - $topLeftCell = $this->updateCellReference($topLeftCell, $pBefore, $pNumCols, $pNumRows); + $splitCell = $this->updateCellReference($splitCell, $beforeCellAddress, $numberOfColumns, $numberOfRows); + $topLeftCell = $this->updateCellReference($topLeftCell, $beforeCellAddress, $numberOfColumns, $numberOfRows); - $pSheet->freezePane($splitCell, $topLeftCell); + $worksheet->freezePane($splitCell, $topLeftCell); } // Page setup - if ($pSheet->getPageSetup()->isPrintAreaSet()) { - $pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows)); + if ($worksheet->getPageSetup()->isPrintAreaSet()) { + $worksheet->getPageSetup()->setPrintArea($this->updateCellReference($worksheet->getPageSetup()->getPrintArea(), $beforeCellAddress, $numberOfColumns, $numberOfRows)); } // Update worksheet: drawings - $aDrawings = $pSheet->getDrawingCollection(); + $aDrawings = $worksheet->getDrawingCollection(); foreach ($aDrawings as $objDrawing) { - $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($objDrawing->getCoordinates() != $newReference) { $objDrawing->setCoordinates($newReference); } } // Update workbook: define names - if (count($pSheet->getParent()->getDefinedNames()) > 0) { - foreach ($pSheet->getParent()->getDefinedNames() as $definedName) { - if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $pSheet->getHashCode()) { - $definedName->setValue($this->updateCellReference($definedName->getValue(), $pBefore, $pNumCols, $pNumRows)); + if (count($worksheet->getParent()->getDefinedNames()) > 0) { + foreach ($worksheet->getParent()->getDefinedNames() as $definedName) { + if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { + $definedName->setValue($this->updateCellReference($definedName->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows)); } } } // Garbage collect - $pSheet->garbageCollect(); + $worksheet->garbageCollect(); } /** * Update references within formulas. * - * @param string $pFormula Formula to update - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to insert - * @param int $pNumRows Number of rows to insert - * @param string $sheetName Worksheet name/title + * @param string $formula Formula to update + * @param string $beforeCellAddress Insert before this one + * @param int $numberOfColumns Number of columns to insert + * @param int $numberOfRows Number of rows to insert + * @param string $worksheetName Worksheet name/title * * @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 - $formulaBlocks = explode('"', $pFormula); + $formulaBlocks = explode('"', $formula); $i = false; foreach ($formulaBlocks as &$formulaBlock) { // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) @@ -644,11 +633,11 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; - $modified3 = substr($this->updateCellReference('$A' . $match[3], $pBefore, $pNumCols, $pNumRows), 2); - $modified4 = substr($this->updateCellReference('$A' . $match[4], $pBefore, $pNumCols, $pNumRows), 2); + $modified3 = substr($this->updateCellReference('$A' . $match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2); + $modified4 = substr($this->updateCellReference('$A' . $match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2); 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 .= $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 @@ -669,11 +658,11 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; - $modified3 = substr($this->updateCellReference($match[3] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2); - $modified4 = substr($this->updateCellReference($match[4] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2); + $modified3 = substr($this->updateCellReference($match[3] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2); + $modified4 = substr($this->updateCellReference($match[4] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2); 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 .= $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 @@ -694,11 +683,11 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; - $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); - $modified4 = $this->updateCellReference($match[4], $pBefore, $pNumCols, $pNumRows); + $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows); + $modified4 = $this->updateCellReference($match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows); 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 .= $modified3 . ':' . $modified4; [$column, $row] = Coordinate::coordinateFromString($match[3]); @@ -722,9 +711,9 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $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[2] == '') || (trim($match[2], "'") == $sheetName)) { + if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3; [$column, $row] = Coordinate::coordinateFromString($match[3]); @@ -741,7 +730,7 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo } } if ($adjustCount > 0) { - if ($pNumCols > 0 || $pNumRows > 0) { + if ($numberOfColumns > 0 || $numberOfRows > 0) { krsort($cellTokens); krsort($newCellTokens); } else { @@ -761,22 +750,22 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo /** * 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) { - $formula = $this->updateColumnRangesAllWorksheets($formula, $insertColumns); + if ($numberOfColumns !== 0) { + $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns); } - if ($insertRows !== 0) { - $formula = $this->updateRowRangesAllWorksheets($formula, $insertRows); + if ($numberOfRows !== 0) { + $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows); } 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( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', @@ -803,11 +792,11 @@ private function updateCellReferencesAllWorksheets(string $formula, int $insertC $row = $rows[$splitCount][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); } if (!empty($row) && $row[0] !== '$') { - $row += $insertRows; + $row += $numberOfRows; $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength); } } @@ -815,7 +804,7 @@ private function updateCellReferencesAllWorksheets(string $formula, int $insertC return $formula; } - private function updateColumnRangesAllWorksheets(string $formula, int $insertColumns): string + private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui', @@ -842,11 +831,11 @@ private function updateColumnRangesAllWorksheets(string $formula, int $insertCol $toColumn = $toColumns[$splitCount][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); } 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); } } @@ -854,7 +843,7 @@ private function updateColumnRangesAllWorksheets(string $formula, int $insertCol return $formula; } - private function updateRowRangesAllWorksheets(string $formula, int $insertRows): string + private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui', @@ -881,11 +870,11 @@ private function updateRowRangesAllWorksheets(string $formula, int $insertRows): $toRow = $toRows[$splitCount][0]; if (!empty($fromRow) && $fromRow[0] !== '$') { - $fromRow += $insertRows; + $fromRow += $numberOfRows; $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength); } if (!empty($toRow) && $toRow[0] !== '$') { - $toRow += $insertRows; + $toRow += $numberOfRows; $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength); } } @@ -896,29 +885,29 @@ private function updateRowRangesAllWorksheets(string $formula, int $insertRows): /** * Update cell reference. * - * @param string $pCellRange Cell range - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to increment - * @param int $pNumRows Number of rows to increment + * @param string $cellReference Cell address or range of addresses + * @param string $beforeCellAddress Insert before this one + * @param int $numberOfColumns Number of columns to increment + * @param int $numberOfRows Number of rows to increment * * @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. - if (strpos($pCellRange, '!') !== false) { - return $pCellRange; + if (strpos($cellReference, '!') !== false) { + return $cellReference; // Is it a range or a single cell? - } elseif (!Coordinate::coordinateIsRange($pCellRange)) { + } elseif (!Coordinate::coordinateIsRange($cellReference)) { // Single cell - return $this->updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows); - } elseif (Coordinate::coordinateIsRange($pCellRange)) { + return $this->updateSingleCellReference($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows); + } elseif (Coordinate::coordinateIsRange($cellReference)) { // Range - return $this->updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows); + return $this->updateCellRange($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows); } // Return original - return $pCellRange; + return $cellReference; } /** @@ -952,33 +941,33 @@ public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $ne /** * Update cell range. * - * @param string $pCellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to increment - * @param int $pNumRows Number of rows to increment + * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') + * @param string $beforeCellAddress Insert before this one + * @param int $numberOfColumns Number of columns to increment + * @param int $numberOfRows Number of rows to increment * * @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.'); } // Update range - $range = Coordinate::splitRange($pCellRange); + $range = Coordinate::splitRange($cellRange); $ic = count($range); for ($i = 0; $i < $ic; ++$i) { $jc = count($range[$i]); for ($j = 0; $j < $jc; ++$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]; } 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]; } 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 @@ private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCo /** * Update single cell reference. * - * @param string $pCellReference Single cell reference - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to increment - * @param int $pNumRows Number of rows to increment + * @param string $cellReference Single cell reference + * @param string $beforeCellAddress Insert before this one + * @param int $numberOfColumns Number of columns to increment + * @param int $numberOfRows Number of rows to increment * * @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.'); } - // Get coordinate of $pBefore - [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($pBefore); + // Get coordinate of $beforeCellAddress + [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress); - // Get coordinate of $pCellReference - [$newColumn, $newRow] = Coordinate::coordinateFromString($pCellReference); + // Get coordinate of $cellReference + [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference); // Verify which parts should be updated $updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn))); @@ -1015,12 +1004,12 @@ private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A // Create new column reference if ($updateColumn) { - $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $pNumCols); + $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $numberOfColumns); } // Create new row reference if ($updateRow) { - $newRow = (int) $newRow + $pNumRows; + $newRow = (int) $newRow + $numberOfRows; } // Return new reference diff --git a/src/PhpSpreadsheet/RichText/RichText.php b/src/PhpSpreadsheet/RichText/RichText.php index 104177bd29..ba9be66fd2 100644 --- a/src/PhpSpreadsheet/RichText/RichText.php +++ b/src/PhpSpreadsheet/RichText/RichText.php @@ -42,13 +42,13 @@ public function __construct(?Cell $pCell = null) /** * Add text. * - * @param ITextElement $pText Rich text element + * @param ITextElement $text Rich text element * * @return $this */ - public function addText(ITextElement $pText) + public function addText(ITextElement $text) { - $this->richTextElements[] = $pText; + $this->richTextElements[] = $text; return $this; } @@ -56,13 +56,13 @@ public function addText(ITextElement $pText) /** * Create text. * - * @param string $pText Text + * @param string $text Text * * @return TextElement */ - public function createText($pText) + public function createText($text) { - $objText = new TextElement($pText); + $objText = new TextElement($text); $this->addText($objText); return $objText; @@ -71,13 +71,13 @@ public function createText($pText) /** * Create text run. * - * @param string $pText Text + * @param string $text Text * * @return Run */ - public function createTextRun($pText) + public function createTextRun($text) { - $objText = new Run($pText); + $objText = new Run($text); $this->addText($objText); return $objText; diff --git a/src/PhpSpreadsheet/RichText/Run.php b/src/PhpSpreadsheet/RichText/Run.php index 592d0e36b6..9c9f807294 100644 --- a/src/PhpSpreadsheet/RichText/Run.php +++ b/src/PhpSpreadsheet/RichText/Run.php @@ -16,11 +16,11 @@ class Run extends TextElement implements ITextElement /** * 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 $this->font = new Font(); } @@ -38,13 +38,13 @@ public function getFont() /** * Set font. * - * @param Font $pFont Font + * @param Font $font Font * * @return $this */ - public function setFont(?Font $pFont = null) + public function setFont(?Font $font = null) { - $this->font = $pFont; + $this->font = $font; return $this; } diff --git a/src/PhpSpreadsheet/RichText/TextElement.php b/src/PhpSpreadsheet/RichText/TextElement.php index 26aebc0e96..6bec005b4d 100644 --- a/src/PhpSpreadsheet/RichText/TextElement.php +++ b/src/PhpSpreadsheet/RichText/TextElement.php @@ -14,12 +14,12 @@ class TextElement implements ITextElement /** * Create a new TextElement instance. * - * @param string $pText Text + * @param string $text Text */ - public function __construct($pText = '') + public function __construct($text = '') { // Initialise variables - $this->text = $pText; + $this->text = $text; } /** diff --git a/src/PhpSpreadsheet/Settings.php b/src/PhpSpreadsheet/Settings.php index 3657f6316b..765ae8c876 100644 --- a/src/PhpSpreadsheet/Settings.php +++ b/src/PhpSpreadsheet/Settings.php @@ -63,7 +63,7 @@ class Settings * * @return bool Success or failure */ - public static function setLocale($locale) + public static function setLocale(string $locale) { return Calculation::getInstance()->setLocale($locale); } @@ -76,16 +76,16 @@ public static function getLocale(): string /** * 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 */ - 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); } - self::$chartRenderer = $rendererClass; + self::$chartRenderer = $rendererClassName; } /** @@ -94,7 +94,7 @@ public static function setChartRenderer($rendererClass): void * @return null|string Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ - public static function getChartRenderer() + public static function getChartRenderer(): ?string { return self::$chartRenderer; } @@ -123,7 +123,7 @@ public static function setLibXmlLoaderOptions($options): void * * @return int Default options for libxml loader */ - public static function getLibXmlLoaderOptions() + public static function getLibXmlLoaderOptions(): int { if (self::$libXmlLoaderOptions === null && defined('LIBXML_DTDLOAD')) { self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR); @@ -154,7 +154,7 @@ public static function setLibXmlDisableEntityLoader($state): void * * @return bool $state */ - public static function getLibXmlDisableEntityLoader() + public static function getLibXmlDisableEntityLoader(): bool { return self::$libXmlDisableEntityLoader; } @@ -168,11 +168,9 @@ public static function setCache(CacheInterface $cache): void } /** - * Gets the implementation of cache that should be used for cell collection. - * - * @return CacheInterface + * Gets the implementation of cache that is being used for cell collection. */ - public static function getCache() + public static function getCache(): CacheInterface { if (!self::$cache) { self::$cache = new Memory(); diff --git a/src/PhpSpreadsheet/Shared/Date.php b/src/PhpSpreadsheet/Shared/Date.php index 7ddce04614..b755ec3a36 100644 --- a/src/PhpSpreadsheet/Shared/Date.php +++ b/src/PhpSpreadsheet/Shared/Date.php @@ -66,17 +66,17 @@ class Date /** * 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 */ - public static function setExcelCalendar($baseDate) + public static function setExcelCalendar($baseYear) { if ( - ($baseDate == self::CALENDAR_WINDOWS_1900) || - ($baseDate == self::CALENDAR_MAC_1904) + ($baseYear == self::CALENDAR_WINDOWS_1900) || + ($baseYear == self::CALENDAR_MAC_1904) ) { - self::$excelCalendar = $baseDate; + self::$excelCalendar = $baseYear; return true; } @@ -263,17 +263,17 @@ public static function dateTimeToExcel(DateTimeInterface $dateValue) /** * 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 */ - public static function timestampToExcel($dateValue) + public static function timestampToExcel($unixTimestamp) { - if (!is_numeric($dateValue)) { + if (!is_numeric($unixTimestamp)) { return false; } - return self::dateTimeToExcel(new DateTime('@' . $dateValue)); + return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp)); } /** @@ -343,9 +343,9 @@ public static function isDateTime(Cell $pCell) * * @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'; @@ -353,23 +353,23 @@ public static function isDateTimeFormat(NumberFormat $pFormat) /** * Is a given number format code a date/time? * - * @param string $pFormatCode + * @param string $excelFormatCode * * @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) return false; } - if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) { + if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) { // Scientific format return false; } // Switch on formatcode - switch ($pFormatCode) { + switch ($excelFormatCode) { // Explicitly defined date formats case NumberFormat::FORMAT_DATE_YYYYMMDD: case NumberFormat::FORMAT_DATE_YYYYMMDD2: @@ -397,21 +397,21 @@ public static function isDateTimeFormatCode($pFormatCode) } // 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; } // 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). - if (\strpos($pFormatCode, '-00000') !== false) { + if (\strpos($excelFormatCode, '-00000') !== false) { return false; } // Try checking for any of the date formatting characters that don't appear within square braces - if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $pFormatCode)) { + if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $excelFormatCode)) { // We might also have a format mask containing quoted strings... // we don't want to test for any of our characters within the quoted blocks - if (strpos($pFormatCode, '"') !== false) { + if (strpos($excelFormatCode, '"') !== false) { $segMatcher = false; - foreach (explode('"', $pFormatCode) as $subVal) { + foreach (explode('"', $excelFormatCode) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) if ( ($segMatcher = !$segMatcher) && @@ -467,21 +467,21 @@ public static function stringToExcel($dateValue) /** * 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 */ - public static function monthStringToNumber($month) + public static function monthStringToNumber($monthName) { $monthIndex = 1; foreach (self::$monthNames as $shortMonthName => $longMonthName) { - if (($month === $longMonthName) || ($month === $shortMonthName)) { + if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) { return $monthIndex; } ++$monthIndex; } - return $month; + return $monthName; } /** diff --git a/src/PhpSpreadsheet/Shared/Drawing.php b/src/PhpSpreadsheet/Shared/Drawing.php index 0e9f0fb68a..1d2a15379f 100644 --- a/src/PhpSpreadsheet/Shared/Drawing.php +++ b/src/PhpSpreadsheet/Shared/Drawing.php @@ -42,15 +42,14 @@ public static function EMUToPixels($emuValue) * This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional. * * @param int $pixelValue Value in pixels - * @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook * * @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 - $name = $pDefaultFont->getName(); - $size = $pDefaultFont->getSize(); + $name = $defaultFont->getName(); + $size = $defaultFont->getSize(); if (isset(Font::$defaultColumnWidths[$name][$size])) { // Exact width can be determined @@ -126,27 +125,27 @@ public static function pointsToPixels($pointValue) /** * Convert degrees to angle. * - * @param int $pValue Degrees + * @param int $degrees Degrees * * @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. * - * @param int|SimpleXMLElement $pValue Angle + * @param int|SimpleXMLElement $angle Angle * * @return int Degrees */ - public static function angleToDegrees($pValue) + public static function angleToDegrees($angle) { - $pValue = (int) $pValue; - if ($pValue != 0) { - return (int) round($pValue / 60000); + $angle = (int) $angle; + if ($angle != 0) { + return (int) round($angle / 60000); } return 0; @@ -157,14 +156,14 @@ public static function angleToDegrees($pValue) * * @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 */ - public static function imagecreatefrombmp($p_sFile) + public static function imagecreatefrombmp($bmpFilename) { // Load the image into a string - $file = fopen($p_sFile, 'rb'); + $file = fopen($bmpFilename, 'rb'); $read = fread($file, 10); while (!feof($file) && ($read != '')) { $read .= fread($file, 1024); diff --git a/src/PhpSpreadsheet/Shared/File.php b/src/PhpSpreadsheet/Shared/File.php index aa917e3f29..83103b4915 100644 --- a/src/PhpSpreadsheet/Shared/File.php +++ b/src/PhpSpreadsheet/Shared/File.php @@ -49,15 +49,15 @@ private static function validateZipFirst4(string $zipFile): bool /** * 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 // file_exists returns strange values when // 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 - $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); - $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); + $zipFile = substr($filename, 6, strpos($filename, '#') - 6); + $archiveFile = substr($filename, strpos($filename, '#') + 1); if (self::validateZipFirst4($zipFile)) { $zip = new ZipArchive(); @@ -73,25 +73,25 @@ public static function fileExists(string $pFilename): bool return false; } - return file_exists($pFilename); + return file_exists($filename); } /** * Returns canonicalized absolute pathname, also for ZIP archives. */ - public static function realpath(string $pFilename): string + public static function realpath(string $filename): string { // Returnvalue $returnValue = ''; // Try using realpath() - if (file_exists($pFilename)) { - $returnValue = realpath($pFilename) ?: ''; + if (file_exists($filename)) { + $returnValue = realpath($filename) ?: ''; } // Found something? if ($returnValue === '') { - $pathArray = explode('/', $pFilename); + $pathArray = explode('/', $filename); while (in_array('..', $pathArray) && $pathArray[0] != '..') { $iMax = count($pathArray); for ($i = 0; $i < $iMax; ++$i) { diff --git a/src/PhpSpreadsheet/Shared/Font.php b/src/PhpSpreadsheet/Shared/Font.php index 085125d3e4..9a74befeb9 100644 --- a/src/PhpSpreadsheet/Shared/Font.php +++ b/src/PhpSpreadsheet/Shared/Font.php @@ -5,6 +5,7 @@ use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\Alignment; +use PhpOffice\PhpSpreadsheet\Style\Font as FontStyle; class Font { @@ -164,16 +165,16 @@ class Font /** * Set autoSize method. * - * @param string $pValue see self::AUTOSIZE_METHOD_* + * @param string $method see self::AUTOSIZE_METHOD_* * * @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; } - self::$autoSizeMethod = $pValue; + self::$autoSizeMethod = $method; return true; } @@ -197,11 +198,11 @@ public static function getAutoSizeMethod() *
  • ~/.fonts/
  • * . * - * @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 @@ public static function getTrueTypeFontPath() /** * 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 int $rotation Rotation angle - * @param null|\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Font object + * @param null|FontStyle $defaultFont Font object * * @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 ($cellText instanceof RichText) { @@ -274,7 +275,7 @@ public static function calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font /** * 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')) { throw new PhpSpreadsheetException('GD library needs to be enabled'); @@ -303,7 +304,7 @@ public static function getTextWidthPixelsExact(string $text, \PhpOffice\PhpSprea * * @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(); $fontSize = $font->getSize(); @@ -344,7 +345,7 @@ public static function getTextWidthPixelsApprox($columnText, \PhpOffice\PhpSprea } else { // rotated text $columnWidth = $columnWidth * cos(deg2rad($rotation)) - + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation + + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation } } @@ -391,11 +392,9 @@ public static function centimeterSizeToPixels($sizeInCm) /** * Returns the font path given the font. * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font - * * @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)) { throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified'); @@ -409,35 +408,35 @@ public static function getTrueTypeFontFileFromFont($font) switch ($name) { case 'Arial': $fontFile = ( - $bold ? ($italic ? self::ARIAL_BOLD_ITALIC : self::ARIAL_BOLD) - : ($italic ? self::ARIAL_ITALIC : self::ARIAL) + $bold ? ($italic ? self::ARIAL_BOLD_ITALIC : self::ARIAL_BOLD) + : ($italic ? self::ARIAL_ITALIC : self::ARIAL) ); break; case 'Calibri': $fontFile = ( - $bold ? ($italic ? self::CALIBRI_BOLD_ITALIC : self::CALIBRI_BOLD) - : ($italic ? self::CALIBRI_ITALIC : self::CALIBRI) + $bold ? ($italic ? self::CALIBRI_BOLD_ITALIC : self::CALIBRI_BOLD) + : ($italic ? self::CALIBRI_ITALIC : self::CALIBRI) ); break; case 'Courier New': $fontFile = ( - $bold ? ($italic ? self::COURIER_NEW_BOLD_ITALIC : self::COURIER_NEW_BOLD) - : ($italic ? self::COURIER_NEW_ITALIC : self::COURIER_NEW) + $bold ? ($italic ? self::COURIER_NEW_BOLD_ITALIC : self::COURIER_NEW_BOLD) + : ($italic ? self::COURIER_NEW_ITALIC : self::COURIER_NEW) ); break; case 'Comic Sans MS': $fontFile = ( - $bold ? self::COMIC_SANS_MS_BOLD : self::COMIC_SANS_MS + $bold ? self::COMIC_SANS_MS_BOLD : self::COMIC_SANS_MS ); break; case 'Georgia': $fontFile = ( - $bold ? ($italic ? self::GEORGIA_BOLD_ITALIC : self::GEORGIA_BOLD) - : ($italic ? self::GEORGIA_ITALIC : self::GEORGIA) + $bold ? ($italic ? self::GEORGIA_BOLD_ITALIC : self::GEORGIA_BOLD) + : ($italic ? self::GEORGIA_ITALIC : self::GEORGIA) ); break; @@ -447,8 +446,8 @@ public static function getTrueTypeFontFileFromFont($font) break; case 'Liberation Sans': $fontFile = ( - $bold ? ($italic ? self::LIBERATION_SANS_BOLD_ITALIC : self::LIBERATION_SANS_BOLD) - : ($italic ? self::LIBERATION_SANS_ITALIC : self::LIBERATION_SANS) + $bold ? ($italic ? self::LIBERATION_SANS_BOLD_ITALIC : self::LIBERATION_SANS_BOLD) + : ($italic ? self::LIBERATION_SANS_ITALIC : self::LIBERATION_SANS) ); break; @@ -466,8 +465,8 @@ public static function getTrueTypeFontFileFromFont($font) break; case 'Palatino Linotype': $fontFile = ( - $bold ? ($italic ? self::PALATINO_LINOTYPE_BOLD_ITALIC : self::PALATINO_LINOTYPE_BOLD) - : ($italic ? self::PALATINO_LINOTYPE_ITALIC : self::PALATINO_LINOTYPE) + $bold ? ($italic ? self::PALATINO_LINOTYPE_BOLD_ITALIC : self::PALATINO_LINOTYPE_BOLD) + : ($italic ? self::PALATINO_LINOTYPE_ITALIC : self::PALATINO_LINOTYPE) ); break; @@ -477,28 +476,28 @@ public static function getTrueTypeFontFileFromFont($font) break; case 'Tahoma': $fontFile = ( - $bold ? self::TAHOMA_BOLD : self::TAHOMA + $bold ? self::TAHOMA_BOLD : self::TAHOMA ); break; case 'Times New Roman': $fontFile = ( - $bold ? ($italic ? self::TIMES_NEW_ROMAN_BOLD_ITALIC : self::TIMES_NEW_ROMAN_BOLD) - : ($italic ? self::TIMES_NEW_ROMAN_ITALIC : self::TIMES_NEW_ROMAN) + $bold ? ($italic ? self::TIMES_NEW_ROMAN_BOLD_ITALIC : self::TIMES_NEW_ROMAN_BOLD) + : ($italic ? self::TIMES_NEW_ROMAN_ITALIC : self::TIMES_NEW_ROMAN) ); break; case 'Trebuchet MS': $fontFile = ( - $bold ? ($italic ? self::TREBUCHET_MS_BOLD_ITALIC : self::TREBUCHET_MS_BOLD) - : ($italic ? self::TREBUCHET_MS_ITALIC : self::TREBUCHET_MS) + $bold ? ($italic ? self::TREBUCHET_MS_BOLD_ITALIC : self::TREBUCHET_MS_BOLD) + : ($italic ? self::TREBUCHET_MS_ITALIC : self::TREBUCHET_MS) ); break; case 'Verdana': $fontFile = ( - $bold ? ($italic ? self::VERDANA_BOLD_ITALIC : self::VERDANA_BOLD) - : ($italic ? self::VERDANA_ITALIC : self::VERDANA) + $bold ? ($italic ? self::VERDANA_BOLD_ITALIC : self::VERDANA_BOLD) + : ($italic ? self::VERDANA_ITALIC : self::VERDANA) ); break; @@ -521,13 +520,13 @@ public static function getTrueTypeFontFileFromFont($font) /** * Returns the associated charset for the font name. * - * @param string $name Font name + * @param string $fontName Font name * * @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. case 'EucrosiaUPC': return self::CHARSET_ANSI_THAI; @@ -546,28 +545,28 @@ public static function getCharsetFromFontName($name) * 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). * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font - * @param bool $pPixels true = return column width in pixels, false = return in OOXML units + * @param FontStyle $font The workbooks default font + * @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units * * @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()])) { // Exact width can be determined - $columnWidth = $pPixels ? + $columnWidth = $returnAsPixels ? self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px'] - : self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width']; + : self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 - $columnWidth = $pPixels ? + $columnWidth = $returnAsPixels ? self::$defaultColumnWidths['Calibri'][11]['px'] - : self::$defaultColumnWidths['Calibri'][11]['width']; + : self::$defaultColumnWidths['Calibri'][11]['width']; $columnWidth = $columnWidth * $font->getSize() / 11; // Round pixels to closest integer - if ($pPixels) { + if ($returnAsPixels) { $columnWidth = (int) round($columnWidth); } } @@ -579,11 +578,11 @@ public static function getDefaultColumnWidthByFont(\PhpOffice\PhpSpreadsheet\Sty * 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. * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font + * @param FontStyle $font The workbooks default font * * @return float Row height in points */ - public static function getDefaultRowHeightByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font) + public static function getDefaultRowHeightByFont(FontStyle $font) { switch ($font->getName()) { case 'Arial': diff --git a/src/PhpSpreadsheet/Shared/OLE.php b/src/PhpSpreadsheet/Shared/OLE.php index 6278553f6e..ca975737b6 100644 --- a/src/PhpSpreadsheet/Shared/OLE.php +++ b/src/PhpSpreadsheet/Shared/OLE.php @@ -110,15 +110,15 @@ class OLE * * @acces public * - * @param string $file + * @param string $filename * * @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) { - throw new ReaderException("Can't open file $file"); + throw new ReaderException("Can't open file $filename"); } $this->_file_handle = $fh; @@ -245,13 +245,13 @@ public function getStream($blockIdOrPps) /** * Reads a signed char. * - * @param resource $fh file handle + * @param resource $fileHandle file handle * * @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; } @@ -259,13 +259,13 @@ private static function readInt1($fh) /** * Reads an unsigned short (2 octets). * - * @param resource $fh file handle + * @param resource $fileHandle file handle * * @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; } @@ -273,13 +273,13 @@ private static function readInt2($fh) /** * Reads an unsigned long (4 octets). * - * @param resource $fh file handle + * @param resource $fileHandle file handle * * @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; } diff --git a/src/PhpSpreadsheet/Shared/OLERead.php b/src/PhpSpreadsheet/Shared/OLERead.php index c4dc572a14..91f1d044be 100644 --- a/src/PhpSpreadsheet/Shared/OLERead.php +++ b/src/PhpSpreadsheet/Shared/OLERead.php @@ -93,22 +93,22 @@ class OLERead /** * 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 // 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 $identifierOle = pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1); 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 - $this->data = file_get_contents($pFilename); + $this->data = file_get_contents($filename); // Total number of sectors used for the SAT $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); @@ -235,13 +235,12 @@ public function getStream($stream) /** * 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 */ - private function readData($bl) + private function readData($block) { - $block = $bl; $data = ''; while ($block != -2) { diff --git a/src/PhpSpreadsheet/Shared/PasswordHasher.php b/src/PhpSpreadsheet/Shared/PasswordHasher.php index ba30fc3156..0d58a8686b 100644 --- a/src/PhpSpreadsheet/Shared/PasswordHasher.php +++ b/src/PhpSpreadsheet/Shared/PasswordHasher.php @@ -53,13 +53,13 @@ private static function getAlgorithm(string $algorithmName): string * Scrutinizer will squawk at the use of bitwise operations here, * 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; - $pwlen = strlen($pPassword); - $passwordArray = pack('c', $pwlen) . $pPassword; + $pwlen = strlen($password); + $passwordArray = pack('c', $pwlen) . $password; for ($i = $pwlen; $i >= 0; --$i) { $intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1; $intermediate2 = 2 * $verifier; diff --git a/src/PhpSpreadsheet/Shared/StringHelper.php b/src/PhpSpreadsheet/Shared/StringHelper.php index 0e8eb8a5f3..d1422c76c7 100644 --- a/src/PhpSpreadsheet/Shared/StringHelper.php +++ b/src/PhpSpreadsheet/Shared/StringHelper.php @@ -294,15 +294,15 @@ private static function buildCharacterSets(): void * So you could end up with something like _x0008_ in a string (either in a cell value () * element or in the shared string element. * - * @param string $value Value to unescape + * @param string $textValue Value to unescape * * @return string */ - public static function controlCharacterOOXML2PHP($value) + public static function controlCharacterOOXML2PHP($textValue) { 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 @@ public static function controlCharacterOOXML2PHP($value) * So you could end up with something like _x0008_ in a string (either in a cell value () * element or in the shared string element. * - * @param string $value Value to escape + * @param string $textValue Value to escape * * @return string */ - public static function controlCharacterPHP2OOXML($value) + public static function controlCharacterPHP2OOXML($textValue) { 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. * - * @param string $value + * @param string $textValue * * @return string */ - public static function sanitizeUTF8($value) + public static function sanitizeUTF8($textValue) { 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. * - * @param string $value + * @param string $textValue * * @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 * point as decimal separator in case locale is other than English. * - * @param mixed $value + * @param mixed $numericValue * * @return string */ - public static function formatNumber($value) + public static function formatNumber($numericValue) { - if (is_float($value)) { - return str_replace(',', '.', $value); + if (is_float($numericValue)) { + return str_replace(',', '.', $numericValue); } - return (string) $value; + return (string) $numericValue; } /** @@ -383,25 +383,25 @@ public static function formatNumber($value) * 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. * - * @param string $value UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * @param mixed[] $arrcRuns Details of rich text runs in $value * * @return string */ - public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = []) + public static function UTF8toBIFF8UnicodeShort($textValue, $arrcRuns = []) { // character count - $ln = self::countCharacters($value, 'UTF-8'); + $ln = self::countCharacters($textValue, 'UTF-8'); // option flags if (empty($arrcRuns)) { $data = pack('CC', $ln, 0x0001); // characters - $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); + $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); } else { $data = pack('vC', $ln, 0x09); $data .= pack('v', count($arrcRuns)); // characters - $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); + $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); foreach ($arrcRuns as $cRun) { $data .= pack('v', $cRun['strlen']); $data .= pack('v', $cRun['fontidx']); @@ -418,17 +418,17 @@ public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = []) * 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. * - * @param string $value UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * * @return string */ - public static function UTF8toBIFF8UnicodeLong($value) + public static function UTF8toBIFF8UnicodeLong($textValue) { // character count - $ln = self::countCharacters($value, 'UTF-8'); + $ln = self::countCharacters($textValue, 'UTF-8'); // characters - $chars = self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); + $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); return pack('vC', $ln, 0x0001) . $chars; } @@ -436,91 +436,91 @@ public static function UTF8toBIFF8UnicodeLong($value) /** * 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 $from Encoding to convert from, e.g. 'UTF-16LE' * * @return string */ - public static function convertEncoding($value, $to, $from) + public static function convertEncoding($textValue, $to, $from) { if (self::getIsIconvEnabled()) { - $result = iconv($from, $to . self::$iconvOptions, $value); + $result = iconv($from, $to . self::$iconvOptions, $textValue); if (false !== $result) { return $result; } } - return mb_convert_encoding($value, $to, $from); + return mb_convert_encoding($textValue, $to, $from); } /** * Get character count. * - * @param string $value - * @param string $enc Encoding + * @param string $textValue + * @param string $encoding Encoding * * @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. * - * @param string $pValue UTF-8 encoded string - * @param int $pStart Start offset - * @param int $pLength Maximum number of characters in substring + * @param string $textValue UTF-8 encoded string + * @param int $offset Start offset + * @param int $length Maximum number of characters in substring * * @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. * - * @param string $pValue UTF-8 encoded string + * @param string $textValue UTF-8 encoded 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. * - * @param string $pValue UTF-8 encoded string + * @param string $textValue UTF-8 encoded 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 * (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 */ - 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) @@ -534,13 +534,13 @@ public static function mbStrSplit($string) * Reverse the case of a string, so that all uppercase characters become lowercase * and all lowercase characters become uppercase. * - * @param string $pValue UTF-8 encoded string + * @param string $textValue UTF-8 encoded 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) { if (self::mbIsUpper($character)) { $character = mb_strtolower($character, 'UTF-8'); @@ -601,11 +601,11 @@ public static function getDecimalSeparator() * Set the decimal separator. Only used by NumberFormat::toFormattedString() * 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 @@ public static function getThousandsSeparator() * Set the thousands separator. Only used by NumberFormat::toFormattedString() * 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 @@ public static function getCurrencyCode() * Set the currency code. Only used by NumberFormat::toFormattedString() * 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. * - * @param string $pValue + * @param string $textValue * * @return string UTF-8 encoded string */ - public static function SYLKtoUTF8($pValue) + public static function SYLKtoUTF8($textValue) { self::buildCharacterSets(); // If there is no escape character in the string there is nothing to do - if (strpos($pValue, '') === false) { - return $pValue; + if (strpos($textValue, '') === false) { + return $textValue; } 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 * (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 */ - public static function testStringAsNumeric($value) + public static function testStringAsNumeric($textValue) { - if (is_numeric($value)) { - return $value; + if (is_numeric($textValue)) { + 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; } } diff --git a/src/PhpSpreadsheet/Shared/TimeZone.php b/src/PhpSpreadsheet/Shared/TimeZone.php index a6f9850757..dabb88f2d0 100644 --- a/src/PhpSpreadsheet/Shared/TimeZone.php +++ b/src/PhpSpreadsheet/Shared/TimeZone.php @@ -17,26 +17,26 @@ class TimeZone /** * 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 */ - 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. * - * @param string $timezone Time zone (e.g. 'Europe/London') + * @param string $timezoneName Time zone (e.g. 'Europe/London') * * @return bool Success or failure */ - public static function setTimeZone($timezone) + public static function setTimeZone($timezoneName) { - if (self::validateTimezone($timezone)) { - self::$timezone = $timezone; + if (self::validateTimezone($timezoneName)) { + self::$timezone = $timezoneName; return true; } @@ -58,19 +58,19 @@ public static function getTimeZone() * 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. * - * @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 * * @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"); - if (!self::validateTimezone($timezone)) { - throw new PhpSpreadsheetException("Invalid timezone $timezone"); + if (!self::validateTimezone($timezoneName)) { + throw new PhpSpreadsheetException("Invalid timezone $timezoneName"); } - $dtobj->setTimeZone(new DateTimeZone($timezone)); + $dtobj->setTimeZone(new DateTimeZone($timezoneName)); return $dtobj->getOffset(); } diff --git a/src/PhpSpreadsheet/Shared/XMLWriter.php b/src/PhpSpreadsheet/Shared/XMLWriter.php index b11463cf07..84ad8a8380 100644 --- a/src/PhpSpreadsheet/Shared/XMLWriter.php +++ b/src/PhpSpreadsheet/Shared/XMLWriter.php @@ -2,8 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Shared; -use PhpOffice\PhpSpreadsheet\Settings; - class XMLWriter extends \XMLWriter { public static $debugEnabled = false; @@ -22,20 +20,20 @@ class XMLWriter extends \XMLWriter /** * Create a new XMLWriter instance. * - * @param int $pTemporaryStorage Temporary storage location - * @param string $pTemporaryStorageFolder Temporary storage folder + * @param int $temporaryStorage Temporary storage location + * @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 - if ($pTemporaryStorage == self::STORAGE_MEMORY) { + if ($temporaryStorage == self::STORAGE_MEMORY) { $this->openMemory(); } else { // Create temporary filename - if ($pTemporaryStorageFolder === null) { - $pTemporaryStorageFolder = File::sysGetTempDir(); + if ($temporaryStorageFolder === null) { + $temporaryStorageFolder = File::sysGetTempDir(); } - $this->tempFileName = @tempnam($pTemporaryStorageFolder, 'xml'); + $this->tempFileName = @tempnam($temporaryStorageFolder, 'xml'); // Open storage if ($this->openUri($this->tempFileName) === false) { @@ -79,16 +77,16 @@ public function getData() /** * Wrapper method for writeRaw. * - * @param string|string[] $text + * @param null|string|string[] $rawTextData * * @return bool */ - public function writeRawData($text) + public function writeRawData($rawTextData) { - if (is_array($text)) { - $text = implode("\n", $text); + if (is_array($rawTextData)) { + $rawTextData = implode("\n", $rawTextData); } - return $this->writeRaw(htmlspecialchars($text ?? '', Settings::htmlEntityFlags())); + return $this->writeRaw(htmlspecialchars($rawTextData ?? '')); } } diff --git a/src/PhpSpreadsheet/Shared/Xls.php b/src/PhpSpreadsheet/Shared/Xls.php index cd2482b0a9..2c3198b04f 100644 --- a/src/PhpSpreadsheet/Shared/Xls.php +++ b/src/PhpSpreadsheet/Shared/Xls.php @@ -13,17 +13,17 @@ class Xls * x is the width in intrinsic Excel units (measuring width in number of normal characters) * This holds for Arial 10. * - * @param Worksheet $sheet The sheet + * @param Worksheet $worksheet The sheet * @param string $col The column * * @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 - $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) if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) { @@ -31,9 +31,9 @@ public static function sizeCol($sheet, $col = 'A') $columnDimension = $columnDimensions[$col]; $width = $columnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); - } elseif ($sheet->getDefaultColumnDimension()->getWidth() != -1) { + } elseif ($worksheet->getDefaultColumnDimension()->getWidth() != -1) { // then we have default column dimension with explicit width - $defaultColumnDimension = $sheet->getDefaultColumnDimension(); + $defaultColumnDimension = $worksheet->getDefaultColumnDimension(); $width = $defaultColumnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); } else { @@ -56,17 +56,17 @@ public static function sizeCol($sheet, $col = 'A') * 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. * - * @param Worksheet $sheet The sheet + * @param Worksheet $worksheet The sheet * @param int $row The row index (1-based) * * @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 - $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) if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) { @@ -74,9 +74,9 @@ public static function sizeRow($sheet, $row = 1) $rowDimension = $rowDimensions[$row]; $rowHeight = $rowDimension->getRowHeight(); $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 - $defaultRowDimension = $sheet->getDefaultRowDimension(); + $defaultRowDimension = $worksheet->getDefaultRowDimension(); $pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS); } else { // we don't even have any default row dimension. Height depends on default font @@ -105,7 +105,7 @@ public static function sizeRow($sheet, $row = 1) * * @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; @@ -113,14 +113,14 @@ public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $start $startColumnIndex = Coordinate::columnIndexFromString($startColumn); $endColumnIndex = Coordinate::columnIndexFromString($endColumn); 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 - $distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024); + $distanceX -= (int) floor(self::sizeCol($worksheet, $startColumn) * $startOffsetX / 1024); // 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; } @@ -136,20 +136,20 @@ public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $start * * @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; // add the widths of the spanning rows for ($row = $startRow; $row <= $endRow; ++$row) { - $distanceY += self::sizeRow($sheet, $row); + $distanceY += self::sizeRow($worksheet, $row); } // 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 - $distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256)); + $distanceY -= (int) floor(self::sizeRow($worksheet, $endRow) * (1 - $endOffsetY / 256)); return $distanceY; } @@ -198,7 +198,6 @@ public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffse * W is the width of the cell * H is the height of the cell * - * @param Worksheet $sheet * @param string $coordinates E.g. 'A1' * @param int $offsetX Horizontal offset in pixels * @param int $offsetY Vertical offset in pixels @@ -207,7 +206,7 @@ public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffse * * @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); $row_start = $row - 1; @@ -220,10 +219,10 @@ public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offs $row_end = $row_start; // Row containing bottom right corner of object // Zero the specified offset if greater than the cell dimensions - if ($x1 >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start))) { + if ($x1 >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start))) { $x1 = 0; } - if ($y1 >= self::sizeRow($sheet, $row_start + 1)) { + if ($y1 >= self::sizeRow($worksheet, $row_start + 1)) { $y1 = 0; } @@ -231,37 +230,37 @@ public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offs $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image - while ($width >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end))) { - $width -= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)); + while ($width >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end))) { + $width -= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)); ++$col_end; } // Subtract the underlying cell heights to find the end cell of the image - while ($height >= self::sizeRow($sheet, $row_end + 1)) { - $height -= self::sizeRow($sheet, $row_end + 1); + while ($height >= self::sizeRow($worksheet, $row_end + 1)) { + $height -= self::sizeRow($worksheet, $row_end + 1); ++$row_end; } // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // 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; } - if (self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { + if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { return null; } - if (self::sizeRow($sheet, $row_start + 1) == 0) { + if (self::sizeRow($worksheet, $row_start + 1) == 0) { return null; } - if (self::sizeRow($sheet, $row_end + 1) == 0) { + if (self::sizeRow($worksheet, $row_end + 1) == 0) { return null; } // Convert the pixel values to the percentage value expected by Excel - $x1 = $x1 / self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; - $y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256; - $x2 = ($width + 1) / self::sizeCol($sheet, 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 + $x1 = $x1 / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; + $y1 = $y1 / self::sizeRow($worksheet, $row_start + 1) * 256; + $x2 = ($width + 1) / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side 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); $endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1); diff --git a/src/PhpSpreadsheet/Spreadsheet.php b/src/PhpSpreadsheet/Spreadsheet.php index db617ef620..78efc78918 100644 --- a/src/PhpSpreadsheet/Spreadsheet.php +++ b/src/PhpSpreadsheet/Spreadsheet.php @@ -439,27 +439,27 @@ public function hasRibbonBinObjects() /** * 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 */ - 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 ! * - * @param string $pName Sheet name + * @param string $codeName Sheet name * * @return null|Worksheet */ - public function getSheetByCodeName($pName) + public function getSheetByCodeName($codeName) { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { - if ($this->workSheetCollection[$i]->getCodeName() == $pName) { + if ($this->workSheetCollection[$i]->getCodeName() == $codeName) { return $this->workSheetCollection[$i]; } } @@ -545,9 +545,9 @@ public function getProperties() /** * 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 @@ public function getSecurity() /** * 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 @@ public function createSheet($sheetIndex = null) /** * 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 */ - public function sheetNameExists($pSheetName) + public function sheetNameExists($worksheetName) { - return $this->getSheetByName($pSheetName) !== null; + return $this->getSheetByName($worksheetName) !== null; } /** * 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 */ - 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( - "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) { $this->activeSheetIndex = 0; } - $this->workSheetCollection[] = $pSheet; + $this->workSheetCollection[] = $worksheet; } else { // Insert the sheet at the requested index array_splice( $this->workSheetCollection, - $iSheetIndex, + $sheetIndex, 0, - [$pSheet] + [$worksheet] ); // Adjust active sheet index if necessary - if ($this->activeSheetIndex >= $iSheetIndex) { + if ($this->activeSheetIndex >= $sheetIndex) { ++$this->activeSheetIndex; } } - if ($pSheet->getParent() === null) { - $pSheet->rebindParent($this); + if ($worksheet->getParent() === null) { + $worksheet->rebindParent($this); } - return $pSheet; + return $worksheet; } /** * 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); - if ($pIndex > $numSheets - 1) { + if ($sheetIndex > $numSheets - 1) { 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 if ( - ($this->activeSheetIndex >= $pIndex) && + ($this->activeSheetIndex >= $sheetIndex) && ($this->activeSheetIndex > 0 || $numSheets <= 1) ) { --$this->activeSheetIndex; @@ -674,21 +675,21 @@ public function removeSheetByIndex($pIndex): void /** * Get sheet by index. * - * @param int $pIndex Sheet index + * @param int $sheetIndex Sheet index * * @return Worksheet */ - public function getSheet($pIndex) + public function getSheet($sheetIndex) { - if (!isset($this->workSheetCollection[$pIndex])) { + if (!isset($this->workSheetCollection[$sheetIndex])) { $numSheets = $this->getSheetCount(); 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 @@ public function getAllSheets() /** * Get sheet by name. * - * @param string $pName Sheet name + * @param string $worksheetName Sheet name * * @return null|Worksheet */ - public function getSheetByName($pName) + public function getSheetByName($worksheetName) { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { - if ($this->workSheetCollection[$i]->getTitle() === trim($pName, "'")) { + if ($this->workSheetCollection[$i]->getTitle() === trim($worksheetName, "'")) { return $this->workSheetCollection[$i]; } } @@ -725,10 +726,10 @@ public function getSheetByName($pName) * * @return int index */ - public function getIndex(Worksheet $pSheet) + public function getIndex(Worksheet $worksheet) { foreach ($this->workSheetCollection as $key => $value) { - if ($value->getHashCode() === $pSheet->getHashCode()) { + if ($value->getHashCode() === $worksheet->getHashCode()) { return $key; } } @@ -739,27 +740,27 @@ public function getIndex(Worksheet $pSheet) /** * Set index for sheet by sheet name. * - * @param string $sheetName Sheet name to modify index for - * @param int $newIndex New index for the sheet + * @param string $worksheetName Sheet name to modify index for + * @param int $newIndexPosition New index for the sheet * * @return int New sheet index */ - public function setIndexByName($sheetName, $newIndex) + public function setIndexByName($worksheetName, $newIndexPosition) { - $oldIndex = $this->getIndex($this->getSheetByName($sheetName)); - $pSheet = array_splice( + $oldIndex = $this->getIndex($this->getSheetByName($worksheetName)); + $worksheet = array_splice( $this->workSheetCollection, $oldIndex, 1 ); array_splice( $this->workSheetCollection, - $newIndex, + $newIndexPosition, 0, - $pSheet + $worksheet ); - return $newIndex; + return $newIndexPosition; } /** @@ -785,20 +786,20 @@ public function getActiveSheetIndex() /** * Set active sheet index. * - * @param int $pIndex Active sheet index + * @param int $worksheetIndex Active sheet index * * @return Worksheet */ - public function setActiveSheetIndex($pIndex) + public function setActiveSheetIndex($worksheetIndex) { $numSheets = count($this->workSheetCollection); - if ($pIndex > $numSheets - 1) { + if ($worksheetIndex > $numSheets - 1) { 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(); } @@ -806,19 +807,19 @@ public function setActiveSheetIndex($pIndex) /** * Set active sheet index by name. * - * @param string $pValue Sheet title + * @param string $worksheetName Sheet title * * @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)); return $worksheet; } - throw new Exception('Workbook does not contain sheet:' . $pValue); + throw new Exception('Workbook does not contain sheet:' . $worksheetName); } /** @@ -840,35 +841,35 @@ public function getSheetNames() /** * Add external sheet. * - * @param Worksheet $pSheet External sheet to add - * @param null|int $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @param Worksheet $worksheet External sheet to add + * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) * * @return Worksheet */ - public function addExternalSheet(Worksheet $pSheet, $iSheetIndex = null) + public function addExternalSheet(Worksheet $worksheet, $sheetIndex = null) { - if ($this->sheetNameExists($pSheet->getTitle())) { - throw new Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first."); + if ($this->sheetNameExists($worksheet->getTitle())) { + 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 $countCellXfs = count($this->cellXfCollection); // 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); } // move sheet to this workbook - $pSheet->rebindParent($this); + $worksheet->rebindParent($this); // update the cellXfs - foreach ($pSheet->getCoordinates(false) as $coordinate) { - $cell = $pSheet->getCell($coordinate); + foreach ($worksheet->getCoordinates(false) as $coordinate) { + $cell = $worksheet->getCell($coordinate); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); } - return $this->addSheet($pSheet, $iSheetIndex); + return $this->addSheet($worksheet, $sheetIndex); } /** @@ -948,9 +949,9 @@ public function addDefinedName(DefinedName $definedName): void /** * 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; @@ -959,7 +960,7 @@ public function getNamedRange(string $namedRange, ?Worksheet $pSheet = null): ?N // first look for global named 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) - $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; @@ -968,9 +969,9 @@ public function getNamedRange(string $namedRange, ?Worksheet $pSheet = null): ?N /** * 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; @@ -979,7 +980,7 @@ public function getNamedFormula(string $namedFormula, ?Worksheet $pSheet = null) // first look for global named 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) - $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; @@ -994,13 +995,13 @@ private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedN 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 ( - ($pSheet !== null) && isset($this->definedNames[$pSheet->getTitle() . '!' . $name]) - && $this->definedNames[$pSheet->getTitle() . '!' . $name]->isFormula() === $type + ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name]) + && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type ) { - return $this->definedNames[$pSheet->getTitle() . '!' . $name]; + return $this->definedNames[$worksheet->getTitle() . '!' . $name]; } return null; @@ -1009,9 +1010,9 @@ private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet /** * 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; @@ -1023,8 +1024,8 @@ public function getDefinedName(string $definedName, ?Worksheet $pSheet = null): } // 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])) { - $returnValue = $this->definedNames[$pSheet->getTitle() . '!' . $definedName]; + if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { + $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName]; } } @@ -1034,53 +1035,53 @@ public function getDefinedName(string $definedName, ?Worksheet $pSheet = null): /** * 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 */ - 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->removeDefinedName($namedRange, $pSheet); + return $this->removeDefinedName($namedRange, $worksheet); } /** * 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 */ - 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->removeDefinedName($namedFormula, $pSheet); + return $this->removeDefinedName($namedFormula, $worksheet); } /** * 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 */ - public function removeDefinedName(string $definedName, ?Worksheet $pSheet = null): self + public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self { $definedName = StringHelper::strToUpper($definedName); - if ($pSheet === null) { + if ($worksheet === null) { if (isset($this->definedNames[$definedName])) { unset($this->definedNames[$definedName]); } } else { - if (isset($this->definedNames[$pSheet->getTitle() . '!' . $definedName])) { - unset($this->definedNames[$pSheet->getTitle() . '!' . $definedName]); + if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { + unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]); } elseif (isset($this->definedNames[$definedName])) { unset($this->definedNames[$definedName]); } @@ -1143,26 +1144,26 @@ public function getCellXfCollection() /** * Get cellXf by index. * - * @param int $pIndex + * @param int $cellStyleIndex * * @return Style */ - public function getCellXfByIndex($pIndex) + public function getCellXfByIndex($cellStyleIndex) { - return $this->cellXfCollection[$pIndex]; + return $this->cellXfCollection[$cellStyleIndex]; } /** * Get cellXf by hash code. * - * @param string $pValue + * @param string $hashcode * * @return false|Style */ - public function getCellXfByHashCode($pValue) + public function getCellXfByHashCode($hashcode) { foreach ($this->cellXfCollection as $cellXf) { - if ($cellXf->getHashCode() === $pValue) { + if ($cellXf->getHashCode() === $hashcode) { return $cellXf; } } @@ -1173,13 +1174,13 @@ public function getCellXfByHashCode($pValue) /** * Check if style exists in style collection. * - * @param Style $pCellStyle + * @param Style $cellStyleIndex * * @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 @@ public function addCellXf(Style $style): void /** * 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.'); } // first remove the cellXf - array_splice($this->cellXfCollection, $pIndex, 1); + array_splice($this->cellXfCollection, $cellStyleIndex, 1); // then update cellXf indexes for cells foreach ($this->workSheetCollection as $worksheet) { foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); $xfIndex = $cell->getXfIndex(); - if ($xfIndex > $pIndex) { + if ($xfIndex > $cellStyleIndex) { // decrease xf index by 1 $cell->setXfIndex($xfIndex - 1); - } elseif ($xfIndex == $pIndex) { + } elseif ($xfIndex == $cellStyleIndex) { // set to default xf index 0 $cell->setXfIndex(0); } @@ -1258,26 +1259,26 @@ public function getCellStyleXfCollection() /** * Get cellStyleXf by index. * - * @param int $pIndex Index to cellXf + * @param int $cellStyleIndex Index to cellXf * * @return Style */ - public function getCellStyleXfByIndex($pIndex) + public function getCellStyleXfByIndex($cellStyleIndex) { - return $this->cellStyleXfCollection[$pIndex]; + return $this->cellStyleXfCollection[$cellStyleIndex]; } /** * Get cellStyleXf by hash code. * - * @param string $pValue + * @param string $hashcode * * @return false|Style */ - public function getCellStyleXfByHashCode($pValue) + public function getCellStyleXfByHashCode($hashcode) { foreach ($this->cellStyleXfCollection as $cellStyleXf) { - if ($cellStyleXf->getHashCode() === $pValue) { + if ($cellStyleXf->getHashCode() === $hashcode) { return $cellStyleXf; } } @@ -1288,23 +1289,23 @@ public function getCellStyleXfByHashCode($pValue) /** * Add a cellStyleXf to the workbook. */ - public function addCellStyleXf(Style $pStyle): void + public function addCellStyleXf(Style $style): void { - $this->cellStyleXfCollection[] = $pStyle; - $pStyle->setIndex(count($this->cellStyleXfCollection) - 1); + $this->cellStyleXfCollection[] = $style; + $style->setIndex(count($this->cellStyleXfCollection) - 1); } /** * 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.'); } - array_splice($this->cellStyleXfCollection, $pIndex, 1); + array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1); } /** diff --git a/src/PhpSpreadsheet/Style/Alignment.php b/src/PhpSpreadsheet/Style/Alignment.php index e072c52411..1b3ed6ac8d 100644 --- a/src/PhpSpreadsheet/Style/Alignment.php +++ b/src/PhpSpreadsheet/Style/Alignment.php @@ -140,36 +140,36 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells()) - ->applyFromArray($this->getStyleArray($pStyles)); + ->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['horizontal'])) { - $this->setHorizontal($pStyles['horizontal']); + if (isset($styleArray['horizontal'])) { + $this->setHorizontal($styleArray['horizontal']); } - if (isset($pStyles['vertical'])) { - $this->setVertical($pStyles['vertical']); + if (isset($styleArray['vertical'])) { + $this->setVertical($styleArray['vertical']); } - if (isset($pStyles['textRotation'])) { - $this->setTextRotation($pStyles['textRotation']); + if (isset($styleArray['textRotation'])) { + $this->setTextRotation($styleArray['textRotation']); } - if (isset($pStyles['wrapText'])) { - $this->setWrapText($pStyles['wrapText']); + if (isset($styleArray['wrapText'])) { + $this->setWrapText($styleArray['wrapText']); } - if (isset($pStyles['shrinkToFit'])) { - $this->setShrinkToFit($pStyles['shrinkToFit']); + if (isset($styleArray['shrinkToFit'])) { + $this->setShrinkToFit($styleArray['shrinkToFit']); } - if (isset($pStyles['indent'])) { - $this->setIndent($pStyles['indent']); + if (isset($styleArray['indent'])) { + $this->setIndent($styleArray['indent']); } - if (isset($pStyles['readOrder'])) { - $this->setReadOrder($pStyles['readOrder']); + if (isset($styleArray['readOrder'])) { + $this->setReadOrder($styleArray['readOrder']); } } @@ -193,21 +193,21 @@ public function getHorizontal() /** * Set Horizontal. * - * @param string $pValue see self::HORIZONTAL_* + * @param string $horizontalAlignment see self::HORIZONTAL_* * * @return $this */ - public function setHorizontal($pValue) + public function setHorizontal(string $horizontalAlignment) { - if ($pValue == '') { - $pValue = self::HORIZONTAL_GENERAL; + if ($horizontalAlignment == '') { + $horizontalAlignment = self::HORIZONTAL_GENERAL; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['horizontal' => $pValue]); + $styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->horizontal = $pValue; + $this->horizontal = $horizontalAlignment; } return $this; @@ -230,21 +230,21 @@ public function getVertical() /** * Set Vertical. * - * @param string $pValue see self::VERTICAL_* + * @param string $verticalAlignment see self::VERTICAL_* * * @return $this */ - public function setVertical($pValue) + public function setVertical($verticalAlignment) { - if ($pValue == '') { - $pValue = self::VERTICAL_BOTTOM; + if ($verticalAlignment == '') { + $verticalAlignment = self::VERTICAL_BOTTOM; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['vertical' => $pValue]); + $styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->vertical = $pValue; + $this->vertical = $verticalAlignment; } return $this; @@ -267,24 +267,24 @@ public function getTextRotation() /** * Set TextRotation. * - * @param int $pValue + * @param int $angleInDegrees * * @return $this */ - public function setTextRotation($pValue) + public function setTextRotation($angleInDegrees) { // Excel2007 value 255 => PhpSpreadsheet value -165 - if ($pValue == self::TEXTROTATION_STACK_EXCEL) { - $pValue = self::TEXTROTATION_STACK_PHPSPREADSHEET; + if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) { + $angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET; } // 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) { - $styleArray = $this->getStyleArray(['textRotation' => $pValue]); + $styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->textRotation = $pValue; + $this->textRotation = $angleInDegrees; } } else { throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.'); @@ -310,20 +310,20 @@ public function getWrapText() /** * Set Wrap Text. * - * @param bool $pValue + * @param bool $wrapped * * @return $this */ - public function setWrapText($pValue) + public function setWrapText($wrapped) { - if ($pValue == '') { - $pValue = false; + if ($wrapped == '') { + $wrapped = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['wrapText' => $pValue]); + $styleArray = $this->getStyleArray(['wrapText' => $wrapped]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->wrapText = $pValue; + $this->wrapText = $wrapped; } return $this; @@ -346,20 +346,20 @@ public function getShrinkToFit() /** * Set Shrink to fit. * - * @param bool $pValue + * @param bool $shrink * * @return $this */ - public function setShrinkToFit($pValue) + public function setShrinkToFit($shrink) { - if ($pValue == '') { - $pValue = false; + if ($shrink == '') { + $shrink = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['shrinkToFit' => $pValue]); + $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->shrinkToFit = $pValue; + $this->shrinkToFit = $shrink; } return $this; @@ -382,27 +382,27 @@ public function getIndent() /** * Set indent. * - * @param int $pValue + * @param int $indent * * @return $this */ - public function setIndent($pValue) + public function setIndent($indent) { - if ($pValue > 0) { + if ($indent > 0) { if ( $this->getHorizontal() != self::HORIZONTAL_GENERAL && $this->getHorizontal() != self::HORIZONTAL_LEFT && $this->getHorizontal() != self::HORIZONTAL_RIGHT && $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED ) { - $pValue = 0; // indent not supported + $indent = 0; // indent not supported } } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['indent' => $pValue]); + $styleArray = $this->getStyleArray(['indent' => $indent]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->indent = $pValue; + $this->indent = $indent; } return $this; @@ -425,20 +425,20 @@ public function getReadOrder() /** * Set read order. * - * @param int $pValue + * @param int $readOrder * * @return $this */ - public function setReadOrder($pValue) + public function setReadOrder($readOrder) { - if ($pValue < 0 || $pValue > 2) { - $pValue = 0; + if ($readOrder < 0 || $readOrder > 2) { + $readOrder = 0; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['readOrder' => $pValue]); + $styleArray = $this->getStyleArray(['readOrder' => $readOrder]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->readOrder = $pValue; + $this->readOrder = $readOrder; } return $this; diff --git a/src/PhpSpreadsheet/Style/Border.php b/src/PhpSpreadsheet/Style/Border.php index a8af9d941c..9fabf366c3 100644 --- a/src/PhpSpreadsheet/Style/Border.php +++ b/src/PhpSpreadsheet/Style/Border.php @@ -114,20 +114,20 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['borderStyle'])) { - $this->setBorderStyle($pStyles['borderStyle']); + if (isset($styleArray['borderStyle'])) { + $this->setBorderStyle($styleArray['borderStyle']); } - if (isset($pStyles['color'])) { - $this->getColor()->applyFromArray($pStyles['color']); + if (isset($styleArray['color'])) { + $this->getColor()->applyFromArray($styleArray['color']); } } @@ -151,24 +151,25 @@ public function getBorderStyle() /** * Set Border style. * - * @param bool|string $pValue + * @param bool|string $style * When passing a boolean, FALSE equates Border::BORDER_NONE * and TRUE to Border::BORDER_MEDIUM * * @return $this */ - public function setBorderStyle($pValue) + public function setBorderStyle($style) { - if (empty($pValue)) { - $pValue = self::BORDER_NONE; - } elseif (is_bool($pValue) && $pValue) { - $pValue = self::BORDER_MEDIUM; + if (empty($style)) { + $style = self::BORDER_NONE; + } elseif (is_bool($style)) { + $style = self::BORDER_MEDIUM; } + if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['borderStyle' => $pValue]); + $styleArray = $this->getStyleArray(['borderStyle' => $style]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->borderStyle = $pValue; + $this->borderStyle = $style; } return $this; @@ -189,10 +190,10 @@ public function getColor() * * @return $this */ - public function setColor(Color $pValue) + public function setColor(Color $color) { // 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) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); diff --git a/src/PhpSpreadsheet/Style/Borders.php b/src/PhpSpreadsheet/Style/Borders.php index eeb4932a1e..5d92f93597 100644 --- a/src/PhpSpreadsheet/Style/Borders.php +++ b/src/PhpSpreadsheet/Style/Borders.php @@ -190,38 +190,38 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['left'])) { - $this->getLeft()->applyFromArray($pStyles['left']); + if (isset($styleArray['left'])) { + $this->getLeft()->applyFromArray($styleArray['left']); } - if (isset($pStyles['right'])) { - $this->getRight()->applyFromArray($pStyles['right']); + if (isset($styleArray['right'])) { + $this->getRight()->applyFromArray($styleArray['right']); } - if (isset($pStyles['top'])) { - $this->getTop()->applyFromArray($pStyles['top']); + if (isset($styleArray['top'])) { + $this->getTop()->applyFromArray($styleArray['top']); } - if (isset($pStyles['bottom'])) { - $this->getBottom()->applyFromArray($pStyles['bottom']); + if (isset($styleArray['bottom'])) { + $this->getBottom()->applyFromArray($styleArray['bottom']); } - if (isset($pStyles['diagonal'])) { - $this->getDiagonal()->applyFromArray($pStyles['diagonal']); + if (isset($styleArray['diagonal'])) { + $this->getDiagonal()->applyFromArray($styleArray['diagonal']); } - if (isset($pStyles['diagonalDirection'])) { - $this->setDiagonalDirection($pStyles['diagonalDirection']); + if (isset($styleArray['diagonalDirection'])) { + $this->setDiagonalDirection($styleArray['diagonalDirection']); } - if (isset($pStyles['allBorders'])) { - $this->getLeft()->applyFromArray($pStyles['allBorders']); - $this->getRight()->applyFromArray($pStyles['allBorders']); - $this->getTop()->applyFromArray($pStyles['allBorders']); - $this->getBottom()->applyFromArray($pStyles['allBorders']); + if (isset($styleArray['allBorders'])) { + $this->getLeft()->applyFromArray($styleArray['allBorders']); + $this->getRight()->applyFromArray($styleArray['allBorders']); + $this->getTop()->applyFromArray($styleArray['allBorders']); + $this->getBottom()->applyFromArray($styleArray['allBorders']); } } @@ -365,20 +365,20 @@ public function getDiagonalDirection() /** * Set DiagonalDirection. * - * @param int $pValue see self::DIAGONAL_* + * @param int $direction see self::DIAGONAL_* * * @return $this */ - public function setDiagonalDirection($pValue) + public function setDiagonalDirection($direction) { - if ($pValue == '') { - $pValue = self::DIAGONAL_NONE; + if ($direction == '') { + $direction = self::DIAGONAL_NONE; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['diagonalDirection' => $pValue]); + $styleArray = $this->getStyleArray(['diagonalDirection' => $direction]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->diagonalDirection = $pValue; + $this->diagonalDirection = $direction; } return $this; diff --git a/src/PhpSpreadsheet/Style/Color.php b/src/PhpSpreadsheet/Style/Color.php index bf5d093f09..d9b9830cb3 100644 --- a/src/PhpSpreadsheet/Style/Color.php +++ b/src/PhpSpreadsheet/Style/Color.php @@ -27,6 +27,10 @@ class Color extends Supervisor const COLOR_YELLOW = 'FFFFFF00'; 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. * @@ -37,14 +41,14 @@ class Color extends Supervisor /** * ARGB - Alpha RGB. * - * @var string + * @var null|string */ protected $argb; /** * 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 * Leave this value at default unless you understand exactly what * its ramifications are @@ -52,14 +56,14 @@ class Color extends Supervisor * Leave this value at default unless you understand exactly what * 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? parent::__construct($isSupervisor); // Initialise values if (!$isConditional) { - $this->argb = $pARGB; + $this->argb = $this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE) ? $colorValue : self::COLOR_BLACK; } } @@ -102,32 +106,36 @@ public function getStyleArray($array) * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['rgb'])) { - $this->setRGB($pStyles['rgb']); + if (isset($styleArray['rgb'])) { + $this->setRGB($styleArray['rgb']); } - if (isset($pStyles['argb'])) { - $this->setARGB($pStyles['argb']); + if (isset($styleArray['argb'])) { + $this->setARGB($styleArray['argb']); } } 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. - * - * @return string */ - public function getARGB() + public function getARGB(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getARGB(); @@ -139,20 +147,23 @@ public function getARGB() /** * Set ARGB. * - * @param string $pValue see self::COLOR_* + * @param string $colorValue ARGB value, or a named color * * @return $this */ - public function setARGB($pValue) + public function setARGB(?string $colorValue = self::COLOR_BLACK) { - if ($pValue == '') { - $pValue = self::COLOR_BLACK; + if ($colorValue === '' || $colorValue === null) { + $colorValue = self::COLOR_BLACK; + } elseif (!$this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE)) { + return $this; } + if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['argb' => $pValue]); + $styleArray = $this->getStyleArray(['argb' => $colorValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->argb = $pValue; + $this->argb = $colorValue; } return $this; @@ -160,10 +171,8 @@ public function setARGB($pValue) /** * Get RGB. - * - * @return string */ - public function getRGB() + public function getRGB(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getRGB(); @@ -175,20 +184,23 @@ public function getRGB() /** * Set RGB. * - * @param string $pValue RGB value + * @param string $colorValue RGB value, or a named color * * @return $this */ - public function setRGB($pValue) + public function setRGB(?string $colorValue = self::COLOR_BLACK) { - if ($pValue == '') { - $pValue = '000000'; + if ($colorValue === '' || $colorValue === null) { + $colorValue = '000000'; + } elseif (!$this->validateColor($colorValue, self::VALIDATE_RGB_SIZE)) { + return $this; } + if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['argb' => 'FF' . $pValue]); + $styleArray = $this->getStyleArray(['argb' => 'FF' . $colorValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->argb = 'FF' . $pValue; + $this->argb = 'FF' . $colorValue; } return $this; @@ -197,16 +209,16 @@ public function setRGB($pValue) /** * 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 bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * * @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); } @@ -214,64 +226,64 @@ private static function getColourComponent($RGB, $offset, $hex = true) /** * 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 * decimal value * * @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. * - * @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 * decimal value * * @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. * - * @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 * decimal value * * @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. * - * @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 * * @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)); /** @var int $red */ - $red = self::getRed($hex, false); + $red = self::getRed($hexColourValue, false); /** @var int $green */ - $green = self::getGreen($hex, false); + $green = self::getGreen($hexColourValue, false); /** @var int $blue */ - $blue = self::getBlue($hex, false); + $blue = self::getBlue($hexColourValue, false); if ($adjustPercentage > 0) { $red += (255 - $red) * $adjustPercentage; $green += (255 - $green) * $adjustPercentage; @@ -294,16 +306,16 @@ public static function changeBrightness($hex, $adjustPercentage) /** * 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 * 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 - $pIndex = (int) $pIndex; + $colorIndex = (int) $colorIndex; // Indexed colors if (self::$indexedColors === null) { @@ -367,15 +379,11 @@ public static function indexedColor($pIndex, $background = false) ]; } - if (isset(self::$indexedColors[$pIndex])) { - return new self(self::$indexedColors[$pIndex]); - } - - if ($background) { - return new self(self::COLOR_WHITE); + if (isset(self::$indexedColors[$colorIndex])) { + return new self(self::$indexedColors[$colorIndex]); } - return new self(self::COLOR_BLACK); + return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK); } /** @@ -383,7 +391,7 @@ public static function indexedColor($pIndex, $background = false) * * @return string Hash code */ - public function getHashCode() + public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); diff --git a/src/PhpSpreadsheet/Style/Conditional.php b/src/PhpSpreadsheet/Style/Conditional.php index c3628da60e..3f84a4c994 100644 --- a/src/PhpSpreadsheet/Style/Conditional.php +++ b/src/PhpSpreadsheet/Style/Conditional.php @@ -112,13 +112,13 @@ public function getConditionType() /** * Set Condition type. * - * @param string $pValue Condition type, see self::CONDITION_* + * @param string $type Condition type, see self::CONDITION_* * * @return $this */ - public function setConditionType($pValue) + public function setConditionType($type) { - $this->conditionType = $pValue; + $this->conditionType = $type; return $this; } @@ -136,13 +136,13 @@ public function getOperatorType() /** * Set Operator type. * - * @param string $pValue Conditional operator type, see self::OPERATOR_* + * @param string $type Conditional operator type, see self::OPERATOR_* * * @return $this */ - public function setOperatorType($pValue) + public function setOperatorType($type) { - $this->operatorType = $pValue; + $this->operatorType = $type; return $this; } @@ -160,13 +160,13 @@ public function getText() /** * Set text. * - * @param string $value + * @param string $text * * @return $this */ - public function setText($value) + public function setText($text) { - $this->text = $value; + $this->text = $text; return $this; } @@ -184,13 +184,13 @@ public function getStopIfTrue() /** * Set StopIfTrue. * - * @param bool $value + * @param bool $stopIfTrue * * @return $this */ - public function setStopIfTrue($value) + public function setStopIfTrue($stopIfTrue) { - $this->stopIfTrue = $value; + $this->stopIfTrue = $stopIfTrue; return $this; } @@ -208,16 +208,16 @@ public function getConditions() /** * Set Conditions. * - * @param bool|float|int|string|string[] $pValue Condition + * @param bool|float|int|string|string[] $conditions Condition * * @return $this */ - public function setConditions($pValue) + public function setConditions($conditions) { - if (!is_array($pValue)) { - $pValue = [$pValue]; + if (!is_array($conditions)) { + $conditions = [$conditions]; } - $this->condition = $pValue; + $this->condition = $conditions; return $this; } @@ -225,13 +225,13 @@ public function setConditions($pValue) /** * Add Condition. * - * @param string $pValue Condition + * @param string $condition Condition * * @return $this */ - public function addCondition($pValue) + public function addCondition($condition) { - $this->condition[] = $pValue; + $this->condition[] = $condition; return $this; } @@ -249,13 +249,13 @@ public function getStyle() /** * Set Style. * - * @param Style $pValue + * @param Style $style * * @return $this */ - public function setStyle(?Style $pValue = null) + public function setStyle(?Style $style = null) { - $this->style = $pValue; + $this->style = $style; return $this; } diff --git a/src/PhpSpreadsheet/Style/Fill.php b/src/PhpSpreadsheet/Style/Fill.php index e793f1e70d..1a7331eb0d 100644 --- a/src/PhpSpreadsheet/Style/Fill.php +++ b/src/PhpSpreadsheet/Style/Fill.php @@ -135,30 +135,30 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['fillType'])) { - $this->setFillType($pStyles['fillType']); + if (isset($styleArray['fillType'])) { + $this->setFillType($styleArray['fillType']); } - if (isset($pStyles['rotation'])) { - $this->setRotation($pStyles['rotation']); + if (isset($styleArray['rotation'])) { + $this->setRotation($styleArray['rotation']); } - if (isset($pStyles['startColor'])) { - $this->getStartColor()->applyFromArray($pStyles['startColor']); + if (isset($styleArray['startColor'])) { + $this->getStartColor()->applyFromArray($styleArray['startColor']); } - if (isset($pStyles['endColor'])) { - $this->getEndColor()->applyFromArray($pStyles['endColor']); + if (isset($styleArray['endColor'])) { + $this->getEndColor()->applyFromArray($styleArray['endColor']); } - if (isset($pStyles['color'])) { - $this->getStartColor()->applyFromArray($pStyles['color']); - $this->getEndColor()->applyFromArray($pStyles['color']); + if (isset($styleArray['color'])) { + $this->getStartColor()->applyFromArray($styleArray['color']); + $this->getEndColor()->applyFromArray($styleArray['color']); } } @@ -182,17 +182,17 @@ public function getFillType() /** * Set Fill Type. * - * @param string $pValue Fill type, see self::FILL_* + * @param string $fillType Fill type, see self::FILL_* * * @return $this */ - public function setFillType($pValue) + public function setFillType($fillType) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['fillType' => $pValue]); + $styleArray = $this->getStyleArray(['fillType' => $fillType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->fillType = $pValue; + $this->fillType = $fillType; } return $this; @@ -215,17 +215,17 @@ public function getRotation() /** * Set Rotation. * - * @param float $pValue + * @param float $angleInDegrees * * @return $this */ - public function setRotation($pValue) + public function setRotation($angleInDegrees) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['rotation' => $pValue]); + $styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->rotation = $pValue; + $this->rotation = $angleInDegrees; } return $this; @@ -246,10 +246,10 @@ public function getStartColor() * * @return $this */ - public function setStartColor(Color $pValue) + public function setStartColor(Color $color) { // 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) { $styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]); @@ -276,10 +276,10 @@ public function getEndColor() * * @return $this */ - public function setEndColor(Color $pValue) + public function setEndColor(Color $color) { // 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) { $styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]); diff --git a/src/PhpSpreadsheet/Style/Font.php b/src/PhpSpreadsheet/Style/Font.php index 5f73c1d312..63a75cc55c 100644 --- a/src/PhpSpreadsheet/Style/Font.php +++ b/src/PhpSpreadsheet/Style/Font.php @@ -155,41 +155,41 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['name'])) { - $this->setName($pStyles['name']); + if (isset($styleArray['name'])) { + $this->setName($styleArray['name']); } - if (isset($pStyles['bold'])) { - $this->setBold($pStyles['bold']); + if (isset($styleArray['bold'])) { + $this->setBold($styleArray['bold']); } - if (isset($pStyles['italic'])) { - $this->setItalic($pStyles['italic']); + if (isset($styleArray['italic'])) { + $this->setItalic($styleArray['italic']); } - if (isset($pStyles['superscript'])) { - $this->setSuperscript($pStyles['superscript']); + if (isset($styleArray['superscript'])) { + $this->setSuperscript($styleArray['superscript']); } - if (isset($pStyles['subscript'])) { - $this->setSubscript($pStyles['subscript']); + if (isset($styleArray['subscript'])) { + $this->setSubscript($styleArray['subscript']); } - if (isset($pStyles['underline'])) { - $this->setUnderline($pStyles['underline']); + if (isset($styleArray['underline'])) { + $this->setUnderline($styleArray['underline']); } - if (isset($pStyles['strikethrough'])) { - $this->setStrikethrough($pStyles['strikethrough']); + if (isset($styleArray['strikethrough'])) { + $this->setStrikethrough($styleArray['strikethrough']); } - if (isset($pStyles['color'])) { - $this->getColor()->applyFromArray($pStyles['color']); + if (isset($styleArray['color'])) { + $this->getColor()->applyFromArray($styleArray['color']); } - if (isset($pStyles['size'])) { - $this->setSize($pStyles['size']); + if (isset($styleArray['size'])) { + $this->setSize($styleArray['size']); } } @@ -292,20 +292,20 @@ public function getBold() /** * Set Bold. * - * @param bool $pValue + * @param bool $bold * * @return $this */ - public function setBold($pValue) + public function setBold($bold) { - if ($pValue == '') { - $pValue = false; + if ($bold == '') { + $bold = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['bold' => $pValue]); + $styleArray = $this->getStyleArray(['bold' => $bold]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->bold = $pValue; + $this->bold = $bold; } return $this; @@ -328,20 +328,20 @@ public function getItalic() /** * Set Italic. * - * @param bool $pValue + * @param bool $italic * * @return $this */ - public function setItalic($pValue) + public function setItalic($italic) { - if ($pValue == '') { - $pValue = false; + if ($italic == '') { + $italic = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['italic' => $pValue]); + $styleArray = $this->getStyleArray(['italic' => $italic]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->italic = $pValue; + $this->italic = $italic; } return $this; @@ -366,13 +366,13 @@ public function getSuperscript() * * @return $this */ - public function setSuperscript(bool $pValue) + public function setSuperscript(bool $superscript) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['superscript' => $pValue]); + $styleArray = $this->getStyleArray(['superscript' => $superscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->superscript = $pValue; + $this->superscript = $superscript; if ($this->superscript) { $this->subscript = false; } @@ -400,13 +400,13 @@ public function getSubscript() * * @return $this */ - public function setSubscript(bool $pValue) + public function setSubscript(bool $subscript) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['subscript' => $pValue]); + $styleArray = $this->getStyleArray(['subscript' => $subscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->subscript = $pValue; + $this->subscript = $subscript; if ($this->subscript) { $this->superscript = false; } @@ -432,24 +432,24 @@ public function getUnderline() /** * 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, * false equates to UNDERLINE_NONE * * @return $this */ - public function setUnderline($pValue) + public function setUnderline($underlineStyle) { - if (is_bool($pValue)) { - $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; - } elseif ($pValue == '') { - $pValue = self::UNDERLINE_NONE; + if (is_bool($underlineStyle)) { + $underlineStyle = ($underlineStyle) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; + } elseif ($underlineStyle == '') { + $underlineStyle = self::UNDERLINE_NONE; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['underline' => $pValue]); + $styleArray = $this->getStyleArray(['underline' => $underlineStyle]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->underline = $pValue; + $this->underline = $underlineStyle; } return $this; @@ -472,21 +472,21 @@ public function getStrikethrough() /** * Set Strikethrough. * - * @param bool $pValue + * @param bool $strikethru * * @return $this */ - public function setStrikethrough($pValue) + public function setStrikethrough($strikethru) { - if ($pValue == '') { - $pValue = false; + if ($strikethru == '') { + $strikethru = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['strikethrough' => $pValue]); + $styleArray = $this->getStyleArray(['strikethrough' => $strikethru]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->strikethrough = $pValue; + $this->strikethrough = $strikethru; } return $this; @@ -507,10 +507,10 @@ public function getColor() * * @return $this */ - public function setColor(Color $pValue) + public function setColor(Color $color) { // 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) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); diff --git a/src/PhpSpreadsheet/Style/NumberFormat.php b/src/PhpSpreadsheet/Style/NumberFormat.php index 6235d8640a..a456928322 100644 --- a/src/PhpSpreadsheet/Style/NumberFormat.php +++ b/src/PhpSpreadsheet/Style/NumberFormat.php @@ -130,17 +130,17 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['formatCode'])) { - $this->setFormatCode($pStyles['formatCode']); + if (isset($styleArray['formatCode'])) { + $this->setFormatCode($styleArray['formatCode']); } } @@ -167,21 +167,21 @@ public function getFormatCode() /** * Set Format Code. * - * @param string $pValue see self::FORMAT_* + * @param string $formatCode see self::FORMAT_* * * @return $this */ - public function setFormatCode($pValue) + public function setFormatCode($formatCode) { - if ($pValue == '') { - $pValue = self::FORMAT_GENERAL; + if ($formatCode == '') { + $formatCode = self::FORMAT_GENERAL; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['formatCode' => $pValue]); + $styleArray = $this->getStyleArray(['formatCode' => $formatCode]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->formatCode = $pValue; - $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue); + $this->formatCode = $formatCode; + $this->builtInFormatCode = self::builtInFormatCodeIndex($formatCode); } return $this; @@ -204,18 +204,18 @@ public function getBuiltInFormatCode() /** * Set Built-In Format Code. * - * @param int $pValue + * @param int $formatCodeIndex * * @return $this */ - public function setBuiltInFormatCode($pValue) + public function setBuiltInFormatCode($formatCodeIndex) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($pValue)]); + $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($formatCodeIndex)]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->builtInFormatCode = $pValue; - $this->formatCode = self::builtInFormatCode($pValue); + $this->builtInFormatCode = $formatCodeIndex; + $this->formatCode = self::builtInFormatCode($formatCodeIndex); } return $this; @@ -327,21 +327,21 @@ private static function fillBuiltInFormatCodes(): void /** * Get built-in format code. * - * @param int $pIndex + * @param int $index * * @return string */ - public static function builtInFormatCode($pIndex) + public static function builtInFormatCode($index) { // Clean parameter - $pIndex = (int) $pIndex; + $index = (int) $index; // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code - if (isset(self::$builtInFormats[$pIndex])) { - return self::$builtInFormats[$pIndex]; + if (isset(self::$builtInFormats[$index])) { + return self::$builtInFormats[$index]; } return ''; @@ -350,18 +350,18 @@ public static function builtInFormatCode($pIndex) /** * Get built-in format code index. * - * @param string $formatCode + * @param string $formatCodeIndex * * @return bool|int */ - public static function builtInFormatCodeIndex($formatCode) + public static function builtInFormatCodeIndex($formatCodeIndex) { // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code - if (array_key_exists($formatCode, self::$flippedBuiltInFormats)) { - return self::$flippedBuiltInFormats[$formatCode]; + if (array_key_exists($formatCodeIndex, self::$flippedBuiltInFormats)) { + return self::$flippedBuiltInFormats[$formatCodeIndex]; } return false; diff --git a/src/PhpSpreadsheet/Style/Protection.php b/src/PhpSpreadsheet/Style/Protection.php index 9ae7d4bb36..fc15e3b831 100644 --- a/src/PhpSpreadsheet/Style/Protection.php +++ b/src/PhpSpreadsheet/Style/Protection.php @@ -80,20 +80,20 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['locked'])) { - $this->setLocked($pStyles['locked']); + if (isset($styleArray['locked'])) { + $this->setLocked($styleArray['locked']); } - if (isset($pStyles['hidden'])) { - $this->setHidden($pStyles['hidden']); + if (isset($styleArray['hidden'])) { + $this->setHidden($styleArray['hidden']); } } @@ -117,17 +117,17 @@ public function getLocked() /** * Set locked. * - * @param string $pValue see self::PROTECTION_* + * @param string $lockType see self::PROTECTION_* * * @return $this */ - public function setLocked($pValue) + public function setLocked($lockType) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['locked' => $pValue]); + $styleArray = $this->getStyleArray(['locked' => $lockType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->locked = $pValue; + $this->locked = $lockType; } return $this; @@ -150,17 +150,17 @@ public function getHidden() /** * Set hidden. * - * @param string $pValue see self::PROTECTION_* + * @param string $hiddenType see self::PROTECTION_* * * @return $this */ - public function setHidden($pValue) + public function setHidden($hiddenType) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['hidden' => $pValue]); + $styleArray = $this->getStyleArray(['hidden' => $hiddenType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->hidden = $pValue; + $this->hidden = $hiddenType; } return $this; diff --git a/src/PhpSpreadsheet/Style/Style.php b/src/PhpSpreadsheet/Style/Style.php index 5453baa875..5823929d0e 100644 --- a/src/PhpSpreadsheet/Style/Style.php +++ b/src/PhpSpreadsheet/Style/Style.php @@ -120,10 +120,8 @@ public function __construct($isSupervisor = false, $isConditional = false) /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. - * - * @return Style */ - public function getSharedComponent() + public function getSharedComponent(): self { $activeSheet = $this->getActiveSheet(); $selectedCell = $this->getActiveCell(); // e.g. 'A1' @@ -199,12 +197,12 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * @param bool $pAdvanced advanced mode for setting borders + * @param array $styleArray Array containing style information + * @param bool $advancedBorders advanced mode for setting borders * * @return $this */ - public function applyFromArray(array $pStyles, $pAdvanced = true) + public function applyFromArray(array $styleArray, $advancedBorders = true) { if ($this->isSupervisor) { $pRange = $this->getSelectedCells(); @@ -237,36 +235,36 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) } // ADVANCED MODE: - if ($pAdvanced && isset($pStyles['borders'])) { + if ($advancedBorders && isset($styleArray['borders'])) { // 'allBorders' is a shorthand property for 'outline' and 'inside' and // it applies to components that have not been set explicitly - if (isset($pStyles['borders']['allBorders'])) { + if (isset($styleArray['borders']['allBorders'])) { foreach (['outline', 'inside'] as $component) { - if (!isset($pStyles['borders'][$component])) { - $pStyles['borders'][$component] = $pStyles['borders']['allBorders']; + if (!isset($styleArray['borders'][$component])) { + $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' // 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) { - if (!isset($pStyles['borders'][$component])) { - $pStyles['borders'][$component] = $pStyles['borders']['outline']; + if (!isset($styleArray['borders'][$component])) { + $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' // 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) { - if (!isset($pStyles['borders'][$component])) { - $pStyles['borders'][$component] = $pStyles['borders']['inside']; + if (!isset($styleArray['borders'][$component])) { + $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) $xMax = min($rangeEndIndexes[0] - $rangeStartIndexes[0] + 1, 3); @@ -315,7 +313,7 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; // retrieve relevant style array for region - $regionStyles = $pStyles; + $regionStyles = $styleArray; unset($regionStyles['borders']['inside']); // what are the inner edges of the region when looking at the selection @@ -327,8 +325,8 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) case 'top': case 'bottom': // should pick up 'horizontal' border property if set - if (isset($pStyles['borders']['horizontal'])) { - $regionStyles['borders'][$innerEdge] = $pStyles['borders']['horizontal']; + if (isset($styleArray['borders']['horizontal'])) { + $regionStyles['borders'][$innerEdge] = $styleArray['borders']['horizontal']; } else { unset($regionStyles['borders'][$innerEdge]); } @@ -337,8 +335,8 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) case 'left': case 'right': // should pick up 'vertical' border property if set - if (isset($pStyles['borders']['vertical'])) { - $regionStyles['borders'][$innerEdge] = $pStyles['borders']['vertical']; + if (isset($styleArray['borders']['vertical'])) { + $regionStyles['borders'][$innerEdge] = $styleArray['borders']['vertical']; } else { unset($regionStyles['borders'][$innerEdge]); } @@ -375,7 +373,7 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) } // 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 $workbook = $this->getActiveSheet()->getParent(); @@ -387,7 +385,7 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) if (self::$cachedStyles === null) { // Clone the old style and apply style-array $newStyle = clone $style; - $newStyle->applyFromArray($pStyles); + $newStyle->applyFromArray($styleArray); // Look for existing style we can use instead (reduce memory usage) $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); @@ -409,7 +407,7 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) if (!$existingStyle) { // The old style combined with the new style array is not cached, so we create it now $newStyle = clone $style; - $newStyle->applyFromArray($pStyles); + $newStyle->applyFromArray($styleArray); // Look for similar style in workbook to reduce memory usage $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); @@ -428,7 +426,7 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) // $newStyle should always be defined. // This block might not be needed in the future $newStyle = clone $style; - $newStyle->applyFromArray($pStyles); + $newStyle->applyFromArray($styleArray); } // we don't have such a cell Xf, need to add @@ -475,33 +473,33 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) } } else { // not a supervisor, just apply the style array directly on style object - if (isset($pStyles['fill'])) { - $this->getFill()->applyFromArray($pStyles['fill']); + if (isset($styleArray['fill'])) { + $this->getFill()->applyFromArray($styleArray['fill']); } - if (isset($pStyles['font'])) { - $this->getFont()->applyFromArray($pStyles['font']); + if (isset($styleArray['font'])) { + $this->getFont()->applyFromArray($styleArray['font']); } - if (isset($pStyles['borders'])) { - $this->getBorders()->applyFromArray($pStyles['borders']); + if (isset($styleArray['borders'])) { + $this->getBorders()->applyFromArray($styleArray['borders']); } - if (isset($pStyles['alignment'])) { - $this->getAlignment()->applyFromArray($pStyles['alignment']); + if (isset($styleArray['alignment'])) { + $this->getAlignment()->applyFromArray($styleArray['alignment']); } - if (isset($pStyles['numberFormat'])) { - $this->getNumberFormat()->applyFromArray($pStyles['numberFormat']); + if (isset($styleArray['numberFormat'])) { + $this->getNumberFormat()->applyFromArray($styleArray['numberFormat']); } - if (isset($pStyles['protection'])) { - $this->getProtection()->applyFromArray($pStyles['protection']); + if (isset($styleArray['protection'])) { + $this->getProtection()->applyFromArray($styleArray['protection']); } - if (isset($pStyles['quotePrefix'])) { - $this->quotePrefix = $pStyles['quotePrefix']; + if (isset($styleArray['quotePrefix'])) { + $this->quotePrefix = $styleArray['quotePrefix']; } } 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 = []; switch ($selectionType) { @@ -514,7 +512,7 @@ private function getOldXfIndexes(string $selectionType, array $rangeStart, array $cellIterator->setIterateOnlyExistingCells(true); foreach ($cellIterator as $columnCell) { if ($columnCell !== null) { - $columnCell->getStyle()->applyFromArray($pStyles); + $columnCell->getStyle()->applyFromArray($styleArray); } } } @@ -533,7 +531,7 @@ private function getOldXfIndexes(string $selectionType, array $rangeStart, array $cellIterator->setIterateOnlyExistingCells(true); foreach ($cellIterator as $rowCell) { if ($rowCell !== null) { - $rowCell->getStyle()->applyFromArray($pStyles); + $rowCell->getStyle()->applyFromArray($styleArray); } } } @@ -627,13 +625,13 @@ public function getConditionalStyles() /** * Set Conditional Styles. Only used on supervisor. * - * @param Conditional[] $pValue Array of conditional styles + * @param Conditional[] $conditionalStyleArray Array of conditional styles * * @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; } @@ -665,20 +663,20 @@ public function getQuotePrefix() /** * Set quote prefix. * - * @param bool $pValue + * @param bool $quotePrefix * * @return $this */ - public function setQuotePrefix($pValue) + public function setQuotePrefix($quotePrefix) { - if ($pValue == '') { - $pValue = false; + if ($quotePrefix == '') { + $quotePrefix = false; } if ($this->isSupervisor) { - $styleArray = ['quotePrefix' => $pValue]; + $styleArray = ['quotePrefix' => $quotePrefix]; $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->quotePrefix = (bool) $pValue; + $this->quotePrefix = (bool) $quotePrefix; } return $this; @@ -716,11 +714,11 @@ public function getIndex() /** * 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 diff --git a/src/PhpSpreadsheet/Worksheet/AutoFilter.php b/src/PhpSpreadsheet/Worksheet/AutoFilter.php index 53fb2347af..f9b1643771 100644 --- a/src/PhpSpreadsheet/Worksheet/AutoFilter.php +++ b/src/PhpSpreadsheet/Worksheet/AutoFilter.php @@ -39,12 +39,12 @@ class AutoFilter * Create a new AutoFilter. * * @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->workSheet = $pSheet; + $this->workSheet = $worksheet; } /** @@ -60,13 +60,13 @@ public function getParent() /** * Set AutoFilter Parent Worksheet. * - * @param Worksheet $pSheet + * @param Worksheet $worksheet * * @return $this */ - public function setParent(?Worksheet $pSheet = null) + public function setParent(?Worksheet $worksheet = null) { - $this->workSheet = $pSheet; + $this->workSheet = $worksheet; return $this; } diff --git a/src/PhpSpreadsheet/Writer/BaseWriter.php b/src/PhpSpreadsheet/Writer/BaseWriter.php index ddd61113df..7811a2a0ed 100644 --- a/src/PhpSpreadsheet/Writer/BaseWriter.php +++ b/src/PhpSpreadsheet/Writer/BaseWriter.php @@ -50,9 +50,9 @@ public function getIncludeCharts() return $this->includeCharts; } - public function setIncludeCharts($pValue) + public function setIncludeCharts($includeCharts) { - $this->includeCharts = (bool) $pValue; + $this->includeCharts = (bool) $includeCharts; return $this; } @@ -62,9 +62,9 @@ public function getPreCalculateFormulas() return $this->preCalculateFormulas; } - public function setPreCalculateFormulas($pValue) + public function setPreCalculateFormulas($precalculateFormulas) { - $this->preCalculateFormulas = (bool) $pValue; + $this->preCalculateFormulas = (bool) $precalculateFormulas; return $this; } @@ -74,15 +74,15 @@ public function getUseDiskCaching() 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 (is_dir($pDirectory)) { - $this->diskCachingDirectory = $pDirectory; + if ($cacheDirectory !== null) { + if (is_dir($cacheDirectory)) { + $this->diskCachingDirectory = $cacheDirectory; } else { - throw new Exception("Directory does not exist: $pDirectory"); + throw new Exception("Directory does not exist: $cacheDirectory"); } } diff --git a/src/PhpSpreadsheet/Writer/Csv.php b/src/PhpSpreadsheet/Writer/Csv.php index 2f6cad2bb2..556ac2dea9 100644 --- a/src/PhpSpreadsheet/Writer/Csv.php +++ b/src/PhpSpreadsheet/Writer/Csv.php @@ -84,9 +84,9 @@ public function __construct(Spreadsheet $spreadsheet) /** * 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); @@ -99,7 +99,7 @@ public function save($pFilename, int $flags = 0): void Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); // Open file - $this->openFileHandle($pFilename); + $this->openFileHandle($filename); if ($this->excelCompatibility) { $this->setUseBOM(true); // Enforce UTF-8 BOM Header diff --git a/src/PhpSpreadsheet/Writer/Html.php b/src/PhpSpreadsheet/Writer/Html.php index 1ac4d4bafb..b440358b41 100644 --- a/src/PhpSpreadsheet/Writer/Html.php +++ b/src/PhpSpreadsheet/Writer/Html.php @@ -152,14 +152,14 @@ public function __construct(Spreadsheet $spreadsheet) /** * 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); // Open file - $this->openFileHandle($pFilename); + $this->openFileHandle($filename); // Write html fwrite($this->fileHandle, $this->generateHTMLAll()); @@ -551,20 +551,19 @@ public function generateNavigation() * Jpgraph code issuing warnings. So, don't measure * code coverage for this function till that is fixed. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param int $row Row to check for charts * * @return array * * @codeCoverageIgnore */ - private function extendRowsForCharts(Worksheet $pSheet, int $row) + private function extendRowsForCharts(Worksheet $worksheet, int $row) { $rowMax = $row; $colMax = 'A'; $anyfound = false; if ($this->includeCharts) { - foreach ($pSheet->getChartCollection() as $chart) { + foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $anyfound = true; $chartCoordinates = $chart->getTopLeftPosition(); @@ -583,11 +582,11 @@ private function extendRowsForCharts(Worksheet $pSheet, int $row) 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; $imageTL = Coordinate::coordinateFromString($drawing->getCoordinates()); $imageCol = Coordinate::columnIndexFromString($imageTL[0]); @@ -610,8 +609,8 @@ private function extendRowsForChartsAndImages(Worksheet $pSheet, int $row): stri while ($row <= $rowMax) { $html .= ''; for ($col = 'A'; $col != $colMax; ++$col) { - $htmlx = $this->writeImageInCell($pSheet, $col . $row); - $htmlx .= $this->includeCharts ? $this->writeChartInCell($pSheet, $col . $row) : ''; + $htmlx = $this->writeImageInCell($worksheet, $col . $row); + $htmlx .= $this->includeCharts ? $this->writeChartInCell($worksheet, $col . $row) : ''; if ($htmlx) { $html .= "$htmlx"; } else { @@ -645,18 +644,18 @@ public static function winFileToUrl($filename) /** * Generate image tag in cell. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet + * @param Worksheet $worksheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param string $coordinates Cell coordinates * * @return string */ - private function writeImageInCell(Worksheet $pSheet, $coordinates) + private function writeImageInCell(Worksheet $worksheet, $coordinates) { // Construct HTML $html = ''; // Write images - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { if ($drawing->getCoordinates() != $coordinates) { continue; } @@ -724,20 +723,15 @@ private function writeImageInCell(Worksheet $pSheet, $coordinates) * Jpgraph code issuing warnings. So, don't measure * code coverage for this function till that is fixed. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet - * @param string $coordinates Cell coordinates - * - * @return string - * * @codeCoverageIgnore */ - private function writeChartInCell(Worksheet $pSheet, $coordinates) + private function writeChartInCell(Worksheet $worksheet, string $coordinates): string { // Construct HTML $html = ''; // Write charts - foreach ($pSheet->getChartCollection() as $chart) { + foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $chartCoordinates = $chart->getTopLeftPosition(); if ($chartCoordinates['cell'] == $coordinates) { @@ -1117,13 +1111,13 @@ public function generateHTMLFooter() return $html; } - private function generateTableTagInline($pSheet, $id) + private function generateTableTagInline(Worksheet $worksheet, $id) { $style = isset($this->cssStyles['table']) ? $this->assembleCSS($this->cssStyles['table']) : ''; - $prntgrid = $pSheet->getPrintGridlines(); - $viewgrid = $this->isPdf ? $prntgrid : $pSheet->getShowGridlines(); + $prntgrid = $worksheet->getPrintGridlines(); + $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines(); if ($viewgrid && $prntgrid) { $html = " " . PHP_EOL; } elseif ($viewgrid) { @@ -1137,28 +1131,28 @@ private function generateTableTagInline($pSheet, $id) return $html; } - private function generateTableTag($pSheet, $id, &$html, $sheetIndex): void + private function generateTableTag(Worksheet $worksheet, $id, &$html, $sheetIndex): void { if (!$this->useInlineCss) { - $gridlines = $pSheet->getShowGridlines() ? ' gridlines' : ''; - $gridlinesp = $pSheet->getPrintGridlines() ? ' gridlinesp' : ''; + $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : ''; + $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : ''; $html .= "
    " . PHP_EOL; } else { - $html .= $this->generateTableTagInline($pSheet, $id); + $html .= $this->generateTableTagInline($worksheet, $id); } } /** * 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 * * @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 $html = ''; @@ -1169,10 +1163,10 @@ private function generateTableHeader($pSheet, $showid = true) $html .= "
    \n"; } - $this->generateTableTag($pSheet, $id, $html, $sheetIndex); + $this->generateTableTag($worksheet, $id, $html, $sheetIndex); // Write
    elements - $highestColumnIndex = Coordinate::columnIndexFromString($pSheet->getHighestColumn()) - 1; + $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1; $i = -1; while ($i++ < $highestColumnIndex) { if (!$this->useInlineCss) { @@ -1198,17 +1192,16 @@ private function generateTableFooter() /** * Generate row start. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param int $sheetIndex Sheet index (0-based) * @param int $pRow row number * * @return string */ - private function generateRowStart(Worksheet $pSheet, $sheetIndex, $pRow) + private function generateRowStart(Worksheet $worksheet, $sheetIndex, $pRow) { $html = ''; - if (count($pSheet->getBreaks()) > 0) { - $breaks = $pSheet->getBreaks(); + if (count($worksheet->getBreaks()) > 0) { + $breaks = $worksheet->getBreaks(); // check if a break is needed before this row if (isset($breaks['A' . $pRow])) { @@ -1219,7 +1212,7 @@ private function generateRowStart(Worksheet $pSheet, $sheetIndex, $pRow) } // open table again:
    + etc. - $html .= $this->generateTableHeader($pSheet, false); + $html .= $this->generateTableHeader($worksheet, false); $html .= '' . PHP_EOL; } } @@ -1237,9 +1230,9 @@ private function generateRowStart(Worksheet $pSheet, $sheetIndex, $pRow) 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); if (!$this->useInlineCss) { $cssClass = 'column' . $colNum; @@ -1296,39 +1289,43 @@ private function generateRowCellDataValueRich($cell, &$cellData): void } } - private function generateRowCellDataValue($pSheet, $cell, &$cellData): void + private function generateRowCellDataValue(Worksheet $worksheet, $cell, &$cellData): void { if ($cell->getValue() instanceof RichText) { $this->generateRowCellDataValueRich($cell, $cellData); } else { $origData = $this->preCalculateFormulas ? $cell->getCalculatedValue() : $cell->getValue(); - $cellData = NumberFormat::toFormattedString( - $origData, - $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(), - [$this, 'formatColor'] - ); + $formatCode = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(); + if ($formatCode !== null) { + $cellData = NumberFormat::toFormattedString( + $origData, + $formatCode, + [$this, 'formatColor'] + ); + } + if ($cellData === $origData) { $cellData = htmlspecialchars($cellData ?? '', Settings::htmlEntityFlags()); } - if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) { + if ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) { $cellData = '' . $cellData . ''; - } elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) { + } elseif ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) { $cellData = '' . $cellData . ''; } } } - private function generateRowCellData($pSheet, $cell, &$cssClass, $cellType) + private function generateRowCellData(Worksheet $worksheet, $cell, &$cssClass, $cellType) { $cellData = ' '; if ($cell instanceof Cell) { $cellData = ''; // Don't know what this does, and no test cases. //if ($cell->getParent() === null) { - // $cell->attach($pSheet); + // $cell->attach($worksheet); //} // 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   // Example: " Hello\n to the world" is converted to "  Hello\n to the world" @@ -1353,7 +1350,7 @@ private function generateRowCellData($pSheet, $cell, &$cssClass, $cellType) } // General horizontal alignment: Actual horizontal alignment depends on dataType - $sharedStyle = $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex()); + $sharedStyle = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex()); if ( $sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL && isset($this->cssStyles['.' . $cell->getDataType()]['text-align']) @@ -1371,9 +1368,9 @@ private function generateRowCellData($pSheet, $cell, &$cssClass, $cellType) 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) @@ -1384,12 +1381,12 @@ private function generateRowSpans($html, $rowSpan, $colSpan) 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? - $htmlx = $this->writeImageInCell($pSheet, $coordinate); + $htmlx = $this->writeImageInCell($worksheet, $coordinate); // Chart? - $htmlx .= $this->generateRowIncludeCharts($pSheet, $coordinate); + $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate); // Column start $html .= ' <' . $cellType; if (!$this->useInlineCss && !$this->isPdf) { @@ -1435,7 +1432,7 @@ private function generateRowWriteCell(&$html, $pSheet, $coordinate, $cellType, $ $html .= '>'; $html .= $htmlx; - $html .= $this->writeComment($pSheet, $coordinate); + $html .= $this->writeComment($worksheet, $coordinate); // Cell data $html .= $cellData; @@ -1447,44 +1444,43 @@ private function generateRowWriteCell(&$html, $pSheet, $coordinate, $cellType, $ /** * Generate row. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param array $pValues Array containing cells in a row * @param int $pRow Row number (0-based) * @param string $cellType eg: 'td' * * @return string */ - private function generateRow(Worksheet $pSheet, array $pValues, $pRow, $cellType) + private function generateRow(Worksheet $worksheet, array $pValues, $pRow, $cellType) { // Sheet index - $sheetIndex = $pSheet->getParent()->getIndex($pSheet); - $html = $this->generateRowStart($pSheet, $sheetIndex, $pRow); + $sheetIndex = $worksheet->getParent()->getIndex($worksheet); + $html = $this->generateRowStart($worksheet, $sheetIndex, $pRow); // Write cells $colNum = 0; foreach ($pValues as $cellAddress) { - [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($pSheet, $cellAddress, $pRow, $colNum); + [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $pRow, $colNum); $colSpan = 1; $rowSpan = 1; // Cell Data - $cellData = $this->generateRowCellData($pSheet, $cell, $cssClass, $cellType); + $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass, $cellType); // Hyperlink? - if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) { - $cellData = '' . $cellData . ''; + if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) { + $cellData = '' . $cellData . ''; } // 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]) - && $this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]); + $writeCell = !(isset($this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum]) + && $this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum]); // Colspan and Rowspan $colspan = 1; $rowspan = 1; - if (isset($this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) { - $spans = $this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]; + if (isset($this->isBaseCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum])) { + $spans = $this->isBaseCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum]; $rowSpan = $spans['rowspan']; $colSpan = $spans['colspan']; @@ -1492,13 +1488,13 @@ private function generateRow(Worksheet $pSheet, array $pValues, $pRow, $cellType // relies on !important for non-none border declarations in createCSSStyleBorder $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($pRow + $rowSpan); if (!$this->useInlineCss) { - $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex(); + $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex(); } } // Write 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 @@ -1770,12 +1766,12 @@ private function calculateSpansOmitRows($sheet, $sheetIndex, $candidateSpannedRo * * @return string */ - private function writeComment(Worksheet $pSheet, $coordinate) + private function writeComment(Worksheet $worksheet, $coordinate) { $result = ''; - if (!$this->isPdf && isset($pSheet->getComments()[$coordinate])) { + if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) { $sanitizer = new HTMLPurifier(); - $sanitizedString = $sanitizer->purify($pSheet->getComment($coordinate)->getText()->getPlainText()); + $sanitizedString = $sanitizer->purify($worksheet->getComment($coordinate)->getText()->getPlainText()); if ($sanitizedString !== '') { $result .= ''; $result .= '
    ' . nl2br($sanitizedString) . '
    '; @@ -1811,17 +1807,17 @@ private function generatePageDeclarations($generateSurroundingHTML) // Loop all sheets $sheetId = 0; - foreach ($sheets as $pSheet) { + foreach ($sheets as $worksheet) { $htmlPage .= "@page page$sheetId { "; - $left = StringHelper::formatNumber($pSheet->getPageMargins()->getLeft()) . 'in; '; + $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; '; $htmlPage .= 'margin-left: ' . $left; - $right = StringHelper::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; '; + $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; '; $htmlPage .= 'margin-right: ' . $right; - $top = StringHelper::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; '; + $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; '; $htmlPage .= 'margin-top: ' . $top; - $bottom = StringHelper::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; '; + $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; '; $htmlPage .= 'margin-bottom: ' . $bottom; - $orientation = $pSheet->getPageSetup()->getOrientation(); + $orientation = $worksheet->getPageSetup()->getOrientation(); if ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE) { $htmlPage .= 'size: landscape; '; } elseif ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_PORTRAIT) { diff --git a/src/PhpSpreadsheet/Writer/IWriter.php b/src/PhpSpreadsheet/Writer/IWriter.php index a0361f7421..b0a6272602 100644 --- a/src/PhpSpreadsheet/Writer/IWriter.php +++ b/src/PhpSpreadsheet/Writer/IWriter.php @@ -10,6 +10,8 @@ interface IWriter /** * IWriter constructor. + * + * @param Spreadsheet $spreadsheet The spreadsheet that we want to save using this Writer */ public function __construct(Spreadsheet $spreadsheet); @@ -27,11 +29,11 @@ public function getIncludeCharts(); * Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object. * Set to false (the default) to ignore charts. * - * @param bool $pValue + * @param bool $includeCharts * * @return IWriter */ - public function setIncludeCharts($pValue); + public function setIncludeCharts($includeCharts); /** * Get Pre-Calculate Formulas flag @@ -50,18 +52,18 @@ public function getPreCalculateFormulas(); * Set to true (the default) to advise the Writer to calculate all formulae on save * Set to false to prevent precalculation of formulae on save. * - * @param bool $pValue Pre-Calculate Formulas? + * @param bool $precalculateFormulas Pre-Calculate Formulas? * * @return IWriter */ - public function setPreCalculateFormulas($pValue); + public function setPreCalculateFormulas($precalculateFormulas); /** * 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? @@ -73,12 +75,12 @@ public function getUseDiskCaching(); /** * Set use disk caching where possible? * - * @param bool $pValue - * @param string $pDirectory Disk caching directory + * @param bool $useDiskCache + * @param string $cacheDirectory Disk caching directory * * @return IWriter */ - public function setUseDiskCaching($pValue, $pDirectory = null); + public function setUseDiskCaching($useDiskCache, $cacheDirectory = null); /** * Get disk caching directory. diff --git a/src/PhpSpreadsheet/Writer/Ods.php b/src/PhpSpreadsheet/Writer/Ods.php index 141a411950..decd82bcd3 100644 --- a/src/PhpSpreadsheet/Writer/Ods.php +++ b/src/PhpSpreadsheet/Writer/Ods.php @@ -113,9 +113,9 @@ public function getWriterPartThumbnails(): Thumbnails /** * 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) { throw new WriterException('PhpSpreadsheet object unassigned.'); @@ -126,7 +126,7 @@ public function save($pFilename, int $flags = 0): void // garbage collect $this->spreadSheet->garbageCollect(); - $this->openFileHandle($pFilename); + $this->openFileHandle($filename); $zip = $this->createZip(); diff --git a/src/PhpSpreadsheet/Writer/Pdf.php b/src/PhpSpreadsheet/Writer/Pdf.php index 36f3966d16..c419e1e26b 100644 --- a/src/PhpSpreadsheet/Writer/Pdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf.php @@ -165,13 +165,13 @@ public function getPaperSize() /** * Set Paper Size. * - * @param int $pValue Paper size see PageSetup::PAPERSIZE_* + * @param int $paperSize Paper size see PageSetup::PAPERSIZE_* * * @return self */ - public function setPaperSize($pValue) + public function setPaperSize($paperSize) { - $this->paperSize = $pValue; + $this->paperSize = $paperSize; return $this; } @@ -189,13 +189,13 @@ public function getOrientation() /** * Set Orientation. * - * @param string $pValue Page orientation see PageSetup::ORIENTATION_* + * @param string $orientation Page orientation see PageSetup::ORIENTATION_* * * @return self */ - public function setOrientation($pValue) + public function setOrientation($orientation) { - $this->orientation = $pValue; + $this->orientation = $orientation; return $this; } @@ -213,16 +213,16 @@ public function getTempDir() /** * Set temporary storage directory. * - * @param string $pValue Temporary storage directory + * @param string $temporaryDirectory Temporary storage directory * * @return self */ - public function setTempDir($pValue) + public function setTempDir($temporaryDirectory) { - if (is_dir($pValue)) { - $this->tempDir = $pValue; + if (is_dir($temporaryDirectory)) { + $this->tempDir = $temporaryDirectory; } else { - throw new WriterException("Directory does not exist: $pValue"); + throw new WriterException("Directory does not exist: $temporaryDirectory"); } return $this; @@ -231,14 +231,14 @@ public function setTempDir($pValue) /** * 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 */ - protected function prepareForSave($pFilename) + protected function prepareForSave($filename) { // Open file - $this->openFileHandle($pFilename); + $this->openFileHandle($filename); return $this->fileHandle; } diff --git a/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php b/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php index 313b34e805..e49c22c7ff 100644 --- a/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php @@ -20,11 +20,11 @@ protected function createExternalWriterInstance() /** * 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 $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) diff --git a/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php b/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php index 0db164b63e..8d0eda91a7 100644 --- a/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php @@ -22,11 +22,11 @@ protected function createExternalWriterInstance($config) /** * 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 $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) diff --git a/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php b/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php index 76f983a045..6ed16a5dd8 100644 --- a/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php @@ -36,11 +36,11 @@ protected function createExternalWriterInstance($orientation, $unit, $paperSize) /** * 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 $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) @@ -97,7 +97,7 @@ public function save($pFilename, int $flags = 0): void $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); // Write to file - fwrite($fileHandle, $pdf->output($pFilename, 'S')); + fwrite($fileHandle, $pdf->output($filename, 'S')); parent::restoreStateAfterSave(); } diff --git a/src/PhpSpreadsheet/Writer/Xls.php b/src/PhpSpreadsheet/Writer/Xls.php index fa7827551f..3a04a7492f 100644 --- a/src/PhpSpreadsheet/Writer/Xls.php +++ b/src/PhpSpreadsheet/Writer/Xls.php @@ -117,9 +117,9 @@ public function __construct(Spreadsheet $spreadsheet) /** * 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); @@ -224,7 +224,7 @@ public function save($pFilename, int $flags = 0): void $time = $this->spreadsheet->getProperties()->getModified(); $root = new Root($time, $time, $arrRootData); // save the OLE file - $this->openFileHandle($pFilename); + $this->openFileHandle($filename); $root->save($this->fileHandle); $this->maybeCloseFileHandle(); diff --git a/src/PhpSpreadsheet/Writer/Xls/Workbook.php b/src/PhpSpreadsheet/Writer/Xls/Workbook.php index a917185d89..6956a261be 100644 --- a/src/PhpSpreadsheet/Writer/Xls/Workbook.php +++ b/src/PhpSpreadsheet/Writer/Xls/Workbook.php @@ -600,7 +600,11 @@ private function writeAllDefinedNamesBiff8() } if ($definedName->getLocalOnly()) { - // local scope + /** + * local scope. + * + * @phpstan-ignore-next-line + */ $scope = $this->spreadsheet->getIndex($definedName->getScope()) + 1; } else { // global scope diff --git a/src/PhpSpreadsheet/Writer/Xlsx.php b/src/PhpSpreadsheet/Writer/Xlsx.php index 6f43989fd2..befc9cef25 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx.php +++ b/src/PhpSpreadsheet/Writer/Xlsx.php @@ -284,9 +284,9 @@ public function getWriterPartWorksheet(): Worksheet /** * 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); @@ -503,7 +503,7 @@ public function save($pFilename, int $flags = 0): void Functions::setReturnDateType($saveDateReturnType); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); - $this->openFileHandle($pFilename); + $this->openFileHandle($filename); $options = new Archive(); $options->setEnableZip64(false); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Chart.php b/src/PhpSpreadsheet/Writer/Xlsx/Chart.php index 56b890bbf0..8cefe4ccad 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Chart.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Chart.php @@ -75,7 +75,7 @@ public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $calcu $objWriter->writeAttribute('val', 0); $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()); @@ -202,7 +202,7 @@ private function writeLegend(XMLWriter $objWriter, ?Legend $legend = null): void * @param Axis $xAxis * @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) { return; diff --git a/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php b/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php index 53706bde59..1fef090146 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php @@ -98,14 +98,14 @@ private function writeDefinedName(DefinedName $pDefinedName): void /** * 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 - $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); - $this->objWriter->writeAttribute('localSheetId', "$pSheetId"); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); $this->objWriter->writeAttribute('hidden', '1'); // Create absolute coordinate and write as raw text @@ -118,7 +118,7 @@ private function writeNamedRangeForAutofilter(Worksheet $pSheet, int $pSheetId = $range[1] = Coordinate::absoluteCoordinate($range[1]); $range = implode(':', $range); - $this->objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle() ?? '') . '\'!' . $range); + $this->objWriter->writeRawData('\'' . str_replace("'", "''", $worksheet->getTitle() ?? '') . '\'!' . $range); $this->objWriter->endElement(); } @@ -127,33 +127,33 @@ private function writeNamedRangeForAutofilter(Worksheet $pSheet, int $pSheetId = /** * 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 - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles'); - $this->objWriter->writeAttribute('localSheetId', "$pSheetId"); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); // Setting string $settingString = ''; // Columns to repeat - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { - $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft(); + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $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 - if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + if ($worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { $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); @@ -165,22 +165,22 @@ private function writeNamedRangeForPrintTitles(Worksheet $pSheet, int $pSheetId /** * 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 - if ($pSheet->getPageSetup()->isPrintAreaSet()) { + if ($worksheet->getPageSetup()->isPrintAreaSet()) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Area'); - $this->objWriter->writeAttribute('localSheetId', "$pSheetId"); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); // Print area - $printArea = Coordinate::splitRange($pSheet->getPageSetup()->getPrintArea()); + $printArea = Coordinate::splitRange($worksheet->getPageSetup()->getPrintArea()); $chunks = []; foreach ($printArea as $printAreaRect) { $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); $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)); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php b/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php index b73d53cca6..755e04d359 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php @@ -14,12 +14,12 @@ class StringTable extends WriterPart /** * Create worksheet stringtable. * - * @param Worksheet $pSheet Worksheet - * @param string[] $pExistingTable Existing table to eventually merge with + * @param Worksheet $worksheet Worksheet + * @param string[] $existingTable Existing table to eventually merge with * * @return string[] String table for worksheet */ - public function createStringTable(Worksheet $pSheet, $pExistingTable = null) + public function createStringTable(Worksheet $worksheet, $existingTable = null) { // Create string lookup table $aStringTable = []; @@ -27,16 +27,16 @@ public function createStringTable(Worksheet $pSheet, $pExistingTable = null) $aFlippedStringTable = null; // For faster lookup // Is an existing table given? - if (($pExistingTable !== null) && is_array($pExistingTable)) { - $aStringTable = $pExistingTable; + if (($existingTable !== null) && is_array($existingTable)) { + $aStringTable = $existingTable; } // Fill index array $aFlippedStringTable = $this->flipStringTable($aStringTable); // Loop through cells - foreach ($pSheet->getCoordinates() as $coordinate) { - $cell = $pSheet->getCell($coordinate); + foreach ($worksheet->getCoordinates() as $coordinate) { + $cell = $worksheet->getCell($coordinate); $cellValue = $cell->getValue(); if ( !is_object($cellValue) && diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php b/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php index 0a20ea9d9f..20ca1aa4fd 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php @@ -201,22 +201,22 @@ private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet): vo * Write sheet. * * @param XMLWriter $objWriter XML Writer - * @param string $pSheetname Sheet name - * @param int $pSheetId Sheet id - * @param int $pRelId Relationship ID + * @param string $worksheetName Sheet name + * @param int $worksheetId Sheet id + * @param int $relId Relationship ID * @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 $objWriter->startElement('sheet'); - $objWriter->writeAttribute('name', $pSheetname); - $objWriter->writeAttribute('sheetId', $pSheetId); + $objWriter->writeAttribute('name', $worksheetName); + $objWriter->writeAttribute('sheetId', $worksheetId); if ($sheetState !== 'visible' && $sheetState != '') { $objWriter->writeAttribute('state', $sheetState); } - $objWriter->writeAttribute('r:id', 'rId' . $pRelId); + $objWriter->writeAttribute('r:id', 'rId' . $relId); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php b/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php index 98e2ae42b2..72b13fc5e4 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php @@ -26,7 +26,7 @@ class Worksheet extends WriterPart * * @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 $objWriter = null; @@ -53,76 +53,76 @@ public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = $objWriter->writeAttribute('xmlns:x14ac', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'); // sheetPr - $this->writeSheetPr($objWriter, $pSheet); + $this->writeSheetPr($objWriter, $worksheet); // Dimension - $this->writeDimension($objWriter, $pSheet); + $this->writeDimension($objWriter, $worksheet); // sheetViews - $this->writeSheetViews($objWriter, $pSheet); + $this->writeSheetViews($objWriter, $worksheet); // sheetFormatPr - $this->writeSheetFormatPr($objWriter, $pSheet); + $this->writeSheetFormatPr($objWriter, $worksheet); // cols - $this->writeCols($objWriter, $pSheet); + $this->writeCols($objWriter, $worksheet); // sheetData - $this->writeSheetData($objWriter, $pSheet, $pStringTable); + $this->writeSheetData($objWriter, $worksheet, $pStringTable); // sheetProtection - $this->writeSheetProtection($objWriter, $pSheet); + $this->writeSheetProtection($objWriter, $worksheet); // protectedRanges - $this->writeProtectedRanges($objWriter, $pSheet); + $this->writeProtectedRanges($objWriter, $worksheet); // autoFilter - $this->writeAutoFilter($objWriter, $pSheet); + $this->writeAutoFilter($objWriter, $worksheet); // mergeCells - $this->writeMergeCells($objWriter, $pSheet); + $this->writeMergeCells($objWriter, $worksheet); // conditionalFormatting - $this->writeConditionalFormatting($objWriter, $pSheet); + $this->writeConditionalFormatting($objWriter, $worksheet); - // dataValidations moved to end - //$this->writeDataValidations($objWriter, $pSheet); + // dataValidations + $this->writeDataValidations($objWriter, $worksheet); // hyperlinks - $this->writeHyperlinks($objWriter, $pSheet); + $this->writeHyperlinks($objWriter, $worksheet); // Print options - $this->writePrintOptions($objWriter, $pSheet); + $this->writePrintOptions($objWriter, $worksheet); // Page margins - $this->writePageMargins($objWriter, $pSheet); + $this->writePageMargins($objWriter, $worksheet); // Page setup - $this->writePageSetup($objWriter, $pSheet); + $this->writePageSetup($objWriter, $worksheet); // Header / footer - $this->writeHeaderFooter($objWriter, $pSheet); + $this->writeHeaderFooter($objWriter, $worksheet); // Breaks - $this->writeBreaks($objWriter, $pSheet); + $this->writeBreaks($objWriter, $worksheet); // Drawings and/or Charts - $this->writeDrawings($objWriter, $pSheet, $includeCharts); + $this->writeDrawings($objWriter, $worksheet, $includeCharts); // LegacyDrawing - $this->writeLegacyDrawing($objWriter, $pSheet); + $this->writeLegacyDrawing($objWriter, $worksheet); // LegacyDrawingHF - $this->writeLegacyDrawingHF($objWriter, $pSheet); + $this->writeLegacyDrawingHF($objWriter, $worksheet); // AlternateContent - $this->writeAlternateContent($objWriter, $pSheet); + $this->writeAlternateContent($objWriter, $worksheet); // ConditionalFormattingRuleExtensionList // (Must be inserted last. Not insert last, an Excel parse error will occur) - $this->writeExtLst($objWriter, $pSheet); + $this->writeExtLst($objWriter, $worksheet); // dataValidations - $this->writeDataValidations($objWriter, $pSheet); + $this->writeDataValidations($objWriter, $worksheet); $objWriter->endElement(); @@ -134,40 +134,40 @@ public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = * Write SheetPr. * * @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 $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 (!$pSheet->hasCodeName()) { - $pSheet->setCodeName($pSheet->getTitle()); + if (!$worksheet->hasCodeName()) { + $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)) { $objWriter->writeAttribute('filterMode', 1); - $pSheet->getAutoFilter()->showHideRows(); + $worksheet->getAutoFilter()->showHideRows(); } // tabColor - if ($pSheet->isTabColorSet()) { + if ($worksheet->isTabColorSet()) { $objWriter->startElement('tabColor'); - $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB()); + $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB()); $objWriter->endElement(); } // outlinePr $objWriter->startElement('outlinePr'); - $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0')); - $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0')); + $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0')); + $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0')); $objWriter->endElement(); // pageSetUpPr - if ($pSheet->getPageSetup()->getFitToPage()) { + if ($worksheet->getPageSetup()->getFitToPage()) { $objWriter->startElement('pageSetUpPr'); $objWriter->writeAttribute('fitToPage', '1'); $objWriter->endElement(); @@ -180,13 +180,12 @@ private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSh * Write Dimension. * * @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 $objWriter->startElement('dimension'); - $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension()); + $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension()); $objWriter->endElement(); } @@ -194,16 +193,15 @@ private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $p * Write SheetViews. * * @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 $objWriter->startElement('sheetViews'); // Sheet selected? $sheetSelected = false; - if ($this->getParentWriter()->getSpreadsheet()->getIndex($pSheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { + if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { $sheetSelected = true; } @@ -213,50 +211,50 @@ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $ $objWriter->writeAttribute('workbookViewId', '0'); // Zoom scales - if ($pSheet->getSheetView()->getZoomScale() != 100) { - $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); + if ($worksheet->getSheetView()->getZoomScale() != 100) { + $objWriter->writeAttribute('zoomScale', $worksheet->getSheetView()->getZoomScale()); } - if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { - $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); + if ($worksheet->getSheetView()->getZoomScaleNormal() != 100) { + $objWriter->writeAttribute('zoomScaleNormal', $worksheet->getSheetView()->getZoomScaleNormal()); } // 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); } // View Layout Type - if ($pSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { - $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); + if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { + $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView()); } // Gridlines - if ($pSheet->getShowGridlines()) { + if ($worksheet->getShowGridlines()) { $objWriter->writeAttribute('showGridLines', 'true'); } else { $objWriter->writeAttribute('showGridLines', 'false'); } // Row and column headers - if ($pSheet->getShowRowColHeaders()) { + if ($worksheet->getShowRowColHeaders()) { $objWriter->writeAttribute('showRowColHeaders', '1'); } else { $objWriter->writeAttribute('showRowColHeaders', '0'); } // Right-to-left - if ($pSheet->getRightToLeft()) { + if ($worksheet->getRightToLeft()) { $objWriter->writeAttribute('rightToLeft', 'true'); } - $topLeftCell = $pSheet->getTopLeftCell(); - $activeCell = $pSheet->getActiveCell(); - $sqref = $pSheet->getSelectedCells(); + $topLeftCell = $worksheet->getTopLeftCell(); + $activeCell = $worksheet->getActiveCell(); + $sqref = $worksheet->getSelectedCells(); // Pane $pane = ''; - if ($pSheet->getFreezePane()) { - [$xSplit, $ySplit] = Coordinate::coordinateFromString($pSheet->getFreezePane() ?? ''); + if ($worksheet->getFreezePane()) { + [$xSplit, $ySplit] = Coordinate::coordinateFromString($worksheet->getFreezePane() ?? ''); $xSplit = Coordinate::columnIndexFromString($xSplit); --$xSplit; --$ySplit; @@ -309,37 +307,36 @@ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $ * Write SheetFormatPr. * * @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 $objWriter->startElement('sheetFormatPr'); // Default row height - if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) { + if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) { $objWriter->writeAttribute('customHeight', 'true'); - $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($pSheet->getDefaultRowDimension()->getRowHeight())); + $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight())); } else { $objWriter->writeAttribute('defaultRowHeight', '14.4'); } // Set Zero Height row if ( - (string) $pSheet->getDefaultRowDimension()->getZeroHeight() === '1' || - strtolower((string) $pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true' + (string) $worksheet->getDefaultRowDimension()->getZeroHeight() === '1' || + strtolower((string) $worksheet->getDefaultRowDimension()->getZeroHeight()) == 'true' ) { $objWriter->writeAttribute('zeroHeight', '1'); } // Default column width - if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) { - $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($pSheet->getDefaultColumnDimension()->getWidth())); + if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) { + $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth())); } // Outline level - row $outlineLevelRow = 0; - foreach ($pSheet->getRowDimensions() as $dimension) { + foreach ($worksheet->getRowDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelRow) { $outlineLevelRow = $dimension->getOutlineLevel(); } @@ -348,7 +345,7 @@ private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorkshee // Outline level - column $outlineLevelCol = 0; - foreach ($pSheet->getColumnDimensions() as $dimension) { + foreach ($worksheet->getColumnDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelCol) { $outlineLevelCol = $dimension->getOutlineLevel(); } @@ -362,18 +359,18 @@ private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorkshee * Write Cols. * * @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 - if (count($pSheet->getColumnDimensions()) > 0) { + if (count($worksheet->getColumnDimensions()) > 0) { $objWriter->startElement('cols'); - $pSheet->calculateColumnWidths(); + $worksheet->calculateColumnWidths(); // Loop through column dimensions - foreach ($pSheet->getColumnDimensions() as $colDimension) { + foreach ($worksheet->getColumnDimensions() as $colDimension) { // col $objWriter->startElement('col'); $objWriter->writeAttribute('min', Coordinate::columnIndexFromString($colDimension->getColumnIndex())); @@ -398,7 +395,7 @@ private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet } // Custom width? - if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) { + if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) { $objWriter->writeAttribute('customWidth', 'true'); } @@ -426,14 +423,13 @@ private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet * Write SheetProtection. * * @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 $objWriter->startElement('sheetProtection'); - $protection = $pSheet->getProtection(); + $protection = $worksheet->getProtection(); if ($protection->getAlgorithm()) { $objWriter->writeAttribute('algorithmName', $protection->getAlgorithm()); @@ -613,15 +609,14 @@ private static function writeDataBarElements(XMLWriter $objWriter, $dataBar): vo * Write ConditionalFormatting. * * @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 $id = 1; // Loop through styles in the current worksheet - foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { foreach ($conditionalStyles as $conditional) { // WHY was this again? // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') { @@ -639,7 +634,7 @@ private function writeConditionalFormatting(XMLWriter $objWriter, Phpspreadsheet $objWriter, ($conditional->getConditionType() != Conditional::CONDITION_DATABAR), 'dxfId', - $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) + (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) ); $objWriter->writeAttribute('priority', $id++); @@ -680,12 +675,11 @@ private function writeConditionalFormatting(XMLWriter $objWriter, Phpspreadsheet * Write DataValidations. * * @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 - $dataValidationCollection = $pSheet->getDataValidationCollection(); + $dataValidationCollection = $worksheet->getDataValidationCollection(); // Write data validations? if (!empty($dataValidationCollection)) { @@ -757,12 +751,11 @@ private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksh * Write Hyperlinks. * * @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 - $hyperlinkCollection = $pSheet->getHyperlinkCollection(); + $hyperlinkCollection = $worksheet->getHyperlinkCollection(); // Relation ID $relationId = 1; @@ -798,16 +791,15 @@ private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $ * Write ProtectedRanges. * * @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 $objWriter->startElement('protectedRanges'); // Loop protectedRanges - foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { + foreach ($worksheet->getProtectedCells() as $protectedCell => $passwordHash) { // protectedRange $objWriter->startElement('protectedRange'); $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); @@ -826,16 +818,15 @@ private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksh * Write MergeCells. * * @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 $objWriter->startElement('mergeCells'); // Loop mergeCells - foreach ($pSheet->getMergeCells() as $mergeCell) { + foreach ($worksheet->getMergeCells() as $mergeCell) { // mergeCell $objWriter->startElement('mergeCell'); $objWriter->writeAttribute('ref', $mergeCell); @@ -850,21 +841,20 @@ private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $ * Write PrintOptions. * * @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 $objWriter->startElement('printOptions'); - $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true' : 'false')); + $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false')); $objWriter->writeAttribute('gridLinesSet', 'true'); - if ($pSheet->getPageSetup()->getHorizontalCentered()) { + if ($worksheet->getPageSetup()->getHorizontalCentered()) { $objWriter->writeAttribute('horizontalCentered', 'true'); } - if ($pSheet->getPageSetup()->getVerticalCentered()) { + if ($worksheet->getPageSetup()->getVerticalCentered()) { $objWriter->writeAttribute('verticalCentered', 'true'); } @@ -875,18 +865,17 @@ private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet * Write PageMargins. * * @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 $objWriter->startElement('pageMargins'); - $objWriter->writeAttribute('left', StringHelper::formatNumber($pSheet->getPageMargins()->getLeft())); - $objWriter->writeAttribute('right', StringHelper::formatNumber($pSheet->getPageMargins()->getRight())); - $objWriter->writeAttribute('top', StringHelper::formatNumber($pSheet->getPageMargins()->getTop())); - $objWriter->writeAttribute('bottom', StringHelper::formatNumber($pSheet->getPageMargins()->getBottom())); - $objWriter->writeAttribute('header', StringHelper::formatNumber($pSheet->getPageMargins()->getHeader())); - $objWriter->writeAttribute('footer', StringHelper::formatNumber($pSheet->getPageMargins()->getFooter())); + $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft())); + $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight())); + $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop())); + $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom())); + $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader())); + $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter())); $objWriter->endElement(); } @@ -894,11 +883,11 @@ private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet * Write AutoFilter. * * @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)) { // autoFilter $objWriter->startElement('autoFilter'); @@ -912,13 +901,13 @@ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $ $objWriter->writeAttribute('ref', str_replace('$', '', $range)); - $columns = $pSheet->getAutoFilter()->getColumns(); + $columns = $worksheet->getAutoFilter()->getColumns(); if (count($columns) > 0) { foreach ($columns as $columnID => $column) { $rules = $column->getRules(); if (count($rules) > 0) { $objWriter->startElement('filterColumn'); - $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); + $objWriter->writeAttribute('colId', $worksheet->getAutoFilter()->getColumnOffset($columnID)); $objWriter->startElement($column->getFilterType()); if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) { @@ -993,37 +982,37 @@ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $ * Write PageSetup. * * @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 $objWriter->startElement('pageSetup'); - $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize()); - $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation()); + $objWriter->writeAttribute('paperSize', $worksheet->getPageSetup()->getPaperSize()); + $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation()); - if ($pSheet->getPageSetup()->getScale() !== null) { - $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale()); + if ($worksheet->getPageSetup()->getScale() !== null) { + $objWriter->writeAttribute('scale', $worksheet->getPageSetup()->getScale()); } - if ($pSheet->getPageSetup()->getFitToHeight() !== null) { - $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight()); + if ($worksheet->getPageSetup()->getFitToHeight() !== null) { + $objWriter->writeAttribute('fitToHeight', $worksheet->getPageSetup()->getFitToHeight()); } else { $objWriter->writeAttribute('fitToHeight', '0'); } - if ($pSheet->getPageSetup()->getFitToWidth() !== null) { - $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth()); + if ($worksheet->getPageSetup()->getFitToWidth() !== null) { + $objWriter->writeAttribute('fitToWidth', $worksheet->getPageSetup()->getFitToWidth()); } else { $objWriter->writeAttribute('fitToWidth', '0'); } - if ($pSheet->getPageSetup()->getFirstPageNumber() !== null) { - $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber()); + if ($worksheet->getPageSetup()->getFirstPageNumber() !== null) { + $objWriter->writeAttribute('firstPageNumber', $worksheet->getPageSetup()->getFirstPageNumber()); $objWriter->writeAttribute('useFirstPageNumber', '1'); } - $objWriter->writeAttribute('pageOrder', $pSheet->getPageSetup()->getPageOrder()); + $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder()); - $getUnparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); - if (isset($getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId'])) { - $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId']); + $getUnparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) { + $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']); } $objWriter->endElement(); @@ -1033,23 +1022,23 @@ private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $p * Write Header / Footer. * * @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 $objWriter->startElement('headerFooter'); - $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); - $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); - $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); - $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); - - $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader()); - $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter()); - $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader()); - $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter()); - $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader()); - $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter()); + $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); + $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); + $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); + $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); + + $objWriter->writeElement('oddHeader', $worksheet->getHeaderFooter()->getOddHeader()); + $objWriter->writeElement('oddFooter', $worksheet->getHeaderFooter()->getOddFooter()); + $objWriter->writeElement('evenHeader', $worksheet->getHeaderFooter()->getEvenHeader()); + $objWriter->writeElement('evenFooter', $worksheet->getHeaderFooter()->getEvenFooter()); + $objWriter->writeElement('firstHeader', $worksheet->getHeaderFooter()->getFirstHeader()); + $objWriter->writeElement('firstFooter', $worksheet->getHeaderFooter()->getFirstFooter()); $objWriter->endElement(); } @@ -1057,14 +1046,14 @@ private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet * Write Breaks. * * @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 $aRowBreaks = []; $aColumnBreaks = []; - foreach ($pSheet->getBreaks() as $cell => $breakType) { + foreach ($worksheet->getBreaks() as $cell => $breakType) { if ($breakType == PhpspreadsheetWorksheet::BREAK_ROW) { $aRowBreaks[] = $cell; } elseif ($breakType == PhpspreadsheetWorksheet::BREAK_COLUMN) { @@ -1113,10 +1102,10 @@ private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pShe * Write SheetData. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet * @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 $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($pStringTable); @@ -1125,14 +1114,14 @@ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $p $objWriter->startElement('sheetData'); // Get column count - $colCount = Coordinate::columnIndexFromString($pSheet->getHighestColumn()); + $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn()); // Highest row number - $highestRow = $pSheet->getHighestRow(); + $highestRow = $worksheet->getHighestRow(); // Loop through cells $cellsByRow = []; - foreach ($pSheet->getCoordinates() as $coordinate) { + foreach ($worksheet->getCoordinates() as $coordinate) { $cellAddress = Coordinate::coordinateFromString($coordinate); $cellsByRow[$cellAddress[1]][] = $coordinate; } @@ -1140,7 +1129,7 @@ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $p $currentRow = 0; while ($currentRow++ < $highestRow) { // Get row dimension - $rowDimension = $pSheet->getRowDimension($currentRow); + $rowDimension = $worksheet->getRowDimension($currentRow); // Write current row? $writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null; @@ -1182,7 +1171,7 @@ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $p if (isset($cellsByRow[$currentRow])) { foreach ($cellsByRow[$currentRow] as $cellAddress) { // Write cell - $this->writeCell($objWriter, $pSheet, $cellAddress, $aFlippedStringTable); + $this->writeCell($objWriter, $worksheet, $cellAddress, $aFlippedStringTable); } } @@ -1298,14 +1287,14 @@ private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell * Write Cell. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet * @param string $pCellAddress Cell Address * @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 - $pCell = $pSheet->getCell($pCellAddress); + $pCell = $worksheet->getCell($pCellAddress); $objWriter->startElement('c'); $objWriter->writeAttribute('r', $pCellAddress); @@ -1353,15 +1342,15 @@ private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet * Write Drawings. * * @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 */ - private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, $includeCharts = false): void + private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, $includeCharts = false): void { - $unparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); - $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']); - $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0; - if ($chartCount == 0 && $pSheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { + $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']); + $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0; + if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { return; } @@ -1369,8 +1358,8 @@ private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pS $objWriter->startElement('drawing'); $rId = 'rId1'; - if (isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds'])) { - $drawingOriginalIds = $unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']; + if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { + $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; // take first. In future can be overriten // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships) $rId = reset($drawingOriginalIds); @@ -1384,12 +1373,12 @@ private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pS * Write LegacyDrawing. * * @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 (count($pSheet->getComments()) > 0) { + if (count($worksheet->getComments()) > 0) { $objWriter->startElement('legacyDrawing'); $objWriter->writeAttribute('r:id', 'rId_comments_vml1'); $objWriter->endElement(); @@ -1400,25 +1389,25 @@ private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorkshee * Write LegacyDrawingHF. * * @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 (count($pSheet->getHeaderFooter()->getImages()) > 0) { + if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $objWriter->startElement('legacyDrawingHF'); $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); $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; } - foreach ($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'] as $alternateContent) { + foreach ($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) { $objWriter->writeRaw($alternateContent); } } @@ -1429,13 +1418,14 @@ private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorks * * @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 = []; - foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { /** @var Conditional $conditional */ foreach ($conditionalStyles as $conditional) { $dataBar = $conditional->getDataBar(); + // @phpstan-ignore-next-line if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) { $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt(); } diff --git a/tests/PhpSpreadsheetTests/CommentTest.php b/tests/PhpSpreadsheetTests/CommentTest.php new file mode 100644 index 0000000000..f21efdf05e --- /dev/null +++ b/tests/PhpSpreadsheetTests/CommentTest.php @@ -0,0 +1,86 @@ +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); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousFilter.php b/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousFilter.php index 346a6558eb..eac37afc1a 100644 --- a/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousFilter.php +++ b/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousFilter.php @@ -55,7 +55,7 @@ public function filter0(int $row): bool return false; } - public function readCell($column, $row, $worksheetName = '') + public function readCell($columnAddress, $row, $worksheetName = '') { if ($this->filterType == 1) { return $this->filter1($row); diff --git a/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericFilter.php b/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericFilter.php index 0904e2d4a6..8d8fd62b40 100644 --- a/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericFilter.php +++ b/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericFilter.php @@ -7,7 +7,7 @@ /** Define a Read Filter class implementing IReadFilter */ class GnumericFilter implements IReadFilter { - public function readCell($column, $row, $worksheetName = '') + public function readCell($columnAddress, $row, $worksheetName = '') { return $row !== 4; } diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/OddColumnReadFilter.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/OddColumnReadFilter.php index 028f2fa32e..859e5b56b3 100644 --- a/tests/PhpSpreadsheetTests/Reader/Xlsx/OddColumnReadFilter.php +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/OddColumnReadFilter.php @@ -9,8 +9,8 @@ */ 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; } } diff --git a/tests/PhpSpreadsheetTests/Reader/Xml/XmlFilter.php b/tests/PhpSpreadsheetTests/Reader/Xml/XmlFilter.php index 1a20bb214d..b53fffd590 100644 --- a/tests/PhpSpreadsheetTests/Reader/Xml/XmlFilter.php +++ b/tests/PhpSpreadsheetTests/Reader/Xml/XmlFilter.php @@ -7,7 +7,7 @@ /** Define a Read Filter class implementing IReadFilter */ class XmlFilter implements IReadFilter { - public function readCell($column, $row, $worksheetName = '') + public function readCell($columnAddress, $row, $worksheetName = '') { return $row !== 4; } diff --git a/tests/PhpSpreadsheetTests/Style/ColorTest.php b/tests/PhpSpreadsheetTests/Style/ColorTest.php index 3a66192d83..9d0da3a233 100644 --- a/tests/PhpSpreadsheetTests/Style/ColorTest.php +++ b/tests/PhpSpreadsheetTests/Style/ColorTest.php @@ -7,6 +7,73 @@ 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 * @@ -21,7 +88,7 @@ public function testGetRed($expectedResult, $color, ...$args): void public function providerColorGetRed(): array { - return require 'tests/data/Style/ColorGetRed.php'; + return require 'tests/data/Style/Color/ColorGetRed.php'; } /** @@ -38,7 +105,7 @@ public function testGetGreen($expectedResult, $color, ...$args): void public function providerColorGetGreen(): array { - return require 'tests/data/Style/ColorGetGreen.php'; + return require 'tests/data/Style/Color/ColorGetGreen.php'; } /** @@ -55,7 +122,7 @@ public function testGetBlue($expectedResult, $color, ...$args): void public function providerColorGetBlue(): array { - return require 'tests/data/Style/ColorGetBlue.php'; + return require 'tests/data/Style/Color/ColorGetBlue.php'; } /** @@ -71,7 +138,7 @@ public function testChangeBrightness($expectedResult, ...$args): void public function providerColorChangeBrightness(): array { - return require 'tests/data/Style/ColorChangeBrightness.php'; + return require 'tests/data/Style/Color/ColorChangeBrightness.php'; } public function testDefaultColor(): void diff --git a/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php b/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php index dea4752281..d1353fa350 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php @@ -42,10 +42,10 @@ public function testBmp(): void $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); $creationDatestamp = $reloadedSpreadsheet->getProperties()->getCreated(); $filstart = $creationDatestamp; - $pSheet = $reloadedSpreadsheet->getActiveSheet(); - $drawings = $pSheet->getDrawingCollection(); + $worksheet = $reloadedSpreadsheet->getActiveSheet(); + $drawings = $worksheet->getDrawingCollection(); self::assertCount(1, $drawings); - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { // See if Scrutinizer approves this $mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing'; self::assertEquals('image/png', $mimeType); @@ -71,10 +71,10 @@ public function testGif(): void $drawing->setCoordinates('A1'); $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); - $pSheet = $reloadedSpreadsheet->getActiveSheet(); - $drawings = $pSheet->getDrawingCollection(); + $worksheet = $reloadedSpreadsheet->getActiveSheet(); + $drawings = $worksheet->getDrawingCollection(); self::assertCount(1, $drawings); - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { $mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing'; self::assertEquals('image/png', $mimeType); } diff --git a/tests/data/Style/ColorChangeBrightness.php b/tests/data/Style/Color/ColorChangeBrightness.php similarity index 100% rename from tests/data/Style/ColorChangeBrightness.php rename to tests/data/Style/Color/ColorChangeBrightness.php diff --git a/tests/data/Style/ColorGetBlue.php b/tests/data/Style/Color/ColorGetBlue.php similarity index 100% rename from tests/data/Style/ColorGetBlue.php rename to tests/data/Style/Color/ColorGetBlue.php diff --git a/tests/data/Style/ColorGetGreen.php b/tests/data/Style/Color/ColorGetGreen.php similarity index 100% rename from tests/data/Style/ColorGetGreen.php rename to tests/data/Style/Color/ColorGetGreen.php diff --git a/tests/data/Style/ColorGetRed.php b/tests/data/Style/Color/ColorGetRed.php similarity index 100% rename from tests/data/Style/ColorGetRed.php rename to tests/data/Style/Color/ColorGetRed.php