Commit Graph

830 Commits

Author SHA1 Message Date
Mark Baker d2473441c3
Merge branch 'master' into Issue-2551-Array-Ready-Function-Financial 2022-02-11 19:07:33 +01:00
MarkBaker c41dd0afae FIND(), SEARCH(), LEFT(), RIGHT, MID(), CLEAN(), TRIM(), TEXTJOIN() and REPT() functions 2022-02-11 18:56:21 +01:00
oleibman ad5532e2f4
Namespacing Phase 2 - Styles (#2471)
* WIP Namespacing Phase 2 - Styles

This is part 2 of a several-phase process to permit PhpSpreadsheet to handle input Xlsx files which use unexpected namespacing. The first phase, introduced as part of release 1.19.0, essentially handled the reading of data. This phase handles the reading of styles. More phases are planned.

It is my intention to leave this in draft status for at least a month. This will give time for additional testing, by me and, I hope, others who might be interested.

This fixes the same problem addressed by PR #2458, if it reaches mergeable status before I am ready to take this out of draft status. I do not anticipate any difficult merge conflicts if the other change is merged first.

This change is more difficult than I'd hoped. I can't get xpath to work properly with the namespaced style file, even though I don't have difficulties with others. Normally we expect:
```xml
<stylesheet xmlns="http://whatever" ...
```
In the namespaced files, we typically see:
```xml
<x:stylesheet xmlns:x="http://whatever" ...
```

Simplexml_load_file specifying a namespace handles the two situations the same, as expected. But, for some reason that I cannot figure out, there are significant differences when xpath processes the result. However, I can manipulate the xml if necessary; I'm not proud of doing that, and will gladly accept any suggestions. In the meantime, it seems to work.

My major non-standard unit test file had disabled any style-related tests when phase 1 was installed. These are now all enabled.

* Scrutinizer

Its analysis is wrong, but the "errors" it pointed out are easy to fix.

* Eliminate XML Source Manipulation

Original solution required XML manipulation to overcome what appears to be an xpath problem. This version replaces xpath with iteration, eliminating the need to manipulate the XML.

* Handle Some Edge Cases

For example, Style file without a Fills section.

* Restore RGB/ARGB Interchangeability

Fix #2494. Apparently EPPlus outputs fill colors as `<fgColor rgb="BFBFBF">` while most output fill colors as `<fgColor rgb="FFBFBFBF">`. EPPlus actually makes more sense. Regardless, validating length of rgb/argb is a recent development for PhpSpreadsheet, under the assumption that an incorrect length is a user error. This development invalidates that assumption, so restore the previous behavior.

In addition, a comment in Colors.php says that the supplied color is "the ARGB value for the colour, or named colour". However, although named colors are accepted, nothing sensible is done with them - they are passed unchanged to the ARGB value, where Excel treats them as black. The routine should either reject the named color, or convert it to the appropriate ARGB value. This change implements the latter.
2022-02-11 06:42:04 -08:00
MarkBaker c9886127c0 Style and phpstan cleanups 2022-02-11 13:55:52 +01:00
MarkBaker df12b06c59 Text function array value tests, plus some cleanup 2022-02-11 12:34:29 +01:00
MarkBaker 1e59b9113f Last of the work on array-enabling Date/Time functions; all completed in this category 2022-02-10 20:53:58 +01:00
MarkBaker ca81991728 phpcs cleanup 2022-02-10 15:40:30 +01:00
MarkBaker ec2ca1764f The `WORKDAY()` function accepts 2 "static" arguments that could be passed as arrays; but also accepts a set of trailing date arguments that are accepted as an array by the splat operator. Only the first two arguments should be tested for returning array values; but the logic still needs to work with the full argument set.
Provide a separate "subset" method in the `ArrayEnabled` Trait, that allows a subset of arguments to be tested for array returns.

Set up basic tests for `WORKDAY()`
2022-02-10 15:37:45 +01:00
MarkBaker 83ff74b97e Enable most of the Date/Time functions to accept array arguments 2022-02-10 15:37:45 +01:00
Mark Baker 291ea88a6c
Initial work enabling Excel function implementations for handling arrays as arguments when used in "array formulae". (#2562)
* Initial work enabling Excel function implementations for handling arrays as aguments when used in "array formulae".

So far:
 - handling for single argument functions
 - for functions where only one of the arguments is an array (a matrix or a row/column vector)
 - for when there are two array arguments, and one is a row vector, the other a column vector
 - for when there are either 2 row vectors, or 2 column vectors
 - for a matrix and either a row or column vector 

Will work ok, as long as there are no more than two array arguments; still need to identify the logic to apply when there are more than two arrays; or there are two that aren't an already supported row vector/column vector pairing (ie two matrices).

* Throw an exception if we have three or more array arguments (after flattening) passed to a supported function until we can identify the abstruse non-euclidian logic behind how Excel handles building, using and presenting those n-dimensional result arrays

* Implement array arguments for the DATE() function so that we can verify that paired arrays/vectors work with functions that support more than 2 arguments

* Implement array arguments for the many of the Math/Trig functions

* Update change log
2022-02-09 15:12:54 +01:00
Mark Baker d0965298d5
Additional unit tests for RANDARRAY() Math/Trig function implementation (#2563) 2022-02-07 10:19:19 +01:00
Mark Baker 6b746dc05f
Extract some methods from the Calculation Engine into dedicated classes (#2537)
* Move binary comparisons out into a dedicated class
2022-02-04 16:02:29 +01:00
Mark Baker ebeed87db5
Initial implementation of the MS Excel RANDARRAY() MathTrig function (#2540)
* Initial implementation of the MS Excel RANDARRAY() MathTrig function
Update Change Log

* Unit Tests for RANDARRAY()
2022-01-31 22:29:03 +01:00
Mark Baker 26079174a0
Implementation of the SEQUENCE() Excel365 function (#2536)
* Implementation of the SEQUENCE() Excel365 function

Note that the Calculation Engine does not yet support the Spill operator, or spilling functions

* Handle the use-case of step = 0; and tests for exception handling for invalid arguments

* Update Change Log
2022-01-29 14:32:40 +01:00
mix5003 e7b0497237
fix warning when open xlsx file with thumbnail (#2517) 2022-01-24 14:17:53 -08:00
oleibman b6bd822b9c
Xlsx Reader Merge Range For Entire Column(s) or Row(s) (#2504)
* Xlsx Reader Merge Range For Entire Column(s) or Row(s)

Fix #2501. Merge range can be supplied as entire rows or columns, e.g. `1:1` or `A:C`. PhpSpreadsheet is expecting a row and a column to be specified for both parts of the range, and fails when the unexpected format shows up.

The code to clear cells within the merge range is very inefficient in terms of both memory and time, especially when the range is large (e.g. for an entire row or column). More efficient code is substituted. It is possible that we can get even more efficient by deleting the cleared cells rather than setting them to null. However, that needs more research, and there is no reason to delay this fix while I am researching.

When Xlsx Writer encounters a null cell, it writes it to the output file. For cell merges (especially involving whole rows or columns), this results in a lot of useless output. It is changed to skip the output of null cells when (a) the cell style matches its row's style, or (b) the row style is not specified and the cell style matches its column's style.

* Scrutinizer

See if these changes appease it.

* Improved CellIterators

Finally figured out how to improve efficiency here, meaning that there is no longer a reason to change Writer/Xlsx, so restore that.

* No Change for CellIterator

I had thought a change was needed for CellIterator, but it isn't.
2022-01-23 10:44:09 -08:00
Mark Baker 4a04499bff
Read conditional styling for cell (#2491)
* Allow single-cell checks on conditional styles, even when the style is configured for a range of cells
* Work on the CellMatcher logic to evaluate Conditionals for a cell based on its value, and identify which conditional styles should be applied
* Refactor style merging and cell matching for conditional formatting into separate classes; this should make it easier to test, and easier to extend for other CF expressions subsequently
* Added support for containsErrors and notContainsErrors
* Initial work on a wizard to help simplify created Conditional Formatting rules, to ensure that the correct expressions are set
* Further work on extending the Conditional Formatting rules to cover more of the options that are available in MS Excel
* Prevent phpcs-fixer from removing class @method annotations, used to identify the signature for magic methods used in Wizard classes
* Implement `fromConditional()`` method to allow the creation of a CF Wizard from an existing Conditional
* Ensure that xlsx Reader picks up the timePeriod attribute for DatesOccurring CF Rules
* Allow Duplicates/Uniques CF Rules to be recognised in the Xlsx Reader
* Basic Xlsx reading of CF Rules/Styles from <extLst><ext><ConditinalFormattings> element, and not just the <ConditinalFormatting> element of the worksheet

* Add some validation for operands passed to the CF Wizards
 - remove any leading ``=` from formulae, because they'll be embedded into other formulae
 - unwrap any string literals from quotes, because that's also handled internally

Handle cross-worksheet cell references in cellReferences and Formulae/Expressions

* re-baseline phpstan

* Update Change Log with details of the CF Improvements
2022-01-22 19:18:26 +01:00
Igor dbaafba6c6
Fix loading drawing size (#2492) 2022-01-16 21:59:31 -08:00
oleibman 06ea9ead2b
Xlsx Reader Cell DataType Numeric or Boolean Without Value (#2489)
Fix #2488. When Excel sees this situation, it leaves the value of the cell as null rather than casting to the specified DataType. It doesn't really make sense to change setValueExplicit to adopt this convention; it should be sufficient to recognize the situation in the Reader and act there. The same sort of situation might apply to strings, but I don't see any practical difference between null string and null even if so.
2022-01-16 21:19:09 -08:00
oleibman 95d9cc965d
Refinement for XIRR (#2487)
* Refinement for XIRR

Fix #2469. The algorithm used for XIRR is known not to converge in some cases, some of which are because the value is legitimately unsolvable; for others, using a different guess might help.

The algorithm uses continual guesses at a rate to hopefully converge on the solution. The code in Python package xirr (https://github.com/tarioch/xirr/) suggests a refinement when this rate falls below -1. Adopting this refinement solves the problem for the data in issue 2469 without any adverse effect on the existing tests. My thanks to @tarioch for that refinement.

The data from 2469 is, of course, added to the test cases. The user also mentions that an initial guess equal to the actual result doesn't converge either. A test is also added to confirm that that case now works.

The test cases are changed to run in the context of a spreadsheet rather than by direct calls to XIRR calculation routine. This revealed some data validation errors which are also cleaned up with this PR. This suggests that other financial tests might benefit from the same change; I will look into that.

* More Unit Tests

From https://github.com/RayDeCampo/java-xirr/blob/master/src/test/java/org/decampo/xirr/XirrTest.java
https://github.com/tarioch/xirr/blob/master/tests/test_math.py

Note that there are some cases where the PHP tests do not converge, but the non-PHP tests do. I have confirmed in each of those cases that Excel does not converge, so the PhpSpreadsheet results are good, at least for now. The discrepancies are noted in comments in the test member.
2022-01-13 19:31:46 -08:00
oleibman 1509097e84
Recalibrate Row/Column Dimensions After removeRow/Col (#2486)
Fix #2442. Although data and styles are handled correctly after removing row(s) or column(s), the dimensions of the removed rows and columns remain behind to afflict their replacements. This PR will take care of removing the dimensions as well.

Dimensions has a _clone method for a deep clone, but all of its properties, as well as the properties of RowDimensions and ColumnDimensions, are scalars, and do not require a deep clone. The method is deleted.
2022-01-13 19:06:22 -08:00
oleibman 8ab834520d
Handle Explicit "Date" Type for Cell (#2485)
Fix #2373. Excel can handle DateTime/Date/Time as a string if the datatype of the cell is set to "d". The string is, apparently, supposed to follow the ISO8601 spec. Openpyxl can be configured to generate a file with such values, so I've added support and set up unit tests. Excel, naturally, converts such a string input into its numeric representation of the date/time stamp. So will PhpSpreadsheet, so a call to setValueExplicit specifying Date format will actually see the cell wind up with Numeric format - there is no way (and no reason) for the Date type to 'stick'.
2022-01-13 18:40:18 -08:00
Mark Baker b13b2a0d59
Allow single-cell checks on conditional styles, even when the style is configured for a range of cells (#2483)
* Allow single-cell checks on conditional styles, even when the style is configured for a range of cells
2022-01-05 13:39:50 +01:00
oleibman 7d71a7ca54
New Error Reported with Phpstan 1.3 (#2481)
* New Error Reported with Phpstan 1.3

Dependabot opened a number of PRs. Most are successful, but this change is necessary to allow PR #2477 to complete successfully, and that is apparently a necessity for PR #2479.

Phpstan 1.3 objected to:
```php
trigger_error($errorMessage, E_USER_ERROR);
return false;
```
It claims the return statement is unreachable. This isn't precisely true - an error handler might allow the return to be reached. At any rate, I have slightly restructured the code so that Phpstan will not object either with 1.2 or 1.3, which should allow the blocked PRs to succeed. There had been no previous tests for what happens when there is a formula error when suppressFormulaErrors is true.

* Scrutinizer

Didn't like effect of changes which Phpstan liked. Hopefully this will work better.

* Improvement

Eliminate added function.
2022-01-03 17:32:52 -08:00
oleibman f24dcc7911
Another Undefined Index in Xls Reader (#2470)
Fix #2463. These continue to dribble in regularly.
2021-12-31 13:43:59 -08:00
oleibman 5d1ab39def
Replace Tests With Unneeded Mocking (#2465)
Replace mock tests with real ones when possible. The original tests are all still present; they just take place in a more representative scenario.

After this, there will be 4 remaining uses of mocking. Of these, 3 are needed for scenarios which are otherwise hard to test - WebServiceTest, CellsTest, and SampleCoverageTest. For the other one, AutoFilterTest, I just can't figure out what it's trying to accomplish, so have left it alone.

This change is almost entirely restricted to tests. There is a one-line change in src. When the first argument passed to OFFSET is null or nullstring, the returned value is currently 0. However, according to the documentation for Excel, it should be `#VALUE!`. The code is changed accordingly.
2021-12-31 13:24:43 -08:00
oleibman 07271c83aa
Rename Two Test Files (#2459)
* Rename Two Test Files

When I run unit tests only for Reader/Xlsx, phpunit is issuing a deprecation message because the names of 2 files have an extra dot in them and thus don't match the class name in the file. I do not see these warnings when I run the entire test suite.

* Remove Phpstan Annotations

It was a bit difficult to handle a cast from mixed to string.

* Fix Same Phpstan Problem in One Other Test

This is the only other test case that tries to cast mixed to string.
2021-12-25 09:05:54 -08:00
oleibman f2b2f07ec3
Null Passed to AutoFilter SetRange (#2454)
* Null Passed to AutoFilter SetRange

Fix #2281. Delete auto filter set range to null, but should set it to null string. This causes a deprecation warning in Php8.1.

* Constructor Call Also Sets Range to Null

Should set it to null string.
2021-12-25 08:45:10 -08:00
oleibman 3a6558625d
General Style Specified in Uppercase in Input Xlsx (#2451)
* General Style Specified in Uppercase in Input Xlsx

Fix #2450. Treat input style GENERAL as if it were expected upper/lowercase.

* Declare Method as Static

Surprised neither Phpstan nor Scrutinizer flagged this.

* Remove Duplicated Statement

Don't know why Scrutinizer didn't flag this the first time.
2021-12-18 09:25:08 -08:00
oleibman 67bf45d700
Fill Pattern Start and End Colors (#2444)
* Fill Pattern Start and End Colors

Fix #2441. The Fill constructor sets start color to white and end color to black and the Xlsx writer writes these values to the output file. This appears to be the wrong setting for all 7 LIGHT* pattern types, 2 of the 7 DARK* patterns (DARKGRAY and DARKTRELLIS), and 1 of the 3 GRAY patterns (GRAY0625). When the wrong colors are written at save time, those patterns are not as expected. Xls writer does not appear to have the same problem.

The XML does not require either a start or end color, and the omission of these colors in the file being read was responsible for the problem. The code is changed to mimic that behavior by omitting the color tags at write time if they have not changed from when they were created by the Fill constructor (they will be written for gradient or solid patterns regardless).

This is another change which is easier to confirm via samples rather than tests. There are separate samples for Xlsx and Xls; as Excel will be quick to warn you, Xls is not as fully functional as Xlsx with respect to fill patterns. The samples do include a cell where one of the cells (LightGrid in C11) explicitly specifies the "default" colors.

* Scrutinizer

It somehow ascribed to me a problem in code which was unchanged by this PR. Correct it anyhow, along with some Phpstan fixes (errors now ignored because of change).

* Added Tests

Also corrected some docBlock problems with Style/*/parent and getSharedComponent.

* Create 2 Abstract Methods

Scrutinizer complained that 2 methods found in all Supervisor sub-types were not defined in Supervisor. Add abstract methods to satisfy it.

* Scrutinizer Ignoring Typehints

Try this instead.

* Slight Improvement

Better handling of Style->getParent().
2021-12-18 08:53:23 -08:00
leo-bsv a7f687fe5c
Xlsx image background in comments #1547 (#2422)
* XLSX Image background in comments

* XLSX-Image-Background-In-Comments (#1547)

* Test fixes, convertion for comment sizes from px to pt, fix for setting image sizes from zip, set image type

* Merge remote-tracking branch 'origin/XLSX-Image-Background-In-Comments' into XLSX-Image-Background-In-Comments

* Tests to check reloaded document.

Co-authored-by: Burkov Sergey
2021-12-17 06:10:59 -08:00
oleibman ea74c96e98
Name Clashes Between Parsed and Unparsed Drawings (#2423)
* Name Clashes Between Parsed and Unparsed Drawings

This is at least a partial fix for #2396 and #1767 (which has been around for a long time). PhpSpreadsheet renames drawing XML files when it reads them from a spreadsheet. However, when it writes unparsed drawing files, it uses the original names, which can result in a clash with the renamed files. The solution in this PR is to write the unparsed files using the same renaming convention as the the others.

This is an incredibly simple fix, basically a one-line change, for such a long-lived problem. It is conceivable that this PR breaks a more sophisticated file than I have come across, e.g. with multiple unparsed files associated with a single worksheet. However, this PR does fix at least part of the problem for both issues, and causes no regression issues. The changed code was covered in only 2 tests - Reader/XlsxTest testLoadSaveWithEmptyDrawings and Writer/Xlsx/UnparsedDataTest testLoadSaveXlsxWithUnparsedData.

2396 is covered by a new test Unparsed2396Test. I had trouble figuring out what to test for 1767. Since it is a problem that becomes evident only when the output file is opened in Excel, I added a new sample to cover it.

* Sloppy Errors

I neglected to run php-cs-fixer and phpstan, and it bit me.

* Scrutinizer

It's not as good as Phpstan at recognizing problems that can't happen due to previous assertions.

* Scrutinizer Again

It can be really stupid sometimes.
2021-12-09 23:37:15 -08:00
oleibman 9c8eeef96d
Xlsx Writer Unhides Explicitly Hidden Row in Filter Range - Minor Breaking Change (#2414)
Fix #1641. Excel allows explicit hiding of row after filter is applied, but PhpSpreadsheet automatically invokes showHideRows on all auto-filters, preventing users from doing the same. Change to invoke showHideRows only if it hasn't already been invoked, or if filter criteria have changed since it was last invoked. Autofilters read in from an existing spreadsheet are assumed to be already invoked.

This is potentially a breaking change, probably a minor one. The conditions to set up 1641 are probably uncommon, but users who meet those conditions and are happy with the current behavior will see a break. The new behavior is closer to how Excel itself behaves. A new method `reevaluateAutoFilters` is added to `Spreadsheet`; this can be used to restore the old behavior if desired. The new method is added to the documentation, along with a description of how the situation described in 1641 is handled in Excel and PhpSpreadsheet.

While examining Excel's behavior, it became evident that, although a filter is applied to an entire column, it is actually applied only to the rows that are populated when the filter is defined, as can be verified by examining the XML definition of the filter. When you re-apply the filter, rows that have been added since are considered. It would be useful to provide PhpSpreadsheet with a method to do the same. I have added, and documented, `setRangeToMaxRow` to `AutoFilter`.
2021-12-05 07:26:24 -08:00
Michael Fürnschuß aa91abc0d8
Respect DataType in insertNewBefore (#2433)
`ReferenceHelper::insertNewBefore` copies data from one cell to another when adding/removing rows or columns.
It now also respects the data type set for that cell and does not use value binder again.
2021-12-04 08:31:38 -08:00
oleibman 580c741c8e
Improve PDF Support for Page Size and Orientation (#2410)
Fix #1691. PhpSpreadsheet allows the setting of different page size and orientation on each worksheet. It also allows the setting of page size and orientation on the PDF writer. It isn't clear which is supposed to prevail when the two are in conflict. In the cited issue, the user expects the PDF writer setting to prevail, and I tend to agree. Code is changed to do this, and handling things in this manner is now explicitly documented.

PhpSpreadsheet uses a default paper size of Letter, and a default orientation of Default (which Excel treats as Portrait). New static routines are added to change the default for sheets created subsequent to such calls. This could allow users to configure these defaults better for their environments. The new functions are added to the documentation.
2021-12-01 23:00:02 -08:00
oleibman d5825a6682
Read Spreadsheet with # in Name (#2409)
Fix #2405. Treat last, rather than first, `#` as separator between zip file name and member name, by finding it with strrpos rather than strpos.
2021-11-30 07:39:50 -08:00
oleibman 290c18e4db
Xlsx Reader Theme Support Broken After 17.1 (#2403)
Fix #2387. Fix #2075. There was substantial refactoring of Writer Xlsx styles in 18.0. An existing static property `$theme` was intended to be shared by both Writer Xlsx and the new Writer Xlsx Styles. However, the initialization of the property in the latter happened later than it should have. This PR makes that initialization happen as soon as the theme has been read. Also, declaring that property as static seems questionable; I have made it an instance member. This small re-factoring makes it possible to now support Themes in tab colors.

Since this PR changes Reader/Xlsx/Styles, add type-hinting throughout that module to eliminate Phpstan/Scrutinizer problems. I also removed method readStyle from Reader/Xlsx, since it was essentially duplicated in Reader/Xlsx/Styles. And I added a small number of tests to ensure that Styles is 100% covered. All of this is necessary in preparation for Namespacing phase 2.
2021-11-26 09:38:09 -08:00
oleibman 3257ae5c90
Rounding in NumberFormatter (#2399)
Fix #2385. NumberFormatter is using sprintf on a float, and is seeing inconsistent rounding as a result (it will also occasionally result in `-0`). Change to round the number before presenting it to sprintf.
2021-11-26 09:05:35 -08:00
Tiago Malheiro 0c93bbaaa3 Don't corrupt file when using chart with fill color
When the fill color property of `DataSeries.plotLabel` using a
DataSeriesValues on a line chart is set, the XLSX file written
is corrupted, and MSExcel2016 removes the drawing1.xml if forced open.

This problem was already documented on issue #589 along with a possible
solution. So all credits go to @madrussa. I am only submitting the PR.

Fixes #589
Closes #1930
2021-11-23 23:34:48 +09:00
oleibman b67404229a
Allow Skipping One Unit Test (#2402)
* Allow Skipping One Unit Test

Alone in the test suite, URLImageTest needs to access the internet. It's a little fragile (the site that it's looking for may go away or change), but no real problem. However, on my system, it runs afoul of my proxy. Rather than jumping through hoops when I run the test suite (which happens very often), I am changing the test to skip if an environment variable is set to a specific value. This should not adversely affect anyone, and the test will still run in github, but it will help me a lot.

* Scrutinizer

It complained that my one new if statement made the module too complex. There actually were a number of if-then-else situations that could be handled just as well with assertions. I have changed it accordingly.
2021-11-19 14:24:42 -08:00
oleibman 2a12587f05
AutoFilter Improvements (#2393)
* AutoFilter Improvements

Fix issue #2378. The following changes are made:
- NotEqual tests must be part of a custom filter. Documentation has been changed to indicate that.
- Method setAndOr was replaced by setJoin some time ago. Documentation now reflects that change.
- Documentation to indicate that string filters are not case-sensitive, same as in Excel.
- Filters testing against numeric value now include a numeric test (not numeric for not equal, numeric for all others).
- String filter had previously treated everything as a test for "equal". It now handles "not equal" and the variants of "greater/less" with or without "equal".
- Documentation correctly stated that no more than 2 rules are allowed in a custom filter. Code did not enforce this restriction. It now does, throwing an exception if an attempt is made to add a third rule.
- Deleted a lot of comments in Rule.php to make it easier to see what is not yet implemented (between, begins with, etc.). I may take these on in future.
- Added a number of tests for the new functionality.

* Not Sure Why Phpstan Results Differ Local vs Github

Let's see if this change suffices.

* Phpstan Still

Not sure how to convince it. Let's try this.

* Phpstan Solved

Figured out the problem on my local machine. Expect this to work.
2021-11-16 07:46:07 -08:00
oleibman 52585a9d7c
Hyperlinks and Namespacing (#2391)
Fix #2389. Hyperlinks referring to cells in the spreadsheet itself are not being handled properly. This is the first namespacing regression identified for release 19. Usual cause and fix - need to take greater care with attributes than was previously the case.
2021-11-14 10:27:59 -08:00
oleibman 4ac0c47ac7
Support Data Validations in More Versions of Excel (#2377)
* Support Data Validations in More Versions of Excel

Attempt to deal with #2368, this time for good. Some deleted code was accidentally restored just before release 19, causing errors in spreadsheets with Data Validations. PR #2369 removed the duplicated code, and the fix was confirmed in current versions of Excel for Windows, Google sheets, and other versions of Excel. However, there were problems reported in earlier version of Excel for Windows, and some, versions of Excel for Mac, not all but including a recent one. This change, which is simpler than the original (no need for extLst) fix for DataValidations, is tested with Excel 2007 and Excel 2003 as well as more recent versions. I do not have a Mac on which to test.

* Multiple Identical Data Validation Lists

Using the same Data Validation List in multiple places on a worksheet caused them all to be merged into the same range. This was because sqref was not part of the hash code; it is now, avoiding this problem.

* Must Write Data Validations Before Hyperlinks

See discussion in #2389.
2021-11-14 10:06:46 -08:00
oleibman f831f48b71
ZipArchive and "Inconsistent" Zip File (#2376)
* ZipArchive and "Inconsistent" Zip File

Fix #2362. I added test for zip file inconsistency when dealing with a particularly nasty PHP/libzip bug affecting zero-length files. However, we also now verify that the file starts with a valid zip signature, so the consistency test is not really needed, and, from what I've read on the web, isn't particularly useful. The file with a problem, for example, opens just fine with Excel and zip, despite Php reporting it as inconsistent (when asked to check consistency). So, remove the consistency check.

* Update Issue2362Test.php

Latest Phpstan does not allow cast from 'mixed' to 'string'.

* Update Issue2362Test.php
2021-11-12 01:18:57 -08:00
oleibman 2f1f3a19b8
Csv, Boolean, and StringValueBinder (#2374)
See the discussion in PR #2232 which came about 3 months after it was merged. It caused a problem in an unusual situation which did not come to light until the change was part of the new release version. The original PR changed PhpSpreadsheet's behavior to match Excel's for (not case sensitive) strings `TRUE` and `FALSE`. Excel treats the values as boolean, and now so does PhpSpreadsheet.

When StringValueBinder is used, this becomes a tricky situation. The user wants the original strings preserved, including the case of all the letters. This PR changes the behavior of CSV reader as follows:
- If StringValueBinder is not in effect, convert to boolean.
- If StringValueBinder (actually any binder with method getBooleanConversion) is in effect, and the result of getBooleanConversion is true (which is the default in StringValueBinder), leave the value coming out of Csv Reader as the unchanged string.
- Otherwise, convert to boolean.

This should mean that there are no regression problems with StringValueBinder, while allowing PhpSpreadsheet to continue to match Excel in the default situation. No new settings are required.
2021-11-12 00:04:08 -08:00
oleibman ffdae8efac
Update Some Doc Block Annotations (#2351)
* Update Some Doc Block Annotations

See PR #2010. That PR was never completed, and has gone stale. However, it was correct in identifying a situation where the doc block was not entirely accurate. It did not go far enough - several closely-related methods have similar problems. This PR attempts to fix the original problem and its close relations. Aside from the doc block changes, there are very minor changes to executable code. It also changes some of the unit tests targeted at the methods in question to eliminate mocking in favor of 'real' tests.

* Change Method to Static

Otherwise Scrutinizer will complain, even though Phpstan doesn't.

* Scrutinizer

Various clean-up activities.

* Scrutinizer

@#&$(*#&$ Got complexity down from 53 to (I think) 50. Don't really know what the target is.

* Code Changes Suggested By Review

Some improvements suggested in review by @PowerKiKi.

* Update Cells.php

* Merge Conflict

A change to a parameter name caused several problems when trying to fix it on Github. Fixing it locally should do the trick.

* Merge Conflicts in Phpstan Baseline

PR #2382 made a large number of changes to Phpstan Baseline, some of which conflicted with the Phpstan Baseline changes in this PR. This should resolve them all.
2021-11-11 23:38:05 -08:00
oleibman f59b4dc363
Eliminate Mocking from Row/Column/Cell Iterator Tests (#2352)
Mocking is not needed for these tests.

Co-authored-by: Adrien Crivelli <adrien.crivelli@gmail.com>
2021-11-01 13:50:42 +09:00
oleibman 26c26ae8df
Xlsx Writer Support for WMF Files (#2339)
PR #1844 fixes it, but changes were requested. It has been almost 3 months and those changes have not been made. This PR replaces that one; it should be suitable for all supported releases of PHP through 8.1, and includes a formal unit test.

Fixes #1685
Closes #1844
2021-11-01 13:28:51 +09:00
Adrien Crivelli 69f633420b
Merge branch 'master' into PHP8-Sane-Property-Names 2021-10-31 15:25:01 +09:00
Einar 7635b3f91a
Optimize applyFromArray by caching existing styles (#1785)
Prevent calling clone and getHashCode when not needed
because these calls are very expensive.

When applying styles to a range of cells can we cache the
styles we encounter along the way so we don't need to look
them up with getHashCode later.
2021-10-31 00:55:00 +09:00
Adrien Crivelli e550528c02
Lock our deps with our minimum PHP 7.2, instead of PHP 7.3 2021-10-30 12:54:26 +09:00
oleibman 241e82b284
Unexpected Format in Timestamp (#2332)
See issue #2331. Timestamp is expected in format yyyy-mm-dd (plus other information), with the expectation that month and day are 2 digits zero-filled on the left if needed. The user's file instead used a space rather than zero as filler. Although I don't know how the unexpected timestamp was created, it was easy enough to alter the timestamp in an otherwise normal spreadsheet, and use that file as a test case.
2021-10-23 18:23:53 -07:00
oleibman 3db0b2a2de
Corrections for HLOOKUP Function (#2330)
See issue #2123. HLOOKUP needs to do some conversions between column numbers and letters which it had not been doing.

HLOOKUP tests were performed using direct calls to the function in question rather than in the context of a spreadsheet. This contributed to keeping this error obscured even though there were, in theory, sufficient test cases. The tests are changed to perform in spreadsheet context. For the most part, the test cases are unchanged. One of the expected results was wrong; it has been changed, and a new case added to cover the case it was supposed to be testing.

After getting the HLOOKUP tests in order, it turned out that a test using literal arrays which had been succeeding now failed. The array constructed by the literals are considerably different than those constructed using spreadsheet cells; additional code was added to handle this situation.
2021-10-23 17:59:42 -07:00
oleibman 9512f54cca
Corrections for Xlsx Read Comments (#2329)
This change was suggested by issue #2316. There was a problem reading Xlsx comments which appeared with release 18.0 but which was already fixed in master. So no source change was needed to fix the issue, but I thought we should at least add the test case to our unit tests.

In developing that case, I discovered that, although comment text was read correctly, there was a problem with comment author. In fact, there were two problems. One was new, with the namespacing changes - as in several other cases, the namespaced attribute `authorId` needed some special handling. However, another problem was much older - the code was checking `!empty($comment['authorId'])`, eliminating consideration of authorId=0, and should instead have been checking `isset`. Both problems are now fixed, and tested.
2021-10-23 17:32:44 -07:00
oleibman cb8ee73355
Cache Results for Tests Involving NOW and TODAY Functions (#2311)
My bulletproofing of these tests was not yet sufficient. Although I have never had a failure in probably thousands of tests, one user submitted a PR which did fail testing NOW, fortunately not in a test that is required to pass. The problem is that it is not sufficient merely to set the cell value inside a do-while loop; it is necessary to calculate it in order to cache its result so that results based on that cell will be internally consistent.

No source code is changed for this PR, just some tests.
2021-10-03 11:06:47 -07:00
oleibman 4001c89aaa
isFormula Referencing Sheet With Space in Title (#2306)
* isFormula Referencing Sheet With Space in Title

See issue #2304. User sets a cell to `ISFORMULA(cell)`, where `cell` exists on a sheet whose title contains a space, and receives an error. Coordinates are not being passed correctly to Functions::isFormula; in particular, the sheet name is not enclosed in apostrophes, e.g. `Sheet Name!A1` rather than `'Sheet Name'!A1`. (Note that sheet name was not specified in Cell; PhpSpreadsheet adds it before calling isFormula.) Sheets without embedded spaces (or other non-word characters) are handled correctly with or without apostrophes, but spaces require surrounding apostrophes.

As part of this investigation, I determined that Excel handles defined names and cell ranges in ISFORMULA (subject to spills), and that PhpSpreadsheet does not. It is changed to handle them. In the absence of spill support, it will use only the first cell in the range.

Existing tests for ISFORMULA used mocking unneccesarily. They are moved to a separate test member, and mocking is no longer used.

* PhpUnit and Jpgraph

35_Char_render.php had previously been a problem only for PHP8+. It is now a problem for PHP7.4, and will therefore be skipped all the time.
2021-10-03 10:04:48 -07:00
Georgiy fea0e34e90
fix #1114 issue (#2308)
* fix #1114 issues

* fixed code style

* update for all version

* add test for bag 1114

* remove comment

Co-authored-by: georgio <georgiokot@gmail.cim>
2021-10-03 09:29:23 -07:00
oleibman 90b9decb8e
Xlsx Reader Better Namespace Handling Phase 1 Second Bugfix (#2303)
* Xlsx Reader Better Namespace Handling Phase 1 Second Bugfix

See issue #2301. The main problem in that issue had been introduced with 18.0 and had already ben fixed in master. However there was a subsequent problem that had been introduced in master, an undotted i uncrossed t with namespace handling. When using namespaces, need to call attributes() to access the attributes before trying to access them directly. Failure to do so in parseRichText caused fonts declared in Rich Text elements to be ignored.

* Add An Assertion

Addresses problem in 2301 that had already been fixed.
2021-09-27 16:59:45 -07:00
oleibman f2cd62a9ef
PhpUnit and Jpgraph (#2307)
35_Char_render.php had previously been a problem only for PHP8+. It is now a problem for PHP7.4, and will therefore be skipped all the time.
2021-09-26 09:39:15 -07:00
oleibman cc14a48604
Permit CSV Delimiter to be Set to Null (#2288)
* Permit CSV Delimiter to be Set to Null

See issue #2287. A 1-character change. The delimiter variable is defined as nullable, and getDelimiter can return null; setDelimiter should follow suit.

* Scrutinizer Inanity

Are you sure the test always returns null?????
Yes, I'm sure, that's why it's part of the test.
Let's see if we can recode it and miss this "problem".
2021-09-15 12:40:03 -07:00
oleibman 4dd5c06c7b
Deleting Sheet with Local Defined Name (#2284)
Fixes issue #2266. Writer/Xlsx fails when there is no longer a sheet which corresponds to the definition of a local defined name. The code is changed to drop such an orphaned name. Writer/Xls does not fail under the same cicrcumstances, so no correction is needed there. Writer/Ods fails in a different manner, and is corrected to no longer do so.
2021-09-15 12:14:13 -07:00
oleibman e02eab29f1
Validate Input to SetSelectedCells (#2280)
* Validate Input to SetSelectedCells

See issue #2279. User requests an enhancement so that you can set a Style on a Named Range. The attempt is failing because setting the style causes a call to setSelectedCells, which does not account for Named Ranges. Although not related to the issue, it is worth noting that setSelectedCells does nothing to attempt to validate its input.

The request seems reasonable, even if it is probably more than Excel itself offers. I have added code to setSelectedCells to recognize Named Ranges (if and only if they are defined on the sheet in question). It will throw an exception if the string passed as coordinates cannot be parsed as a range of cells or an appropriate Named Range, e.e.g. a Named Range on a different sheet, a non-existent named range, named formulas, formulas, use of sheet name qualifiers (even for the same sheet). Tests are, of course, added for all of those and for the original issue. The code in setSelectedCells is tested in a very large number of cases in the test suite, none of which showed any problems after this change.

* Scrutinizer

2 minor (non-fatal) corrections, including 1 where Phpstan and Scrutinizer have a different idea about return values from preg_replace.
2021-09-11 06:55:00 -07:00
oleibman bc9234e5a5
Process Comments in Sylk File (#2277)
Fixes issue #2276.
2021-08-26 11:56:13 -07:00
oleibman de5f450856
Data Validations Referencing Another Sheet (#2265)
See issues #1432 and #2149. Data validations on an Xlsx worksheet can be specified in two manners - one (henceforth "internal") if a list is specified from the same sheet, and a different one (henceforth "external") if a list is specified from a different sheet. Xlsx worksheet reader formerly processed only the internal format; PR #2150 fixed this so that both would be processed correctly on read. However, Xlsx worksheet writer outputs data validators only in the internal format, and that does not work for external data validations; it appears, however, that internal data validations can be specified in external format.

This PR changes Xlsx worksheet writer to use only the external format. Somewhat surprisingly, this must come after most of the other XML tags that constitute a worksheet. It shares this characteristic (and XML tag) with conditional formatting. The new test case DataValidator2Test includes a worksheet which has both internal and external data validation, as well as conditional formatting.

There is some additional namespacing work supporting Data Validations that needs to happen on Xlsx reader. Since that is substantially unchanged with this PR, that work will happen in a future namespacing phase, probably phase 2. However, there are some non-namespace-related changes to Xlsx reader in this PR:
- Cell DataValidation adds support for a new property sqref, which is initialized through Xlsx reader using a setSqref method. If not initialized at write time, the code will work as it did before the introduction of this property. In particular, before this change, data validation applied to an entire column (as in the sample spreadsheet) would be applied only through the last populated row. In addition, this also allows a user to extend a Data Validation over a range of cells rather than just a single cell; the new method is added to the documentation.
- The topLeft property had formerly been used only for worksheets which use "freeze panes". However, as luck would have it, the sample dataset provided to demonstrate the Data Validations problem uses topLeft without freeze panes, slightly affecting the view when the spreadsheet is initially opened; PhpSpreadsheet will now do so as well.

It is worth noting issue #2262, which documents a problem with the hasValidValue method involving the calculation engine. That problem existed before this PR, and I do not yet have a handle on how it might be fixed.
2021-08-24 08:58:38 -07:00
Alayn Gortazar d0076343c4
Fix Reading XLSX files without styles.xml throws an exception. (#2247)
* Fix Reading XLSX files without styles.xml throws an exception.

* Bugfix, debugging code removed

* Fix Reading XLSX files without styles.xml throws an exception (rethinked)

* Fix Reading XLSX files without styles.xml throws an exception (rethinked)

* Style fixes

* Fix Spreadsheet loaded without styles cannot be written

* Replaced test files for empty styles.xml testing
2021-08-16 05:05:32 -07:00
oleibman d7ac7021c6
Apache OpenOffice Creates Xls Using Wrong Case for Number Format General (#2242)
See issue #2239. Problem is dealt with at the source, by making sure that Reader Xls checks for use of 'GENERAL' rather than 'General'. There doesn't seem to be a reason to test in other places, or to test for other casing variants.
2021-08-08 08:24:03 -07:00
oleibman de230fa899
Html Reader Comments (#2235)
* Html Reader Comments

See issue #2234. Html Reader processes Comment as comment, then processes it as part of cell contents. Change to only do the first. Comment Test checks that comment read by Html Reader is okay, but neglects to check the value of the cell to which the comment is attached. Added that check.

* Disconnect Worksheets

... at end of test.
2021-08-05 08:40:13 -07:00
oleibman 0cd20f3099
Csv Handling of Booleans (and an 8.1 Deprecation) (#2232)
* Csv Handling of Booleans (and an 8.1 Deprecation)

PhpSpreadsheet writes boolean values to a Csv as null-string/1, and treats input values of 'true' and 'false' as if they were strings. On the other hand, Excel writes boolean values to a Csv as TRUE/FALSE, and case-insensitively treats a matching string as boolean on read. This PR changes PhpSpreadsheet to match Excel.

A side-effect of this change is that it fixes behavior incorrectly reported as a bug in PR #2048. That issue was closed, correctly, as user error. The user had altered Csv Writer, including adding ```declare(strict_types=1);```; that declaration was the cause of the error. The "offending" statements, calls to strpbrk and str_replace, will now work correctly whether or not strict_types is in use.

And, just as I was getting ready to push this, the dailies for PHP 8.1 introduced a change deprecating auto_detect_line_endings. Csv Reader uses that setting; it allows it to process a Csv with Mac line endings, which happens to be something that Excel can do. As they say in https://wiki.php.net/rfc/deprecations_php_8_1, where the proposal passed without a single dissenting vote, "These newlines were used by “Classic” Mac OS, a system which has been discontinued in 2001, nearly two decades ago. Interoperability with such systems is no longer relevant." I tend to agree, but I don't know that we're ready to pull the plug yet. I don't see an easy way to emulate that functionality. For now, I have silenced the deprecation notices with at signs. I have also added a test case which will fail when support for that setting is pulled; this will give time to consider alternatives.

* Scrutinizer: Handling ini_set

This could be interesting. It doesn't like not handling an error condition for ini_set. Let's see if this satisfies it.
2021-08-04 07:00:17 -07:00
oleibman b9f6c70b86
New Looming Problems with PHP8.1 (#2231)
* New Looming Problems with PHP8.1

More deprecations. The following corrections are made in this PR:
- Calculation.php has a call to ctype_upper and apparently one of the samples manages to pass it an int. That function treats int differently from numeric strings, and that treatment is on the deprecation list. Enclosing the argument in quotes cannot cause a problem unless the int represents the ASCII value of an uppercase letter, which I cannot believe is the case; anyhow, if it is, the code will wind up with a nonsense result, e.g. if column is C and row is 1, the cell will be resolved as C1, but if column is int 67 (ASCII for C) and row is 1, the cell will be resolved as 671, not C1.
- Several Worksheet iterators need one or more functions to explicitly declare their return types. Thankfully, this does not seem to break earlier PHP versions.
- LocaleFloatsTest - see issue #1863. This was supposed to fail in PHP 8.0, but var_dump continued to support the old way (for 64-bit PHP only, not for 32-bit). PHP 8.1 appears to correct that omission, and the test will now fail. It doesn't show up as a failure in Github because of an accident - the attempt to set the locale to France in Github fails, so it skips the test before attempting the var_dump. But it does fail locally on my system. I have changed the test to use sprintf rather than var_dump; I think users are far more likely to use sprintf rather than var_dump in their applications. (They are, of course, even more likely to just cast to string, but the result of doing that is already different in 8.0 than in 7.4.) I would be equally happy to delete the test altogether.

There remain PHP 8.1 problems with Mpdf which are, of course, out of scope here.

There is one additional problem that I do not address in this ticket. The auto_detect_line_endings setting is being deprecated. This has some implications for Csv. I have another PR ready for Csv, and will discuss that problem there.

* Minor Scrutinizer Error

Hopefully fixed now.
2021-08-03 21:37:53 -07:00
oleibman 51163713c7
Tweaks to Input File Validation (#2217)
* Tweaks to Input File Validation

This started as a response to issue #1718, for which it is a partial (not complete) solution. The following changes are made:
- canRead can currently throw an exception. This seems wrong. It should just return true/false.
- Breaking change of sorts. When AssertFile encounters a non-existent or unreadable file, it throws InvalidArgumentException. This does not make sense. I have changed it to throw PhpSpreadsheet/Reader/Exception.
- Since the previous bullet item required changing of most of the Reader files anyhow, this is a good time to add explicit typing for canRead in the function signature rather than the DocBlock. Since all the canRead functions inherit from an abstract version in IReader, they all have to be changed simulatneously. Except for Xlsx and Ods, most of the Reader files are otherwise unchanged.
- AssertFile is changed to add an optional "zip member" parameter. It will check for the existence of an appropriate member in what is supposed to be a zip file. It is used by Xlsx and Ods.
- Verifying that a given file is a valid zip ought to be a feature of ZipArchive. Thanks to a particularly nasty bug in php/libzip (see https://bugs.php.net/bug.php?id=81222), it is unsafe to attempt to open a zero-length file as a zip archive. There is a solution, but it does not apply to all the PHP releases which we support, and isn't even necessarily supported on all the point versions of the PHP versions which we do support. I have coded up a manual test for "valid zip", with a comment pointing to the spec.
- In theory, tests now cover 100% of the code in Shared/File. In practice ... One of the tests require that chmod works properly, which is not quite true on Windows systems, so that test is skipped on Windows. Another test requires that php.ini uses a non-default value for upload_temp_dir (can't be overridden in application code), which is probably not the case when Github runs the unit tests, so that test is skipped when appropriate. I have run tests for both on systems where they are not skipped.

* Update File.php

* Scrutinizer Timeout

It's not actually timing out, it's just waiting for something to finish that finished ages ago. Making a meaningless comment change in hopes that will clear the jam. Not particularly hopeful.
2021-07-24 20:44:04 -07:00
James Lucas 11bf051c94 Fix test names per `composer check` 2021-07-21 05:53:49 -07:00
James Lucas a9533b77ec Add unit tests for files with true/false (LibreOffice) in DataValidation boolean values and those with 1/0 (Excel, GoogleSheets) 2021-07-21 05:53:49 -07:00
oleibman e8966183d3
Merge branch 'master' into chartcaption 2021-07-16 06:11:26 -07:00
oleibman 5507b96d7a
Merge branch 'master' into sheetpasswd 2021-07-13 06:11:47 -07:00
Mark Baker 15170cf8cd
Issue 2216 resolve office365 auto filter structure move (#2218)
* Initial adjustments to Xlsx Reader for two possible locations for AutoFiter information, either on the sheet itself for older files, or in the tables/tableX file for more recent files
* Refactor AutoFilter Reader logic into separate methods; preparatory work toward the eventual goal of moving it into its own dedicated AutoFilterTables class
* Basic unit tests to verify that the Xlsx Reader can read both the older and Office365 variants of the files used to store AutoFilter structure
2021-07-12 03:19:40 +02:00
oleibman 8729a68338
Xls Reader Handle MACCENTRALEUROPE With or Without Hyphen (#2213)
* Xls Reader Handle MACCENTRALEUROPE With or Without Hyphen

Fixes issue #549 and https://github.com/Maatwebsite/Laravel-Excel/issues/989 (which is the source of the new test file). Some systems accept MACCENTRALEUROPE as the name for the appropriate encoding, and some accept MAC-CENTRALEUROPE. I fortunately have access to at least one of each type, and have run the tests on each.

CodePage.php has an array of translations from codepage number to string. I now allow the value to itself be an array; if so, the code will test each in turn to see if it can be used in iconv. I did not go fishing for other similar problems. If such show up, they can be dealt with in the same manner as this one. I don't really expect others, since this is a problem not merely for Xls, but, even then, it applies only to BIFF5 and earlier.

I also moved XlsTest from Reader to Reader/Xls.

* Cache Successful Result For Future Use

Per suggestion from @MarkBaker
2021-07-12 03:02:47 +02:00
oleibman 1ff2e50ed2
Merge branch 'master' into chartcaption 2021-07-02 14:35:29 -07:00
Owen Leibman ecb4a7fe27 DocBlock Changes for Chart/Title
This is a leftover Scrutinizer change, but it needed more attention than most others. Chart/Title DocBlocks define caption as `null|string`. However, in the wild, Excel usually presents the caption as an array, and not an array of strings but rather of RichText items. I am not sure why an array is needed since a RichText item can contain many text runs, but things are what they are.

Reader/Xlsx/ChartTitleTest reads a spreadsheet with the captions stored as a RichText array. Since it performs array operations on something the DocBlock says cannot be an array, Scrutinizer objects, although not seriously enough to fail the module. Phpstan also objects; its objection is silenced with an annotation. Aside from this test, there are other tests which do set the caption to a string, and Excel seems to handle that without a problem. So, I have changed the DocBlock to specify `array|RichText|String`. I have dropped null as a possibility; nullstring will do equally well.

Because getCaption can now return multiple datatypes, I think a new function which can return the text portion of the entire caption as a single string is needed. I have added it. This simplifies the test named above, and some code in Writer/Html. The latter is not part of unit testing because the version of JpGraph found in Composer is too antiquated. I verified the Html change manually by running samples/Chart/32_Chart_read_write_HTML.php using a recent version of JpGraph. It was as a result of this test that I uncovered issue #2203. I did not see anything about Charts in docs, so did not add a description of the new function there.

Phpstan is happy with the changes. We'll see how Scrutinizer feels when I push it.
2021-07-02 14:33:43 -07:00
oleibman 075cecd268
Xlsx Reader Better Namespace Handling Phase 1 First Bugfix (#2204)
See issue #2203. An undotted i uncrossed t. When using namespaces, need to call attributes() to access the attributes before trying to access them directly. Failure to do so in castToFormula caused problem for shared formulas.

Surprisingly, this didn't show up in unit tests. Perhaps sharing the same formula between two cells isn't common. It did show up in Chart Samples. I've added a test.

I was really inclined to merge this right away. Not to worry - I can control myself. It should be moved fairly quickly nevertheless.
2021-07-02 12:36:54 +02:00
oleibman 5523fc935b
Merge branch 'master' into sheetpasswd 2021-07-01 06:52:17 -07:00
Owen Leibman b03544469b 2 Tests vs. Scrutinizer/Phpstan
Just reviewing Scrutinizer's list of "bugs". There are 19 ascribed to me. For some, I will definitely take no action (e.g. use of bitwise operators in AND, OR, and XOR functions). However, where I can clean things up so that Scrutinizer is satisfied and the resulting code is not too contorted, I will make an attempt.

This PR corrects 2 problems according to Scrutinizer, and 1 per Phpstan. Only test members are involved.
2021-07-01 11:15:02 +02:00
Owen Leibman 7b3585c76a Now That SettingsTest Is Well-Behaved
7 tests that needed to invoke Settings::setLibXmlLoaderOptions no longer need to do so.
2021-06-30 13:15:20 -07:00
Owen Leibman 3bb574c302 Fix SettingsTest
SettingsTest was changing the global LibXMLLoaderOptions without restoring the original. This caused problems for one of my new tests.
2021-06-30 11:33:35 -07:00
oleibman 2ae948a319
Reader/Slk vs. Scrutinizer/Phpstan (#2192)
Just reviewing Scrutinizer's list of "bugs". There are 19 ascribed to me. For some, I will definitely take no action (e.g. use of bitwise operators in AND, OR, and XOR functions). However, where I can clean things up so that Scrutinizer is satisfied and the resulting code is not too contorted, I will make an attempt.

This PR corrects 3 problems (2 mine) according to Scrutinizer, and 7 per Phpstan. It also moves the Reader Slk tests under their own directory, as is the case for all the other Reader types.
2021-06-29 20:48:31 +02:00
oleibman 49e97f0914
Correct Some Problems Which Will Show Up for PHP8.1 (#2191)
* Reader/Gnumeric vs. Scrutinizer

Just reviewing Scrutinizer's list of "bugs". There are 19 ascribed to me. For some, I will definitely take no action (e.g. use of bitwise operators in AND, OR, and XOR functions). However, where I can clean things up so that Scrutinizer is satisfied and the resulting code is not too contorted, I will make an attempt.

I believe this is the only one with which will involve more than 2 or 3 changes. It fixes 5 items ascribed to me, and 4 to others.

* Use Strict Checking for in_array

* Correct Some Problems Which Will Show Up for PHP8.1

PHP8.1 wants to issue a message when you use a float where it thinks you ought to be using an int (it wants its implicit casts made explicit). This is causing unit tests to fail. The following corrections are made in this PR:
- Calculation.php tests `isset(self::binaryOperators[$token])`, where token can be a float. No numeric values are members of that array, so we can test for numeric before isset.
- SharedOle.php packs a float, intending it as an int, in 2 places. I simplified the logic here, and added explicit casts to avoid the problem. This is used by Xls Reader and Writer; as added confirmation, I added some timestamps from before 1970 (i.e. negative values) to Document/EpochTest. Because of this, the test suite has been verified for 32-bit PHP as well as PHP 8.1.
- Writer/Xlsx/StringTable tests `isset($aFlippedStringTable[$cellValue])`. This is the same problem as in Calculation, but requires a different solution. The same if statement here also tests that the datatype is string, but it does so after the isset test. Changing the order of these tests avoids the problem.

* Update OLE.php
2021-06-29 19:54:08 +02:00
Owen Leibman 36b328a9fa Fix Worksheet Passwords
Fix for issue #1897.

The existing hashing code seems to work correctly almost all the time, but there are exceptions. It is replaced by an exact implementation of the spec, including a link to the spec in the comments. Cases known to fail are added to the unit test suite.

The spec expects the string to be at most 255 bytes (yes, bytes not characters). The program had permitted any length; it will now throw an exception when the maximum length is exceeded.

Xls does not support any hashing algorithm except basic. The Xls writer had, nevertheless, accepted the results of any of the other possible algorithms. This leads to (a) a worksheet that can't be unprotected, and (b) deprecation notices during the write (because it is using hexdec, which expects only hex characters, and the other algorithms generate non-hex characters). I have changed Xls writer to ignore passwords generated by other algorithms. An alternative would be to have the password hasher generate both an algorithmic password (for use by Xlsx) and a basic password (for use by Xls); I think that is too complex a solution, but can look into it if you think it worthwhile.

I do not see any current support for Worksheet passwords in ODS Reader or Writer. I did not add support in this PR.

I added a new test to confirm the password for reading a spreadsheet is consistent with the one used for writing it. As you can see from the comments for the new test, it had an unusual problem with a somewhat unusual solution.
2021-06-29 09:11:51 -07:00
oleibman cd84020693
Xlsx Reader Better Namespace Handling Phase 1 Try2 (#2173)
* Xlsx Reader Better Namespace Handling Phase 1 Try2

This is a replacement for #2088, which has run into merge conflicts. I will close that PR in the near future, however the comments in that PR may prove useful for this one. While that PR has been in draft status all along, I am marking this one as ready. I will gladly add additional tests (and, of course, make code changes) that anyone has to suggest, but, with my most recent test files which I will describe in a separate comment, I have no further ideas on useful additions.

As mentioned in the earlier ticket, this is a risky change. But, as has been demonstrated, delaying it comes with its own set of risks. It would be helpful to have a temporary moratorium on changes to Reader/Xlsx until this change is merged.

The original commit message follows.

There have been a number of issues concerning the handling of legitimate but unexpected namespace prefixes in Xlsx spreadsheets created by software other than Excel and PhpSpreadsheet/PhpExcel.I have studied them, but, till now, have not had a good idea on how to act on them. A recent comment https://github.com/PHPOffice/PhpSpreadsheet/issues/860#issuecomment-824926224 in issue #860 by @IMSoP has triggered an idea about how to proceed.

Gnumeric Reader was recently changed to handle namespaces better. Using that as a model, this PR begins the process of doing the same for Xlsx. Xlsx is much larger and more complicated than Gnumeric, hence the need to tackle it in multiple phases. I believe that this PR handles all of:
- listWorkSheetNames
- listWorkSheetInfo. Note that there was a bug in this function which would cause it to count only used columns rather than all columns. That bug is corrected.
- active sheet
- selected cell and top left cell
- cell content (formulas, numbers, text)
- hyperlinks
- comments (partial - see below)

This PR does not address:
- styles
- images and charts
- VBA and ribbons
- many other items, I'm sure

The issue for non-standard namespacing till now has been the use of unexpected prefixes. While I was working on this change, @Lambik introduced issue #2067 PR #2068 which introduced a completely different problem - the use of unexpected URLs. That PR and the issue associated with it were quite well documented, including the supplying of a test file and tests for it. I asked if I could take a look to see if it could be integrated with my change, and the result seems to be yes, so those changes are also part of this PR.

While adding a comment to my test file, I discovered that Microsoft had added "threaded comments" as a new feature. I believe these are not yet supported by PhpSpreadsheet, and I am not going to add it, at least not now. I believe that, among other things, this will make identifying the author of a comment more difficult.

Although there are a number of Phpstan baseline changes as part of this PR, I did not attempt to resolve all Phpstan reports for Reader/Xlsx. Nor did I do anything to increase coverage. This change is already large and complex enough without those efforts.
2021-06-25 09:05:49 +02:00
jarrett jordaan 795992835f
When image source is a URL, store the URL for use during extraction. (#2072)
When image source is a link store the link.
Add url mutator.

Update section in documentation on image extraction.
2021-06-24 10:50:44 +02:00
Owen Leibman d88af46ab5 Scrutinizer
24 minor problems, almost all of them unused code in tests.
2021-06-24 10:09:21 +02:00
Owen Leibman a735afc088 Autofilter Part 2
Most of the remaining 32-bit-unsafe date handling that remains in PhpSpreadsheet is in AutoFilter. Cleaning this up demonstrated that there are a lot of problems with AutoFilter, and I will do it in two pieces. Part 1 was PR #2141 which I have just merged.

In this PR:
- Fix remaining 32-bit dates in filterTestInDateGroupSet.
- Also in some of the existing AutoFilter samples. Note that the comments in two of those said the filter was being set for the first day of each month, but the code specifies the last day - I have corrected the comments.
- Remove mocking in unit tests for AutoFilter in favor of 'real' tests.
- Code coverage is now 100% in all of AutoFilter, AutoFilter/Column, and AutoFilter/Common/Rule.
- No remaining AutoFilter(/Column(/Rule)) exceptions in Phpstan baseline.
- Documentation for escaping of asterisk, question mark, and tilde in text filters included spurious backslashes which are now removed.
- Text filter escaping of question mark did not work. There had been no unit tests for any text filtering.
- Likewise there had been no testing for TopTen.
- Above- and below- average filters were not working because they acquired their Calculation instance incorrectly. There had been no tests.
- Several unchanging private static arrays in Rule were changed to private const arrays.
- Clones are now tested.
- RuleTest is moved to same directory as other tests.
2021-06-24 10:09:21 +02:00
Mark Baker 5769885802
Changes to the default arguments for `htmlspecialchars()` and `html_entity_decode()` requires setting of the argument value explicitly to prevent changes in behaviour. (#2176)
Specifically, the default for these two functions has been changed from `ENT_COMPAT` to `ENT_QUOTES | ENT_SUBSTITUTE`

This PR configures the argument used for those functions in Settings, and then explicitly applies it everywhere they are used in the codebase.
2021-06-21 12:56:03 +02:00
Owen Leibman 83c0f02c95 Move Reader Xlsx Tests from Reader to Reader/Xlsx Try 2
PR #2088 is having major merge problems. This is partly because it moves some tests from Reader to Reader/Xlsx. Making this move beforehand may help. Or it may make things worse, but they are already bad enough that I am contemplating redoing the PR. If I do that, having this done beforehand will make things easier.

This PR does nothing but move some tests. This will make it easier to test changes to Xlsx Reader without having to run each test individually, or without having to run tests for all the other readers at the same time.
2021-06-17 09:45:11 -07:00
Mark Baker d2076fefab
Additional unit tests for negative interest rates in the financial functions, and also tests using negative present/future value arguments (#2166) 2021-06-16 14:16:48 +02:00
Olivier TARGET 803737a893
Fix for #2149 / Read data validations for drop down list in another sheet. (#2150)
* Read data validations for drop down list in another sheet.

* Add function testLoadXlsxDataValidationOfAnotherSheet() in class tests/PhpSpreadsheetTests/Reader/XlsxTest.php for unit test.

* Add sample xlsx for unit tests.

* Modifiy call function isset() for warnings.

* Additional assertions to ensure that the worksheet has been read correctly for DataValidation that references a list on a different worksheet

* This should resolve the phpstan issues

Co-authored-by: Mark Baker <mark@lange.demon.co.uk>
2021-06-15 13:28:10 +02:00
oleibman 1e74282259
Fix for Issue 2158 (AverageIf Calculation Problem) (#2160)
* Improve Identification of Samples in Coverage Report

The Phpunit coverage report currently contains bullet items like `PhpOffice\PhpSpreadsheetTests\Helper\SampleTest\testSample with data set "49"`. This extremely simple change takes advantage of Phpunit's ability to accept an array with keys which are either strings or integers, by using the sample filenames as the array keys rather than sequential but otherwise meaningless integers (e.g. `49` in the earlier cited item). The bullet item will now read `PhpOffice\PhpSpreadsheetTests\Helper\SampleTest\testSample with data set "Basic/38_Clone_worksheet.php"`.

* Fix for Issue 2158 (AverageIf Calculation Problem)

Issue #2158 reports an error calculating AverageIf because a function returns null rather than a string. There turn out to be several components to this problem:
- The nominal fix to the problem is to add some null-to-nullstring coercion in DatabaseAbstract.
- This fixes the error, but does not necessarily lead to the correct result because buildQuery treats values of null and null-string identically, whereas Excel does not. So change that to treat null-string as any other string.
- But that doesn't lead to the correct result either. That's because Functions/ifCondition recognizes a null string, but then continues to (over-)process it until it returns the wrong result. Fix this problem in conjunction with the other two, and we finally get the correct result.

A new unit test is added for AVERAGEIF, and new test cases are added for SUMIF. In each case, there are complementary tests for conditions of null and null-string, and the results agree with Excel. There may or may not be value in adding new tests to other functions, and I will be glad to do so for any functions which you care to identify, but no existing tests broke as a result of these changes.
2021-06-15 09:54:57 +02:00
oleibman 4f06d84248
TextData - Minor Changes, Test Coverage (#2151)
* PHP8.1 Deprecation Passing Null to String Function

For each of the files in this PR, one or more statements can pass a null to string functions like strlower. This is deprecated in PHP8.1, and, when deprecated messages are enabled, causes many tests to error out. In every case, use coercion to pass null string rather than null.

* TextData - Minor Changes, Test Coverage

Per agreement on a previous push, I looked into standardizing the initialization of the TextData functions (like Engineering and MathTrig), with particular regard for avoiding multiple later null coercions. This simplifies the code quite a bit. This PR also increases coverage to 100% for all TextData modules. All entries in Phpstan baseline for non-deprecated TEXTDATA functions are removed. There were some minor bugfixes.

Whereas Excel (and Gnumeric) treat booleans when supplied as strings as 'TRUE' or 'FALSE', ODS treats them as '1' or '0'. Unlike Excel, ODS generally does not allow bool for int arguments; it does, however, allow them for FIND and SEARCH. ODS allows boolean for into for SUBSTITUTE even though Excel doesn't. ODS allows bool for string for NUMBERVALUE and VALUE even though Excel doesn't. ODS accepts 0 as an argument for CHAR; Excel doesn't. Most of this seems like random decisions on the part of the developers; I've done my best to follow the products in each case. There is a new test member devoted to ODS tests.

Gnumeric has an anomaly vis-a-vis the others - if length is supplied to LEFT/MID/RIGHT as null, Gnumeric treats it as 0 rather than 1.

All tests now take place in the context of a spreadsheet ...

Except for RETURNSTRING, which is not the implementation of an Excel function, and is referred to in the rest of PhpSpreadsheet only in the unit tests for itself. It should probably be deprecated, but that is not part of this PR, just in case there is some reason for it that I couldn't discern.

I have tried to make the first line of each doc block identify the Excel function name rather than its name in PhpSpreadsheet. I think it makes things more comprehensible.

Some tests call Settings::setLocale, but there was no Settings::getLocale. At the end of the tests which do it, they invoke setLocale('EN-US'), which, in a practical sense, is sufficient. However, in theory it would be better for them to get the current locale before changing it, then changing it back to the original when the time came. I have added getLocale and made the appropriate testing change.

The CHAR function took an interesting turn. One can set the value of a cell to, say, CHAR(2), the ASCII/UTF-8 representation of a control character, which is not legal in certain contexts. The only Reader/Writer that could handle this without problems is Xls, which deals with binary data all the time. However, if you tried to write it to Xlsx, Excel would not be able to open the resulting file because of what it considers an illegal character. I changed the Xlsx writer to escape such characters when writing the value of a string function. I did not make any other changes to the Xlsx writer - it seems to me that setting a cell to CHAR(2) is legitimate, but setting it to say `"\x02"` seems less likely to be legitimate, so the latter will still fail (although `="\x02"` should work). The Xlsx reader already supports the escape mechanism that I added to the writer.

CHAR control character and Ods - not supported by either Reader or Writer. I did not attempt to add this now. There is lots still missing from ODS, and this item just can't be a high priority amongst all of those.

CHAR control character and Csv - it is supported by reader and writer if the file has a csv extension. However, trying to guess the mime type without an extension - the control character makes mime_get_type guess application/octet-stream, and PhpSpreadsheet therefore thinks that Csv can't read it.

CHAR control character and Html. Actual use of the control character in the file is subject to the same problems as Xml (i.e. Xlsx and Ods). It wasn't terribly difficult to get the Html Writer to change `"\x02"` to "`&#2;`". I believe that this is technically legal; however, DOMDocument.loadHTML rejects it as an illegal entity, and I am not convinced that it is wrong to do so, so I haven't changed the Html writer.

* Scrutinizer

Correct 3 minor errors.
2021-06-15 08:37:17 +02:00
oleibman 9b6e4f9bac
Merge branch 'master' into moredatefilter 2021-06-14 20:13:36 -07:00
Mark Baker 74b02fb31c
Fix for the BIFF-8 Xls colour mappings in the Reader (#2156)
* Fix for the BIFF-8 Xls colour mappings in the Reader
* Unit test for reading colours, writing hen rereading and ensuring that the RGB values have not changed
2021-06-13 21:46:49 +02:00
oleibman b98b9c761c
Improve Identification of Samples in Coverage Report (#2153)
The Phpunit coverage report currently contains bullet items like `PhpOffice\PhpSpreadsheetTests\Helper\SampleTest\testSample with data set "49"`. This extremely simple change takes advantage of Phpunit's ability to accept an array with keys which are either strings or integers, by using the sample filenames as the array keys rather than sequential but otherwise meaningless integers (e.g. `49` in the earlier cited item). The bullet item will now read `PhpOffice\PhpSpreadsheetTests\Helper\SampleTest\testSample with data set "Basic/38_Clone_worksheet.php"`.
2021-06-11 22:29:44 +02:00
Mark Baker 05466e99ce
Html import dimension conversions (#2152)
Allows basic column width conversion when importing from Html that includes UoM... while not overly-sophisticated in converting units to MS Excel's column width units, it should allow import without errors

Also provides a general conversion helper class, and allows column width getters/setters to specify a UoM for easier usage
2021-06-11 17:29:49 +02:00
oleibman a340240a3f
PHP8.1 Deprecation Passing Null to String Function (#2137)
For each of the files in this PR, one or more statements can pass a null to string functions like strlower. This is deprecated in PHP8.1, and, when deprecated messages are enabled, causes many tests to error out. In every case, use coercion to pass null string rather than null.
2021-06-05 15:14:23 +02:00
Mark Baker 19724e3217
Reader writer flags (#2136)
* Use of passing flags with Readers to identify whether speacial features such as loading charts should be enabled; no need to instantiate a reader and manually enable it before loading any more.

This is in preparation for supporting new "boolean" Reaer/Writer features, such as pivot tables

* Use of passing flags with Writers to identify whether speacial features such as loading charts should be enabled; no need to instantiate a writer and manually enable it before loading any more.

* Update documentation with details of changes to the StringValueBinder
2021-06-04 13:45:32 +02:00
MarkBaker da9fbd6c8d PHPCS appeasement again 2021-06-03 21:42:20 +02:00
MarkBaker 8cea3a94df Unit test for RichText object 2021-06-03 21:42:20 +02:00
MarkBaker 883115a079 phpstan appeasement 2021-06-03 21:42:20 +02:00
MarkBaker f135da0b11 phpstan appeasement 2021-06-03 21:42:20 +02:00
MarkBaker 8e41445fbd Allow more control over what non-string datatypes are converted to strings in the StringValueBinder 2021-06-03 21:42:20 +02:00
MarkBaker 642fc7dee7 PHPCS and PHStan appeasement 2021-06-03 21:42:20 +02:00
MarkBaker 3297f503c2 Addtional unit tests for vlue binders 2021-06-03 21:42:20 +02:00
Owen Leibman 4ab6439de1 Scrutinizer
Fix 5 minor errors.
2021-06-02 21:49:12 -07:00
oleibman 300ea99e93
Merge branch 'master' into moredatefilter 2021-06-02 20:50:05 -07:00
Owen Leibman b19fcef51f Autofilter Part 1
Most of the remaining 32-bit-unsafe date handling that remains in PhpSpreadsheet is in AutoFilter. Cleaning this up demonstrated that there are a lot of problems with AutoFilter, and I will do it in (probably two) pieces.

In this PR:
- Dynamic date processing was really wrong. There were no tests nor samples to exercise this code. (If you need details, you can try running the new sample against old code.) It is completely re-written.
- ThisYear/Month/Week/Quarter had been omitted.
- Rules such as AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 were almost correct, but showed some off-by-1 errors. I suspect these were timezone-related, and therefore more obvious to those of us far away from Greenwich.
- All Autofilter tests are moved to a single directory.
- The documentation suggested using null with the Dynamic Date setup, but Phpstan did not like that in my new tests/samples. Rather than change the doc block, I changed the documentation to suggest null string.
- I created a new sample to generate sheets using all the dynamic filters.
- I have added some new unit tests for each of the dynamic filters. I would love to be able to add some "time travel" tests because the dynamic nature of the filter makes most of the results change from day to day, which presents significant challenges in writing comprehensive unit tests (the same is true for code coverage). I was not able to find a good way to simulate time within PhpUnit, but the Linux 'faketime' package was extraordinarily easy and helpful in allowing me to confirm some edge cases. I had less satisfactory results with some Windows equivalents, but was still able to run some tests.
- Code coverage increases from below 60% to above 80%.

To be done:
- Some 32-bit unsafe dates remain in filterTestInDateGroupSet.
- Also in some of the existing AutoFilter samples.
- Study existing unit tests for AutoFilter which use mocking to see if they can/should be replaced with 'real' tests.
- Improve code coverage in AutoFilter, AutoFilter/Column, and AutoFilter/Common/Rule.
2021-06-02 20:46:14 -07:00
MarkBaker 3168cbfb3e Select the correct TestCase 2021-05-31 13:59:51 +02:00
MarkBaker d51e4ec75a phpstan appeasement 2021-05-31 13:59:51 +02:00
MarkBaker 53362991a8 Additional unit tests to confirm behaviour when formulae reference cells within a merge range 2021-05-31 13:59:51 +02:00
oleibman eccfecd529
Reader XML Properties - Eliminate strtotime (#2134)
* Document Properties - Coverage and 32-bit-safe Timestamps

While researching an issue, I noticed that coverage of Document/Properties was poor. Further, the use of int timestamps will eventually lead to problems for 32-bit PHP (see issue #1826).

Coverage Changes:
- Many property types with no special handling are enumerated but not tested. These are removed, but will continue to function as before.
- Existing code theoretically allows property to be set to an object, but there is no means to read or write such a property, and, even if there were, I don't believe Excel supports it. Setting a property to an object will now be changed to a no-op (can throw an exception if preferred).
- Since the Properties object now has no members which are themselves objects, there is no need for a deep clone. The untested __clone method is removed.
- Large switch statements are replaced with associative arrays. Scrutinizer will like that.
- Coverage is now 100%.

<!-- end of coverage changes list -->

Timestamp Changes:
- Timestamps will be stored as int if possible, or float if not. This is, or will soon be, needed for 32-bit systems. Tests have been added for beyond-epoch dates, and run successfully with 32-bit.
- LibreOffice doesn't quite get the Created/Modified properties correct. These are written to the file as a string which includes offset from UTC, but LibreOffice ignores the offset portion when displaying them. Code had been generating these in UTC, but now generates them in default timezone, which should meet user's expectations.

<!-- end of timestamp changes list -->

Other Changes:
- Custom properties added to ODS Writer.
- Samples had not been generating any ODS files. One is now generated.
- Ods uses a single 'keywords' property rather than multiple 'keyword' properties.
- Breaking change - default company is changed to null string from Microsoft Corporation.
- Breaking change of sorts - PropertiesTest incorrectly tested a custom date property against a string, Reader/XlsxTest correctly tested against a timestamp converted to a string. PropertiesTest was defective, and will no longer work as coded; anyone using it as a model will likewise have a problem.
- PHP8.1 has been complaining for weeks about a time zone conversion test. I have now downloaded a version, and changed the code so that it will work in 8.1 as well as prior releases. (It is still likely that the existing code should work in 8.1, but I haven't yet figured out how to file a bug report.) In the course of testing, 3 additional 8.1 problems were reported (all along the lines of "can't pass null to strpos"), and are fixed with null coercion.
- Two Calculation tests failed because of large results on 32-bit system. These are corrected by allowing the functions involved to return float|int rather than int. I suspect that there are other functions with this problem, and will investigate as a follow-up activity.
- See issue #2090. I believe that changes between 17.1 and master will merely cause the problematic spreadsheet to fail in a different way. I believe that enclosing in quotes some variables passed to Document/Properties by Reader/Xlsx will eliminate the problem, but, in the absence of an example file, cannot say for sure.
- Properties tests are now separated out from Reader/XlsxTest and Reader/OdsTest, and now test both Read and Write (via reload).

<!-- end of other changes list -->

Miscellaneous Notes:
- There remains no support for Custom Properties in Xls Reader or Writer.
- We now have default timezones for all of PHP itself, Shared/Date, and Shared/Timezone. That is least one too many. I was unable to disentangle the latter two for this change, but will look into deprecating one or the other in future.

* Phpstan

6 baseline deletions, 2 docblock changes

* Scrutinizer's Turn

3 minor errors that hadn't blocked the request.

* Reader XML Properties - Eliminate strtotime

Piggyback on top of prior changes to eliminate 32-bit-unsafe call.

Add explicit tests for created, modified, and custom date properties.
2021-05-31 11:04:07 +02:00
oleibman e1cb997ee6
Gnumeric Reader - Distinguish Created and Modified Timestamps (#2133)
* Document Properties - Coverage and 32-bit-safe Timestamps

While researching an issue, I noticed that coverage of Document/Properties was poor. Further, the use of int timestamps will eventually lead to problems for 32-bit PHP (see issue #1826).

Coverage Changes:
- Many property types with no special handling are enumerated but not tested. These are removed, but will continue to function as before.
- Existing code theoretically allows property to be set to an object, but there is no means to read or write such a property, and, even if there were, I don't believe Excel supports it. Setting a property to an object will now be changed to a no-op (can throw an exception if preferred).
- Since the Properties object now has no members which are themselves objects, there is no need for a deep clone. The untested __clone method is removed.
- Large switch statements are replaced with associative arrays. Scrutinizer will like that.
- Coverage is now 100%.

<!-- end of coverage changes list -->

Timestamp Changes:
- Timestamps will be stored as int if possible, or float if not. This is, or will soon be, needed for 32-bit systems. Tests have been added for beyond-epoch dates, and run successfully with 32-bit.
- LibreOffice doesn't quite get the Created/Modified properties correct. These are written to the file as a string which includes offset from UTC, but LibreOffice ignores the offset portion when displaying them. Code had been generating these in UTC, but now generates them in default timezone, which should meet user's expectations.

<!-- end of timestamp changes list -->

Other Changes:
- Custom properties added to ODS Writer.
- Samples had not been generating any ODS files. One is now generated.
- Ods uses a single 'keywords' property rather than multiple 'keyword' properties.
- Breaking change - default company is changed to null string from Microsoft Corporation.
- Breaking change of sorts - PropertiesTest incorrectly tested a custom date property against a string, Reader/XlsxTest correctly tested against a timestamp converted to a string. PropertiesTest was defective, and will no longer work as coded; anyone using it as a model will likewise have a problem.
- PHP8.1 has been complaining for weeks about a time zone conversion test. I have now downloaded a version, and changed the code so that it will work in 8.1 as well as prior releases. (It is still likely that the existing code should work in 8.1, but I haven't yet figured out how to file a bug report.) In the course of testing, 3 additional 8.1 problems were reported (all along the lines of "can't pass null to strpos"), and are fixed with null coercion.
- Two Calculation tests failed because of large results on 32-bit system. These are corrected by allowing the functions involved to return float|int rather than int. I suspect that there are other functions with this problem, and will investigate as a follow-up activity.
- See issue #2090. I believe that changes between 17.1 and master will merely cause the problematic spreadsheet to fail in a different way. I believe that enclosing in quotes some variables passed to Document/Properties by Reader/Xlsx will eliminate the problem, but, in the absence of an example file, cannot say for sure.
- Properties tests are now separated out from Reader/XlsxTest and Reader/OdsTest, and now test both Read and Write (via reload).

<!-- end of other changes list -->

Miscellaneous Notes:
- There remains no support for Custom Properties in Xls Reader or Writer.
- We now have default timezones for all of PHP itself, Shared/Date, and Shared/Timezone. That is least one too many. I was unable to disentangle the latter two for this change, but will look into deprecating one or the other in future.

* Phpstan

6 baseline deletions, 2 docblock changes

* Scrutinizer's Turn

3 minor errors that hadn't blocked the request.

* Gnumeric Reader - Distinguish Created and Modified Timestamps

Both are being used to set both fields; change to set the appropriate one in each case.

Also replace use of 32-bit-unsafe strtotime.
2021-05-31 10:24:37 +02:00
oleibman e53a2b2e0d
Document Properties - Coverage and 32-bit-safe Timestamps (#2113)
* Document Properties - Coverage and 32-bit-safe Timestamps

While researching an issue, I noticed that coverage of Document/Properties was poor. Further, the use of int timestamps will eventually lead to problems for 32-bit PHP (see issue #1826).

Coverage Changes:
- Many property types with no special handling are enumerated but not tested. These are removed, but will continue to function as before.
- Existing code theoretically allows property to be set to an object, but there is no means to read or write such a property, and, even if there were, I don't believe Excel supports it. Setting a property to an object will now be changed to a no-op (can throw an exception if preferred).
- Since the Properties object now has no members which are themselves objects, there is no need for a deep clone. The untested __clone method is removed.
- Large switch statements are replaced with associative arrays. Scrutinizer will like that.
- Coverage is now 100%.

<!-- end of coverage changes list -->

Timestamp Changes:
- Timestamps will be stored as int if possible, or float if not. This is, or will soon be, needed for 32-bit systems. Tests have been added for beyond-epoch dates, and run successfully with 32-bit.
- LibreOffice doesn't quite get the Created/Modified properties correct. These are written to the file as a string which includes offset from UTC, but LibreOffice ignores the offset portion when displaying them. Code had been generating these in UTC, but now generates them in default timezone, which should meet user's expectations.

<!-- end of timestamp changes list -->

Other Changes:
- Custom properties added to ODS Writer.
- Samples had not been generating any ODS files. One is now generated.
- Ods uses a single 'keywords' property rather than multiple 'keyword' properties.
- Breaking change - default company is changed to null string from Microsoft Corporation.
- Breaking change of sorts - PropertiesTest incorrectly tested a custom date property against a string, Reader/XlsxTest correctly tested against a timestamp converted to a string. PropertiesTest was defective, and will no longer work as coded; anyone using it as a model will likewise have a problem.
- PHP8.1 has been complaining for weeks about a time zone conversion test. I have now downloaded a version, and changed the code so that it will work in 8.1 as well as prior releases. (It is still likely that the existing code should work in 8.1, but I haven't yet figured out how to file a bug report.) In the course of testing, 3 additional 8.1 problems were reported (all along the lines of "can't pass null to strpos"), and are fixed with null coercion.
- Two Calculation tests failed because of large results on 32-bit system. These are corrected by allowing the functions involved to return float|int rather than int. I suspect that there are other functions with this problem, and will investigate as a follow-up activity.
- See issue #2090. I believe that changes between 17.1 and master will merely cause the problematic spreadsheet to fail in a different way. I believe that enclosing in quotes some variables passed to Document/Properties by Reader/Xlsx will eliminate the problem, but, in the absence of an example file, cannot say for sure.
- Properties tests are now separated out from Reader/XlsxTest and Reader/OdsTest, and now test both Read and Write (via reload).

<!-- end of other changes list -->

Miscellaneous Notes:
- There remains no support for Custom Properties in Xls Reader or Writer.
- We now have default timezones for all of PHP itself, Shared/Date, and Shared/Timezone. That is least one too many. I was unable to disentangle the latter two for this change, but will look into deprecating one or the other in future.

* Phpstan

6 baseline deletions, 2 docblock changes

* Scrutinizer's Turn

3 minor errors that hadn't blocked the request.
2021-05-30 13:55:58 +02:00
Mark Baker bff2317a03
Merge branch 'master' into docprops 2021-05-30 13:37:07 +02:00
Owen Leibman b533f43f75 Improve Coverage for HashTable, Fix Clone
Add unit tests to cover all of HashTable. I was hoping to do this without source changes, but this class does require a deep clone, and, as the new unit tests revealed, the existing code did not fill the bill - it cloned objects, but not arrays which contained objects, and all the object variables in this class are arrays which can contain objects.
2021-05-30 13:03:37 +02:00
oleibman d21d943d99
Merge branch 'master' into csvdflts 2021-05-29 23:38:53 -07:00
oleibman 05d3b9393c
Document Security - Coverage, Testing, and Bug-fixing (#2128)
Having a parallel project to complete cover Document Properties, I turned my attention to to Document Security. As happens, this particular change grew a bit over time.

Coverage and Testing Changes:
- Since the Security object has no members which are themselves objects, there is no need for a deep clone. The untested __clone method is removed.
- Almost all of the coverage for the Security Object came about through samples 11 and 41, not through formal tests with assertions. Formal tests have been added.
- All methods now use type-hinting via the function signature rather than doc block.
- Coverage is now 100%.

<!-- end of coverage and testing changes list -->

Bug:
- Xlsx Reader was not evaluating the Lock values correctly. This revelation came as a result of the new tests ...
- Which showed that Xlsx Reader was testing SimpleXmlElement as a boolean rather than the stringified version of that ...
- Which didn't matter all that much because Xlsx Writer was writing the values as 'true' or 'false' rather than '1' or '0', and (bool) 'false' is true.
- Xlsx Reader clearly needed a change. I was trying to avoid that while awaiting the namespacing change. At least this is restricted to a very small self-contained piece of the code.
- It is less clear whether Xlsx Writer should be changed. It is true that Excel itself uses 1/0 when writing; however it is equally true that it recognizes true/false as well as 1/0 when reading. For now, I have left Xlsx Writer alone to limit the change to what is absolutely needed.

<!-- end of bug list -->

Other Changes:
- I was at a complete loss as to what "lock revisions" was supposed to do, and it took a while to find anything on the web that explained it. Thank you, openpyxl, for coming through. I have documented it for PhpSpreadsheet now.

<!-- end of other changes list -->

Miscellaneous Note:
- There remains no support for Document Security in Xls Reader or Writer (nor in any of the other readers/writers except Xlsx).
- No Phpstan baseline changes, possibly for the first time in any of my PRs since Phpstan was introduced.

Co-authored-by: Mark Baker <mark@lange.demon.co.uk>
2021-05-29 14:13:28 +02:00
Owen Leibman 3540a275b9 Scrutinizer and Phpstan
Didn't realize Scrutinizer enforces complexity limits in tests.
2021-05-29 12:52:11 +02:00
Owen Leibman 68dd2c39da Tests for PreCalc
PR #2110 added some documentation for an unexpected observation when formula pre-calculation was set to false. I had suggested adding a unit test to demonstrate the observation, but I couldn't find any existing tests for PreCalc. This PR rectifies that omission.
2021-05-29 12:52:11 +02:00
Matjaž Drolc 0b0f02206f fix: Set font size to 10 when given 0
This change restored behavior from PHP7 in PHP8. In PHP7 calling
setSize(0) resulted in font size being set to 10. The fix addresses
change to equal comparisons in PHP8. Extra comparison is added to keep
result from PHP7 in PHP8 for the setSize(0) case.
2021-05-29 11:17:25 +02:00
MarkBaker 5e531b4511 Fix phpcs, phpstan and scrutinizer issues 2021-05-28 22:35:37 +02:00
MarkBaker e0e5a81d69 Move documentation builder to infra so that it isn't included in non `--dev` composer downloads
Unit test for locale builder
Add new function stubs (as dummy) to Calculation list of functions
2021-05-28 22:35:37 +02:00
Owen Leibman 1bce0e193d Scrutinizer's Turn
3 minor errors that hadn't blocked the request.
2021-05-23 17:24:26 -07:00
oleibman c5df2fc928
Merge branch 'master' into docprops 2021-05-23 15:14:11 -07:00
Owen Leibman cad1730d38 Document Properties - Coverage and 32-bit-safe Timestamps
While researching an issue, I noticed that coverage of Document/Properties was poor. Further, the use of int timestamps will eventually lead to problems for 32-bit PHP (see issue #1826).

Coverage Changes:
- Many property types with no special handling are enumerated but not tested. These are removed, but will continue to function as before.
- Existing code theoretically allows property to be set to an object, but there is no means to read or write such a property, and, even if there were, I don't believe Excel supports it. Setting a property to an object will now be changed to a no-op (can throw an exception if preferred).
- Since the Properties object now has no members which are themselves objects, there is no need for a deep clone. The untested __clone method is removed.
- Large switch statements are replaced with associative arrays. Scrutinizer will like that.
- Coverage is now 100%.

<!-- end of coverage changes list -->

Timestamp Changes:
- Timestamps will be stored as int if possible, or float if not. This is, or will soon be, needed for 32-bit systems. Tests have been added for beyond-epoch dates, and run successfully with 32-bit.
- LibreOffice doesn't quite get the Created/Modified properties correct. These are written to the file as a string which includes offset from UTC, but LibreOffice ignores the offset portion when displaying them. Code had been generating these in UTC, but now generates them in default timezone, which should meet user's expectations.

<!-- end of timestamp changes list -->

Other Changes:
- Custom properties added to ODS Writer.
- Samples had not been generating any ODS files. One is now generated.
- Ods uses a single 'keywords' property rather than multiple 'keyword' properties.
- Breaking change - default company is changed to null string from Microsoft Corporation.
- Breaking change of sorts - PropertiesTest incorrectly tested a custom date property against a string, Reader/XlsxTest correctly tested against a timestamp converted to a string. PropertiesTest was defective, and will no longer work as coded; anyone using it as a model will likewise have a problem.
- PHP8.1 has been complaining for weeks about a time zone conversion test. I have now downloaded a version, and changed the code so that it will work in 8.1 as well as prior releases. (It is still likely that the existing code should work in 8.1, but I haven't yet figured out how to file a bug report.) In the course of testing, 3 additional 8.1 problems were reported (all along the lines of "can't pass null to strpos"), and are fixed with null coercion.
- Two Calculation tests failed because of large results on 32-bit system. These are corrected by allowing the functions involved to return float|int rather than int. I suspect that there are other functions with this problem, and will investigate as a follow-up activity.
- See issue #2090. I believe that changes between 17.1 and master will merely cause the problematic spreadsheet to fail in a different way. I believe that enclosing in quotes some variables passed to Document/Properties by Reader/Xlsx will eliminate the problem, but, in the absence of an example file, cannot say for sure.
- Properties tests are now separated out from Reader/XlsxTest and Reader/OdsTest, and now test both Read and Write (via reload).

<!-- end of other changes list -->

Miscellaneous Notes:
- There remains no support for Custom Properties in Xls Reader or Writer.
- We now have default timezones for all of PHP itself, Shared/Date, and Shared/Timezone. That is least one too many. I was unable to disentangle the latter two for this change, but will look into deprecating one or the other in future.
2021-05-23 15:05:49 -07:00
MarkBaker 5e657b296a Eliminate spurious test that I managed to introduce by accident (related to a different issue) 2021-05-20 23:29:57 +02:00
MarkBaker 91af5bbc4f Resolve phpcs issues 2021-05-20 23:29:57 +02:00
Nathan Dench 1a78ecfb10 Track down bug in AddressHelper::convertFormulaToA1 2021-05-20 21:26:20 +02:00
Nathan Dench 03ba547f5a Test convertFormulaToA1FromR1C1 2021-05-20 21:26:20 +02:00
Nathan Dench 62d3a56a57 Add AddressHelper::convertFormulaToA1 tests for SpreadsheetXML 2021-05-20 21:26:20 +02:00
MarkBaker 41a52c592c Some simplification to the locale file loader 2021-05-20 20:41:09 +02:00
MarkBaker 65309dbe78 Fix unit tests for function list markdown, and style issues for DOLLAR/USDOLLAR 2021-05-20 20:41:09 +02:00
MarkBaker f89bfc9e02 Additional language data, and improved automated build of translation files for Calculation Engine locale 2021-05-20 20:41:09 +02:00
oleibman 990d46d451
Merge branch 'master' into sample19b 2021-05-18 21:01:36 -07:00
oleibman 294933c9e5
Update CsvContiguousTest.php 2021-05-16 11:48:12 -07:00
oleibman 251df6e61e
Merge branch 'master' into csvdflts 2021-05-16 06:13:40 -07:00
Owen Leibman ae80c12ef0 CSV Reader Enhancements
This PR came about as I pondered how feasible it was to change the default escape character from backslash to null string, since the latter emulates Excel's own actions. Also, surveying issues relating to CSV, it seems that people are often in a situation where the current defaults aren't optimal for them (e.g. they are in a region where semicolon rather than comma is a better default delimiter). My case and that case can both be handled by methods after a reader is constructed. However, the issues also show that many use `IOFactory::load` rather than `new Csv()`, and the methods to affect the defaults are not available in that case.

Adding a static callback that can be invoked by the constructor addresses all these problems. This can be set as part of the user application's normal initialization, and no special attention needs to be paid to CSV loads thereafter, no matter how they are invoked.

This also makes it feasible to use 'guess' as inputEncoding, by providing a new setFallbackEncoding (default CP1252) method to use if none of the heuristic tests pass. There was already the ability to guess the encoding before `$reader->load()`, but not before `IOFactory::load`.

Almost all typehints in Reader/Csv and Reader/Csv/Delimiter are now part of the function signature rather than in the DocBlock. The exceptions are one method in Delimiter which uses a `resource` parameter, and the `canRead` and `load` methods, which must match the signature in IOFactory. I will look into changing those later.

The Csv Reader tests are moved into their own directory. All Phpstan baseline entries involving Csv Reader are eliminated.
2021-05-16 06:05:02 -07:00
Owen Leibman 4bd506b414 Minor Improvement to Test Cleanup DateTime
Permit spreadsheet allocated as private member in test class to be garbage-collected after test completion.
2021-05-14 10:53:27 +02:00
Owen Leibman efe8f49123 Minor Improvement to Test Cleanup LookupRef
Permit spreadsheet allocated as private member in test class to be garbage-collected after test completion.
2021-05-14 10:30:49 +02:00
Owen Leibman 7aa83eb72f Missed One
Correct one test.
2021-05-14 09:54:24 +02:00
Owen Leibman 4df184320a Minor Improvement to Test Cleanup MathTrig
Permit spreadsheet allocated as private member in test class to be garbage-collected after test completion.
2021-05-14 09:54:24 +02:00
MarkBaker 765d4586ae Renaming the last of the DateTime implementation methods 2021-05-12 17:17:25 +02:00
MarkBaker f7a07747fd More method renaming 2021-05-12 17:17:25 +02:00
MarkBaker aa3269a863 Some method renaming 2021-05-12 17:17:25 +02:00
MarkBaker cd667500e0 Group some of the newly extracted Excel DateTime function implementations into groups of related functions with appropriate and meaningful class names, and rename the public methods to be more descriptive of their purpose 2021-05-12 17:17:25 +02:00
oleibman d5492ac8ed
Merge branch 'master' into #984 2021-05-11 14:44:33 -07:00
Owen Leibman 9c43d5f1b7 Xlsx Writer Formula with Bool Result of False
Fix for #2082. Xlsx Writer was writing a cell which is a formula which evaluates to boolean false as an empty XML tag. This is okay for Excel 365, but not for Excel 2016-. Change to write the tag as a value of 0 instead, which works for all Excel releases. Add test.
2021-05-11 13:48:38 +02:00
xandros15 bb11378fca #984 fix php-cs-fixer warnings 2021-05-11 12:44:40 +02:00
Owen Leibman 9fed8d87f6 Two Problems with Sample19
19_NamedRange.php was not changed to use absolute addressing when that was introduced to Named Ranges. Consequently, the output from this sample has been wrong ever since, for both Xls and Xlsx.

There was an additional problem with Xls. It appears that the Xls Writer Parser does not parse multiple concatenations using the ampersand operator correctly. So, `=B1+" "+B2` was parsed as `=B1+" "`. I believe that this is due to ampersand being treated as a condition rather than an operator; `A1>A2>A3` isn't valid, but `A1&A2&A3` is. My original PR (#1992, which I will now close) only partially resolved this, but I think moving ampersand handling from `condition` to `expression` is fully successful.

There are already more than ample tests for Named Ranges, so I did not add a new one for that purpose. However, I did add a new test for the Xls parser problem.
2021-05-09 15:41:36 -07:00
Mark Baker d2e6db71fa
Lookup functions additional unit tests (#2074)
* Additional unit tests for VLOOKUP() and HLOOKUP()
* Additional unit tests for CHOOSE()
* Unit tests for HYPERLINK() function
* Fix CHOOSE() test for spillage
2021-05-07 23:40:30 +02:00
Mark Baker 72a36a5bb8
Resolve issue with conditional font size set to zero in PHP8 (#2073)
* Let's see if the tests now pass against PHP8; output file looks to be good
* Font can't be both superscript and subscript at the same time, so we use if/else rather than if/if
2021-05-07 12:53:59 +02:00
Mark Baker 5ee4fbf090
Implement basic autofilter ranges with Gnumeric Reader (#2057)
* Load basic autofilter ranges with Gnumeric Reader
* Handle null values passed to row height/column with/merged cells/autofilters
2021-05-04 22:32:12 +02:00
oleibman 4be9366722
Gnumeric Better Namespace Handling (#2022)
* Gnumeric Better Namespace Handling

There have been a number of issues concerning the handling of legitimate but unexpected namespace prefixes in Xlsx spreadsheets created by software other than Excel and PhpSpreadsheet/PhpExcel.I have studied them, but, till now, have not had a good idea on how to act on them. A recent comment https://github.com/PHPOffice/PhpSpreadsheet/issues/860#issuecomment-824926224 in issue #860 by @IMSoP has triggered an idea about how to proceed.

Although the issues exclusively concern Xlsx format, I am starting out by dealing with Gnumeric. It is simpler and smaller than Xlsx, and, more important, already has a test for an unexpected prefix, since, at some point, it changed its generic prefix from gmr to gnm. I added support and a test for that some time ago, but almost certainly not in the best possible manner. The code as changed for this PR seems simpler and less kludgey, both for that exceptional case as well as for normal handling.

My hope is that this change can be a template for similar Reader changes for Xml, Ods, and, especially, Xlsx.

All grandfathered Phpstan issues with Gnumeric are fixed and eliminated from baseline as part of this change.

* Namespace Handling using XMLReader

Adopt a suggestion from @IMSoP affecting listWorkSheetInfo, which uses XMLReader rather than SimpleXML for its processing.

* Update GnumericLoadTest.php

PR #2024 was pushed last night, causing a Phpstan problem with this member.

* Update Gnumeric.php

Suggestions from Mark Baker - strict equality test, more descriptive variable names.
2021-05-04 21:41:11 +02:00
Mark Baker 5873116488
Unit testing for row/column/worksheet visibility for Xls and Xlsx files (#2059)
* Unit testing for row/column/worksheet visibility for Xls and Xlsx files
* Include very hidden in worksheet visibility tests
2021-05-03 23:46:40 +02:00
Mark Baker 2b268c8dd9
Fix row visibility in XLS Writer (#2058)
* Fix reversed visibility in Xls Writer
2021-05-03 22:21:57 +02:00
oleibman 346bad1b1d
Fix for Issue 2042 (SUM Partially Broken) (#2045)
As issue #2042 documents, SUM behaves differently with invalid strings depending on whether they come from a cell or are used as literals in the formula. SUM is not alone in this regard; COUNTA is another function within this behavior, and the solution to this one is modeled on COUNTA. New tests are added for SUM, and the resulting tests are duplicated to confirm correct behavior for both cells and literals.

Samples 16 (CSV), 17 (Html), and 21 (PDF) were adversely affected by this problem. 17 and 21 were immediately fixed, but 16 had another problem - Excel was not interpreting the UTF8 currency symbols correctly, even though the file was saved with a BOM. After some experimenting, it appears that the `sep=;` line generated by setExcelCompatibility(true) causes Excel to mis-handle the file. This seems like a bug - there is apparently no way to save a UTF-8 CSV with non-ASCII characters which specifies a non-standard separator which Excel will open correctly. I don't know if this is a recent change or if it is just the case that nobody noticed this problem till now. So, I changed Sample 16 to use setUseBom rather than setExcelCompatibility, which solved its problem. I then added new tests for setExcelCompatibility, with documentation of this problem.
2021-05-03 18:31:01 +02:00
Mark Baker fd14da1675
Ods defined names unit tests (#2054)
* Defined names/formulae in ODS are prefixed by $$ when used in a formula; so we need to strip this out to fully convert them to an Excel formula

* Test for ODS Writer for DefinedNames
2021-05-03 08:39:42 +02:00
xandros15 a757692992 #984 add support notContainsText for conditional styles in xlsx reader 2021-05-02 22:09:38 +02:00
Mark Baker 83e55cffcc
First steps in the implementation of AutoFilters for ODS Reader and Writer (#2053)
* First steps in the implementation of AutoFilters for ODS Reader and Writer, starting with reading a basic AutoFilter range (ignoring row visibility, filter types and active filters for the moment).

And also some additional refactoring to extract the DefinedNames Reader into its own dedicated class as a part of overall code improvement... on the principle of "when working on a class, always try to leave the library codebase in a better state than you found it"

* Provide a basic Ods Writer implementation for AutoFilters
* AutoFilter Reader Test
* AutoFilter Writer Test
* Update Change Log
2021-05-02 22:00:48 +02:00
Mark Baker d555b5d312
Pattern Fill style should default to 'solid' if there is a pattern fill with colour but no style (#2050)
* Pattern Fill style should default to 'solid' if there is a pattern fill style for a conditional; though may need to check if there are defined fg/bg colours as well; and only set a fill style if there are defined colurs
2021-04-30 20:05:45 +02:00
xandros15 815dabae89 #984 add support notContainsText for conditional styles in xlsx 2021-04-30 15:22:07 +02:00
oleibman cc5c0205d5
Fix for Issue 2029 (Invalid Cell Coordinate A-1) (#2032)
* Fix for Issue 2029 (Invalid Cell Coordinate A-1)

Fix for #2021. When Html Reader encounters an embedded table, it tries to shift it up a row. It obviously should not attempt to shift it above row 1. @danmodini reported the problem, and suggests the correct solution. This PR implements that and adds a test case.

Performing some additional testing, I found that Html Reader cannot handle inline column width or row height set in points rather than pixels (and HTML writer with useInlineCss generates these values in points). It also doesn't handle border style when the border width (which it ignores) is omitted. Fixed and added tests.
2021-04-29 22:59:01 +02:00
Mark Baker e4973fa041
Start work on refactoring the last of the Excel Statistical functions (#2033)
* Refactoring the last of the Excel Statistical functions
2021-04-29 14:34:50 +02:00
Mark Baker 475874bed3
Initial implementation of the URLENCODE() web function (#2031)
* Initial implementation of the URLENCODE() web function
2021-04-28 17:10:36 +02:00
Mark Baker d118a7070b
Completion of refactoring for Excel Lookup and Reference functions (#2030)
* Completion of refactoring for Excel Lookup and Reference functions
* Fix LookupRef tests checking for cell existence
* Fix a couple of now invalid callable references in the Calculation Engine lookup table
2021-04-28 14:08:20 +02:00
Mark Baker 8d7be25823
Improve Range handling in the Calculation Engine for Row and Column ranges (#2028)
* Improve Range handling in the Calculation Engine for Row and Column ranges
2021-04-27 19:10:37 +02:00
Adrien Crivelli 4e2259c135
BREAKING `Worksheet::getRowDimension()` and `Worksheet::getColumnDimension()` cannot return null anymore
Both methods used to optionally return null if passed a
second argument. This second argument was removed entirely and the
method always returns a RowDimension or ColumnDimension respectively
(possibly creating it if needed).

This make the API more predictable and easier to do static analysis
with tools such as PHPStan.

If you relied on that second parameter, you should instead use the
`Worksheet::getRowDimensions()` or `Worksheet::getColumnDimensions()` and
check for existence yourself before calling the getters.
2021-04-25 17:02:36 +09:00
oleibman 1e8ff9f852
DateTimeExcel - Change Names of funcWhatever to evaluate (#2015)
* DateTimeExcel - Change Names of funcWhatever to evaluate

Per discussions while MathTrig was being broken up, this would help standardize the code. This PR applies that standardization to the DateTimeExcel family of functions.

The deprecation messages in DateTime.php are changed to match the style used in PR #2005.

All Phpstan grandfathered errors (about 25) in DateTimeExcel are fixed and removed from baseline. A small number (about 5) of phpstan annotations in the source members in that directory are also fixed and eliminated.
2021-04-24 18:56:58 +02:00
oleibman a01a401228
MathTrig - Fix Phpstan Accomodations (#2020)
* MathTrig - Fix Phpstan Accomodations

This should be the last of my mass changes to MathTrig. All he Phpstan violations found in baseline which  are part of MathTrig are now fixed and removed from baseline. There were about 20 of these.
2021-04-24 18:12:17 +02:00
oleibman b05dc31850
MathTrig - Change Names of funcWhatever to evaluate (#2008)
* MathTrig - Change Names of funcWhatever to evaluate

Per discussions while MathTrig was being broken up, this would help standardize the code. That idea was adopted partway through the breakup. This PR applies that standardization to the earlier efforts. A similar effort is required for DateTime; that will come later. This PR replaces #2006.

The only 2 remaining funcWhatevers in MathTrig are both in SUM, which required two different methods depending on whether or not string parameters were to be ignored. It seems appropriate to leave those method names non-standardized in order to require a decision about which is to be used if they are invoked internally.

3 Phpstan grandfathered errors were eliminated as part of this change, and its baseline has changed accordingly.

Co-authored-by: Mark Baker <mark@lange.demon.co.uk>
2021-04-20 22:43:29 +02:00
oleibman c79a9a8e21
Improved Support for INDIRECT, ROW, and COLUMN Functions (#2004)
* Improved Support for INDIRECT, ROW, and COLUMN Functions

This should address issues #1913 and #1993. INDIRECT had heretofore not supported an optional parameter intended to support addresses in R1C1 format which was introduced with Excel 2010. It also had not supported the use of defined names as an argument. This PR is a replacement for #1995, which is currently in draft status and which I will close in a day or two.

The ROW and COLUMN functions also should support defined names. I have added that, and test cases, with the latest push. ROWS and COLUMNS already supported it correctly, but there had been no test cases. Because ROW and COLUMN can return arrays, and PhpSpreadsheet does not support dynamic arrays, I left the existing direct-call tests unchanged to demonstrate those capabilities.

The unit tests for INDIRECT had used mocking, and were sorely lacking (tested only error conditions). They have been replaced with normal, and hopefully adequate, tests. This includes testing globally defined names, as well as locally defined names, both in and out of scope.

The test case in 1913 was too complicated for me to add as a unit test. The main impediments to it are now removed, and its complex situation will, I hope, be corrected with this fix.

INDIRECT can also support a reference of the form Sheetname!localName when localName on its own would be out of scope. That functionality is added. It is also added, in theory, for ROW and COLUMN, however such a construction is rejected by the Calculation engine before passing control to ROW or COLUMN. It might be possible to change the engine to allow this, and I may want to look into that later, but it seems much too risky, and not nearly useful enough, to attempt to address that as part of this change.

Several unusual test cases (leading equals sign, not-quite-as-expected name definition in file, complex indirection involving concatenation and a dropdown list) were suggested by @MarkBaker and are included in this request.
2021-04-20 22:16:21 +02:00
oleibman aeccdb35e2
XLSX Reader and Empty Fill Tag (#2011)
Openpyxl can generate the xml tag `<patternFill/>`, possibly even as a default style. Excel has no problem with this, treating it as "fill none", but PhpSpreadsheet has a glitch because it treats it as "fill solid white". So, when PhpSpreadsheet loads and saves such a file, the result at first appears as if gridlines are disabled; in fact, the gridlines are merely invisible behind the cells with their solid white fill. This PR makes PhpSpreadsheet behave the same as Excel in this circumstance.

Co-authored-by: Mark Baker <mark@lange.demon.co.uk>
2021-04-20 17:20:59 +02:00
Mark Baker 6282035c96
Extract Property and Style readers from the XML Reader into separate classes (#2009)
* Extract Property and Style readers from the XML Reader into separate classes
2021-04-20 15:27:44 +02:00
Tiago Fernandes 11f8a02194
Merge branch 'master' into issue-907-absolute-path-in-Target 2021-04-19 14:32:20 +01:00
Tiago Fernandes 559c0761df Remove unnecessary changes. Added test 2021-04-19 11:25:48 +01:00
Mark Baker f49a951bea
Tag deprecations for MathTrig, and eliminate calls to the deprecated methods (#2005)
* Tag deprecations for MathTrig, and eliminate calls to the deprecated methods
2021-04-18 12:19:53 +02:00
Adrien Crivelli d85eaacfa3
BREAKING `Worksheet::getCell()` cannot return null anymore
`Worksheet::getCell()` used to optionnaly return null if passed a
second argument. This second argument was removed entirely and the
method always returns a Cell (possibly creating it if needed).

This make the API more predictable and easier to do static analysis
with tools such as PHPStan.

If you relied on that second parameter, you should instead use the
`Worksheet::cellExists()` before calling `getCell()`.
2021-04-13 11:09:29 +09:00
Adrien Crivelli 49f87de165
Reduce PHPStan error in tests 2021-04-12 11:10:23 +09:00
Adrien Crivelli f9532231d2
PHPStan Level 3 2021-04-11 16:33:53 +09:00
Akira Taniguchi da28089c3c
Merge branch 'master' into master 2021-04-06 23:56:37 +09:00
Mark Baker bc18fb7e77
more extraction of Excel Financial functions (#1989)
* More Financial function extracts, this time looking at the Periodic Cashflow functions
* Initial extract of Constant Periodic Interest and Payment functions
2021-04-06 12:45:37 +02:00
Akira Taniguchi 551bbdf30f
Update CsvOutputEncodingTest.php 2021-04-06 18:53:21 +09:00
Vivek 93d858a064
Merge branch 'master' into fix_excel_overwrite 2021-04-06 08:19:44 +05:30
Akira Taniguchi e48ffdbe77
Update CsvOutputEncodingTest.php 2021-04-06 04:44:24 +09:00
Akira Taniguchi 991616d1d9
Update CsvOutputEncodingTest.php 2021-04-06 04:39:26 +09:00
Akira Taniguchi 86f3bdd598
Update CsvOutputEncodingTest.php 2021-04-06 04:27:14 +09:00
Akira Taniguchi bfd4a659a4
Update CsvOutputEncodingTest.php 2021-04-06 04:11:46 +09:00
Akira Taniguchi 2adc44262c
Update CsvOutputEncodingTest.php 2021-04-06 03:48:08 +09:00
Akira Taniguchi 7681a1093f
Update CsvOutputEncodingTest.php 2021-04-06 03:46:10 +09:00
Akira Taniguchi 2df8e1a93f
Update CsvOutputEncodingTest.php 2021-04-06 03:07:10 +09:00
Akira Taniguchi f6bfbd0655
Create CsvOutputEncodingTest.php 2021-04-06 02:56:54 +09:00
Akira Taniguchi 2a16ce1432
Delete CsvOutputEncoding.php 2021-04-06 02:47:46 +09:00
Akira Taniguchi eef90b62df
Create CsvOutputEncoding.php 2021-04-06 02:05:08 +09:00
Vivek Kumar dd9cb259d0 Unlink temporary file 2021-04-05 22:14:50 +05:30
oleibman 95b8c4d59b
Continue MathTrig Breakup - Completion! (#1985)
* Continue MathTrig Breakup - Completion!

Continuing the process of breaking MathTrip.php up into smaller classes. This round takes care of everything that was left:
- ABS
- DEGREES
- EXP
- RADIANS
- SQRT
- SQRTPI
- SUMSQ, SUMX2MY2, SUMX2PY2, SUMXMY2

The only notable logic change was that the 3 SUMX* functions had accepted arrays of unlike length; in that condition, they now return N/A, as Excel does. There had been no tests for this condition.

All the functions in MathTrig.php are now deprecated. Except for COMBIN, the test suite executes them only from MathTrig MovedFunctionsTest. COMBIN is still directly called by some Statistics Binomial functions which have not yet had the opportunity to be re-coded for the new location.


Co-authored-by: Mark Baker <mark@lange.demon.co.uk>
2021-04-05 16:39:03 +02:00
Vivek Kumar 5e96f4292b Merge remote-tracking branch 'master' into fix_excel_overwrite 2021-04-05 12:42:43 +05:30
Vivek Kumar 59de56bb62 Move original file to temporary file 2021-04-05 12:26:44 +05:30
Adrien Crivelli d02352845c
PHPStan Level 2 2021-04-04 22:06:00 +09:00
Mark Baker dd74dd7fcf
Let's start with some appeasements to phpstan, just to reduce the baseline (#1983)
* Let's start with some appeasements to phpstan, just to reduce the baseline
* Appeasements to phpstan, taking the number of reported errors down to just 61
2021-04-03 17:10:40 +02:00
Adrien Crivelli a189d933f2
Introduce PHPStan
To improve the feedback loop on code quality with a process
that can be run locally by the developers, instead of only
on Scrutinizer.
2021-04-03 16:13:21 +09:00
Mark Baker a2bb825bc5
Extract Normal and Standard Normal Distributions from the Statistical Class (#1981)
* Extract Normal and Standard Normal Distributions from the Statistical Class
* Extract ZTest from the Statistical Class, and move it to the Standard Normal Distribution class
Additional unit tests for NORMINV()
* Extract LogNormal distribution functions from Statistical
2021-04-02 20:17:03 +02:00
oleibman a4982fd9fe
Continue MathTrig Breakup - Penultimate? (#1973)
* Continue MathTrig Breakup - Penultimate?

Continuing the process of breaking MathTrip.php up into smaller classes. This round takes care of about half of what is left, so perhaps one round after this one will finish the job:
- ARABIC
- COMBIN; also implemented COMBINA
- FACTDOUBLE
- GCD (which accepts and ignores empty cells as arguments, but returns VALUE if all the arguments are that way; LCM does the same)
- LOG_BASE, LOG10, LN
- implemented MUNIT
- MOD
- POWER
- RAND, RANDBETWEEN (RANDARRAY is too complicated to implement with this ticket)

As you can see from the description, there are some functions which were combined in a single class. When not combined, I adopted PowerKiki's suggestion of using "execute" as the function name.

Co-authored-by: Mark Baker <mark@lange.demon.co.uk>
2021-04-02 14:35:34 +02:00
Mark Baker 17af13281b
Extract a few more Distribution functions from Statistical (#1975)
* Extract a few more Distribution functions from Statistical; this time EXPONDIST() and HYPGEOMDIST()

* Extract the F Distribution (although only F.DIST() is implemented so far

* Updae docblocks

* PHPCS
2021-03-31 21:45:06 +02:00
Mark Baker 029f345987
Extract Binomial Distribution functions from Statistical (#1974)
* Extract Binomial Distribution functions from Statistical
Replace the old MS algorithm for CRITBINOM() (which has now been replaced with te BINOM.INV() function) with a brute force approach - I'll look to refine it later. The MS algorithm is no longer documented, and the implementation produced erroneous results anyway

* Exract the NEGBINOMDIST() function as well; still need to add a cumulative flag to support the additional argument for the newer NEGBINOM.DIST() function
* Rationalise validation of probability arguments
2021-03-30 22:49:10 +02:00
Mark Baker e68978f1c7
Chi squared inverse left tailed (#1964)
* Implementation of the CHISQ.INV() method for ChiSquared distribution left-tail
2021-03-28 19:12:45 +02:00
Mark Baker e2ff14fe89
Implemented the CHISQ.DIST() Statistical function. (#1961)
* Implementation of the CHISQ.DIST() statistical function for left tail distribution
2021-03-28 16:13:00 +02:00
Mark Baker 67fec4e3fc
Implementation of the CHITEST() statistical function (#1960)
* Implementation of the CHITEST() statistical function

* A couple of additional edge case tests (rows = 1, columns = 1)
2021-03-27 22:04:05 +01:00
Mark Baker a34dd71cce
Difference in variance calculations between Excel/Gnumeric and Open/LibreOffice (#1959)
* Difference in variance calculations between Excel/Gnumeric and Open/LibreOffice
* Simplify STDEV() function logic by remembering that STDEV() is simply the square root of VAR(), so we can simply use the VAR() calculaion rather than duplicating the basic logic... and also allow for the differences between Excel/Gnumeric and Open/LibreOffice
2021-03-27 18:31:24 +01:00
Mark Baker ec2531411d
Start implementing Newton-Raphson for the inverse of Statistical Distributions (#1958)
* Start implementing Newton-Raphson for the inverse of Statistical Distributions, starting with the two-tailed Student-T
* Additional unit tests and validations
* Use the new Newton Raphson class for calculating the Inverse of ChiSquared
* Extract Weibull distribution, and provide unit tests
2021-03-27 13:29:58 +01:00
Mark Baker c699d144e2
Extract ACCRINT() and ACCRINTM() Financial functions into their own class (#1956)
* Extract ACCRINT() and ACCRINTM() Financial functions into their own class
Implement additional validations, with additional unit tests
Add support for the new calculation method argument for ACCRINT()
* Additional tests for Amortization functions
2021-03-26 22:49:16 +01:00
oleibman 9239b3deca
Continue MathTrig Breakup - Problem Children (#1954)
Continuing the process of breaking MathTrip.php up into smaller classes. This round takes care of all functions which might be an impediment to installing due to either uncovered code or "complexity":
- BASE
- FACT
- LCM
- MDETERM, MINVERSE, MMULT
- MULTINOMIAL
- PRODUCT
- QUOTIENT
- SERIESSUM
- SUM
- SUMPRODUCT

MathTrig and the members in directory MathTrig are now 100% covered. Many tests have been added, and some edge-case bugs are corrected. Some cases where PhpSpreadsheet had rejected numeric values stored as strings have been changed to accept them whenever Excel does; there had been no tests for that condition.

Boolean arguments are now accepted as arguments wherever Excel accpets them. Taking a cue from what has been done in Engineering, the parameter validation now happens in a routine which issues Exceptions for invalid values; this simplifies the code in the functions themselves. Thank you for doing that; I did not foresee how useful that was when I first looked at it.

Consistent with earlier changes of this nature, the versions in the MathTrig class remain, with a doc block indicating deprecation, and a stub call to the new routines.

All tests except for MINVERSE and MMULT are now handled in the context of a spreadsheet rather than a direct call to the calculation function which implements it. PhpSpreadsheet would need to handle dynamic arrays in order to test MINVERSE and MMULT in a spreadsheet context. Implementing that looks like it might be *very* challenging. It is not something I plan to look at, at least not in the near future.

One parsing problem turned up in the test conversion. It is in one of the SUMIF tests. It takes me to an area in Calculation where the comment says "I don't even want to know what you did to get here". It did not show up in the previous incarnation because, by using a direct call, the previous test managed to bypass the parsing. I have confirmed that this problem shows up in earlier releases of PhpSpreadsheet, so the changes in this PR did not cause it - they merely exposed it. I have left the test intact, but marked it "incomplete" for documentation purposes. I have not been able to get a handle on what's going wrong yet. I will probably open an issue on it if I can't resolve it soon. However, the test in question isn't a "real world" issue, and the error wasn't caused by this change, so I see no reason to delay this pending a resolution of the problem.

SUM had an idiosyncratic moment of its own. It had been ignoring non-numeric values, but Excel returns VALUE in that situation. So I changed it and wrote some new tests, which worked, but ... SUMIF uses several levels of indirection to get to SUM, and SUMIF *does* ignore non-numeric values, so a SUMIF test broke. SUM is a really simple function; the most practical approach seemed to be to clone it, with the string-accepting version being used by the Legacy version (which is called by SUMIF), and the non-string-accepting version being used in the Calculation Function table. That seems far easier and more practical than, for instance, adding a boolean parameter to the variable parameter list. As a follow-up, I will change SUMIF to explicitly call the appropriate new version, but I did not want to add that to this already large change.

SUM again - although it was fully covered beforehand, there was not a specific test member for it. There is now.

FACT had been coded to fail Gnumeric requests where the numeric argument has a decimal portion. However, Gnumeric does accept such an argument, and, unlike Excel and ODS, does not truncate it, but returns the result of a Gamma function call instead. This has been corrected.

When LCM included arguments which contained both 0 and a negative number, it returned 0 or NUM, whichever it found first. It is changed to always return NUM in that circumstance, as Excel does.

QUOTIENT had been documented as taking a variadic list of arguments. In fact, it takes exactly 2 - numerator and denominator - and the docblock and signature is fixed, even in the deprecated version.

The SERIESSUM docbock and signature are more accurate, even in the deprecated version. It is changed to ignore nulls, as Excel does, rather than return VALUE, and is one of the routines which previously rejected numbers in string form.

SUBTOTAL tests had used mocking for some reason. These are replaced with normal tests. And SUBTOTAL had a big surprise in store. That part of it which deals with hidden cells cares only whether the row is hidden, and doesn't care about the column's visibility.

I struggled with whether it should be SubTotal or Subtotal. I think the latter is correct, so that's how I proceeded. I don't think there are likely to be any other capitalization controversies.
2021-03-26 17:35:30 +09:00
Mark Baker 07ad800755
New Bessel Algorithm, providing a higher degree of accuracy and precision (#1946)
* New Bessel Algorithm, providing a higher degree of precision (12 decimal places) and still matching/exceeding MS Excel's precision across the range of values
2021-03-24 13:29:54 +01:00
Mark Baker 1a7b9a446a
First phase of refactoring the Excel Text functions (#1945)
* Refactoring the Excel Text functions
* More unit tests for utf-8 handling, for edge cases, and for argument validations
2021-03-23 13:34:28 +01:00
oleibman 9beacd21be
Complete Breakup Of Calculation/DateTime Functions (#1937)
* Complete Breakup Of Calculation/DateTime Functions

In conjunction with parallel breakups happening in other areas of Calculation, this change breaks up all the DateTime functions into their own classes. All methods remaining in DateTime itself have a doc block deprecation notice, and consist only of stub code to call the replacement methods. Coverage of DateTime itself and all the replacement methods is 100%.

There is only one substantive change to the code (see next paragraph). Among the non-substantive changes, it now adopts the same parsing technique (throwing and catching exceptions) already in use in Engineering and MathTrig. Boolean parameters are allowed in lieu of numbers when Excel allows them. Most of the code changes involve refactoring due to the need to avoid Scrutinizer "complexity" failures in what it will consider to be new methods.

Issue #1936 was opened just as I was staging this. It is now fixed. One existing WORKDAY test was wrong (noted in a comment in the test data file), and a bunch of new tests are added.

I found it confusing to use DateTime as a node of the the class name since most of the methods invoke native DateTime methods. So, everything is moved to directory DateTimeExcel, and that is what is used in the class names.

There are several follow-up activities that I am planning to undertake if this PR is merged.

- ODS supports dates well before 1900. There are exactly 2 assertions for this functionality. More are needed (and some functions might have to change to accept this).
- WEEKDAY has some poorly documented extra options for "style" which are not yet implemented.
- Most tests have been changed to use a formula as entered on a spreadsheet rather than a direct call to the method which implements the formula. There are 3 exceptions at this time. WORKDAY and NETWORKDAYS, which include arrays as part of their parameters, are more complicated than most. YEARFRAC was just too large to deal with now.
- There are direct calls to the now-deprecated methods in both source code and tests, mostly in Financial code, but possibly in others as well. These need to be changed.
- Some constants, none "officially" documented, remain in the original class. These should be either deleted or marked deprecated. I wasn't sure if deprecation was even possible (or desirable), and did not want that to be something which would cause Scrutinizer to fail the change.

* Deprecate Now-unused Constants, Fix Yearfrac bug, Change 3 Tests

Add new DateTime/Constants class, initially populated with constants used in Weeknum.

MS has another inconsistency with how it handles null cells in Yearfrac. Change PhpSpreadsheet to behave compatibly with this bug.

I have modified YearFrac, WorkDay, and NetworkDays tests to be more to my liking. Many tests added to YearFrac because of the bug above. Only minor modifications to the existing tests for the others.
2021-03-21 09:12:05 +01:00
Mark Baker d346318c2b
Start work on breaking down some of the Financial Excel functions (#1941)
* Start work on breaking down some of the Financial Excel functions
* Unhappy path unit tests for Treasury Bill functions
* Codebase for Treasury Bills includes logic for a different days between settlement and maturity calculation for OpenOffice; but Open/Libre Office now uses the Excel days calculation, so this discrepancy between packages is no longer required
* We've already converted the Settlement and Maturity dates to Excel timestamps, so there's no need to try doing it again when calculating the days between Settlement and Maturity
* Add Unit Tests for the Days per Year helper function
* Extract Interest Rate functions - EFFECT() and NOMINAL() - with additional validation, and unhappy path unit tests
* First pass at extracting the Coupon Excel functions
* Simplify the validation methods
* Extended unit tests to cover all combinations of frequency and basis, including leap years
Fix for COUPDAYSNC() when basis is US 360 and settlement date is the last day of the month
* Ensure that all Financial function code uses the new Helpers class for Days Per Year
2021-03-20 18:40:53 +01:00
Mark Baker 4cd6c7806e
Initial unit tests for Document Properties (#1932)
* Initial unit tests for Document Properties
* Typehinting in the document properties class
2021-03-17 18:36:13 +01:00
Mark Baker 09022256f4
Resolve Deprecated setMethods() call when Mocking for tests (#1925)
Resolve Deprecated `setMethods()` calls when Mocking for tests, using `onlyMethods()` and `addMethods()` instead
2021-03-15 14:50:05 +01:00
Mark Baker ae2468426f
jpgraph seems to be finally dying with PHP. (#1926)
* jpgraph seems to be finally dying with PHP. Until we have a valid alternative, disabling this run for PHP because it errors

https://github.com/HuasoFoundries/jpgraph looks like a natural successor, but it isn't BC so it will require some work to integrate
2021-03-15 14:14:44 +01:00
oleibman 30c880b5e6
Bitwise Functions and 32-bit (#1900)
* Bitwise Functions and 32-bit

When running the test suite with 32-bit PHP, a failure was reported in BITLSHIFT.
In fact, all of the following are vulnerable to problems, and didn't report
any failures only because of a scarcity of tests:
- BITAND
- BITOR
- BITXOR
- BITRSHIFT
- BITLSHIFT

Those last 2 can be resolved fairly easily by using multiplication by a power of 2
rather than shifting. The first 3 are a tougher nut to crack, and I will continue
to think how they might best be approached. For now, I have added skippable tests
for each of them, which at least documents the problem.

Aside from adding many new tests, some bugs were correctd:
- The function list in Calculation.php pointed BITXOR to BITOR.
- All 5 functions allow null/false/true parameters.
- BIT*SHIFT shift amount must be numeric, can be negative, allows decimal portion
(which is truncated to integer), and has an absolute value limit of 53.
- Because BITRSHIFT allows negative shift amount, its result can overflow
(in which case return NAN).
- All 5 functions disallow negative parameters (except ...SHIFT second parameter).
This was coded, but the code had been thwarted by an earlier is_int test.

* Full Support for AND/OR/XOR on 32-bit

Previous version did not support operands 2**32 through 2**48.
2021-03-14 20:05:31 +01:00
oleibman d99a4a3fac
Improve Coverage of BIN2DEC etc. (#1902)
* Improve Coverage of BIN2DEC etc.

The following functions have some special handling
depending on the Calculation mode:
- BIN2DEC
- BIN2HEX
- BIN2OCT
- DEC2BIN
- DEC2HEX
- DEC2OCT
- HEX2BIN
- HEX2DEC
- HEX2OCT
- OCT2BIN
- OCT2DEC
- OCT2HEX

Ods accepts boolean for its numeric argument.
This had already been coded, but there were no tests for it.

Gnumeric allows the use of non-integer argument where Excel/Ods do not.
The existing code allowed this for certain functions but not for others.
Gnumeric consistently allows it, so there is no need for parameter
gnumericCheck in convertBase::ValidateValue.
Again, there were no tests for this.

There were some minor changes needed:
- In functions where you are allowed to specify the numnber of "places" in the
result, there is an upper bound of 10 which had not been enforced.
- Negative values were not handled correctly in some cases.
- There was at least one (avoidable) error on a 32-bit system.
- Some upper and lower bounds were not being enforced. In addition to enforcing
those, the bounds are now defined as class constants in ConvertDecimal.

Many tests have been added, so that Engineering is now almost 100% covered.
The exception is some BESSEL code. There have been some recent changes to
BESSEL which are not yet part of my fork, so I could not address those now.
However, I freely admit that, when I looked at the uncovered portion, it seemed
like it might be a difficult task, so I probably wouldn't have tackled it anyhow.
In particular, the uncovered code seemed to deal with very large numbers,
and, although PhpSpreadsheet and Excel both give very large results for these
conditions, their answers are not particularly close to each other. I think
we're dealing with resuts approaching infinity. More study is needed.
2021-03-14 20:04:50 +01:00
oleibman 7e071e8abc
Coverage for Helper/Samples (#1920)
* Coverage for Helper/Samples

I was perplexed by the fact that Helper/Samples seemed to be entirely uncovered when running the test suite, since I know all the samples are run as part of the test. I think that what must be happening is that the Helper code is invoked mostly as part of a Data Provider (and therefore not counted), not as part of the test proper (which would count). So, this change adds a small number of tests which result in Samples being 100% covered.

Covering one statement was tricky - simulating the inability to create a test directory. Mocking, a technique I have not used before, solves this problem admirably.

* Suggestions From Mark Baker

Tests changed from assertEquals to assertSame.

Added @covers annotation to test class.

Validate parameter for method being mocked.
2021-03-14 20:04:07 +01:00
Mark Baker ed62526aca
First step extracting INDIRECT() and OFFSET() to their own classes (#1921)
* First step extracting INDIRECT() and OFFSET() to their own classes
* Start building unit tests for OFFSET() and INDEX()
* Named ranges should be handled by the Calculation Engine, not by the implementation of the Excel INDIRECT() function
* When calling the calculation engine to get the range of cells to return, INDIRECT() and OFFSET() should use the instance of the calculation engine for the current workbook to benefit from cached results in that range

There's a couple of minor bugfixes in here; but it's basically just refactoring of the INDIRECT() and OFFSET() Excel functions into their own classes - still needs a lot of work on unit testing; and there's a lot more that could be improved in the code itself (including handling of the a1 flag for R1C1 format in INDIRECT()
2021-03-14 19:58:10 +01:00
Vivek Kumar 51abdf0b8f Refactor xlsx writer
* Move file handler creation and file addition to the end
2021-03-14 22:20:11 +05:30
Vivek Kumar 5686453bcc Add test case for excel with media 2021-03-14 20:48:10 +05:30
oleibman 0ce8509a8c
Continue MathTrig Breakup - Trig Functions (#1905)
* Continue MathTrig Breakup - Trig Functions

Continuing the process of breaking MathTrip.php up into smaller classes.
This round takes care of the trig and hyperbolic functions, plus a few others.
- COS, COSH, ACOS, ACOSH
- COT, COTH, ACOT, ACOTH
- CSC, CSCH
- SEC, SECH
- SIN, SINH, ASIN, ASINH
- TAN, TANH, ATAN, ATANH, ATAN2
- EVEN
- ODD
- SIGN

There are no bug fixes in this PR, except that boolean arguments are now
accepted for all these functions, as they are for Excel.
Taking a cue from what has been done in Engineering, the parameter validation
now happens in a routine which issues Exceptions for invalid values;
this simplifies the code in the functions themselves.

Consistent with earlier changes of this nature, the versions in the
MathTrig class remain, with a doc block indicating deprecation,
and a stub call to the new routines.

I think several more iterations will be needed to break up MathTrig completely.
2021-03-13 12:06:30 +01:00
Mark Baker 2259de578b
Lookup ref further tests and examples (#1918)
* Extract LookupRef\INDEX() into index() method of LookupRef\Matrix class
Additional tests
* Bugfix for returning a column using INDEX()
* Some improvements to ROW() and COLUMN()
* Simplify some of the INDEX() logic, eliminating redundant code
2021-03-11 22:34:47 +01:00
Mark Baker 499ce61cf7
Unhappy path tests for FORMULATEXT() Function (#1915)
* Unhappy path tests
2021-03-10 22:38:41 +01:00
oleibman 13b62becdd
Fix for Issue #1887 - Lose Track of Selected Cells After Save (#1908)
* Fix for Issue #1887 - Lose Track of Selected Cells After Save

Issue #1887 reports that selected cells are lost after saving Xlsx. Testing indicates that this applies to the object in memory, though not to the saved spreadsheet.

Xlsx writer tries to save calculated values for cells which contain formulas. Calculation::_calculateFormulaValue issues a getStyle call merely to retrieve the quotePrefix property, which, if set, indicates that the cell does not contain a formula even though it looks like one. A side-effect of calls to getStyle is that selectedCell is updated. That is clearly accidental, and highly undesirable, in this case. Code is changed to save selectedCell before getStyle call and restore it afterwards.

The problem was reported only for Xlsx save. To be on the safe side, test is made for output formats of Xlsx, Xls, Ods, Html (which basically includes Pdf), and Csv. For all of those, the object in memory is tested after the save. For Xlsx and Xls, the saved file is also tested. It does not make sense to test the saved file for Csv and Html. It does make sense to test it for Ods, but the necessary support is not yet present in either the Ods Reader or Ods Writer - a project for another day.

* Move Logic Out of Calculation, Add Support for Ods ActiveSheet and SelectedCells

Mark Baker thought logic belonged in Worksheet, not Calculation.
I couldn't get it to work in Worksheet, but doing it in Cell works,
and that has already been used to preserve ActiveSheet over call to
getCalculatedValue, so this just extends that idea to SelectedCells.

Original tests could not completely support Ods because of a lack of support
for ActiveSheet and SelectedCells in Ods Reader and Writer.
There's a lot missing in Ods support, but a journey of 1000 miles ...
Those two particular concepts are now supported for Ods.
2021-03-10 21:23:08 +01:00
Mark Baker 70f372d88c
Start refactoring the Lookup and Reference functions (#1912)
* Start refactoring the Lookup and Reference functions
 - COLUMN(), COLUMNS(), ROW() and ROWS()
 - LOOKUP(), VLOOKUP() and HLOOKUP()
 - Refactor TRANSPOSE() and ADDRESS() functions into their own classes

* Additional unit tests
 - LOOKUP()
 - TRANSPOSE()
 - ADDRESS()
2021-03-10 21:18:33 +01:00
Mark Baker c4ed0ee7b0
Minor scrutinizer improvements (#1906)
* Minor scrutinizer improvements
* Minor typing improvements
2021-03-07 14:22:03 +01:00
Mark Baker 2d8c8c8ecf
Trend unit tests (#1899)
- Move TREND() functions into the Statistical Trends class
- Unit tests for TREND()
- Create Confidence class for Statistical Confidence functions
2021-03-06 22:50:19 +01:00
Mark Baker a79a4ddbab
Statistical refactoring - Confidence() and Trend() (#1898)
- Move TREND() functions into the Statistical Trends class
- Unit tests for TREND()
- Create Confidence class for Statistical Confidence functions, and the CONFIDENCE() method
2021-03-04 21:45:56 +01:00
Mark Baker d2a83b404a
Statistical trends additional functions and unit tests (#1896)
* PEARSON() and CORREL() are identical functions
* Unit tests for GROWTH() function
* Move GROWTH() function into Statistical\Trends Class
2021-03-03 23:18:56 +01:00
Patrick Brouwers 000e6088c9
Reverted Scrutinzer fix in Xslx Reader listWorksheetInfo (#1895) 2021-03-03 21:34:45 +01:00
oleibman 04e7c30758
Fix Two 32-bit Timestamp Problems, and Minor getFormattedValue Bug (#1891)
I ran the test suite using 32-bit PHP. There were 2 places where changes
were needed due to 32-bit timestamps.

Reader\\Xml.php was using strtotime as an intermediate step in converting
a string timestamp to an Excel timestamp. The XML file type stores pure timestamps
(i.e. no date portion) as, e.g., 1899-12-31T02:30:00.000, and that value
causes an error using strtotime on a 32-bit system. However, it is sufficient
to use that value in a DateTime constructor, and that will work for 32- and 64-bit.

There was no test for that particular cell, so I added one to the XML read test.
And that's when I discovered the getFormattedValue bug. The cell's format
is `hh":"mm":"ss`. The quotes around the colons are disrupting the formatting.
PhpSpreadsheet formats the cell by converting the Excel format
to a Php Date format, in this case `H\:m\:s`.
That's a problem,
since Excel thinks 'm' means *minutes*, but PHP thinks it means *months*.
This is not a problem when the colon is not quoted; there are ample tests for that.
I added my best guess as to how to recognize this situation,
changing `\:m` to `:i`. The XML read test
now succeeds, and no other tests were broken by this change.

Test Shared\\DateTest had one test where the expected result of converting to a
Unix timestamp exceeds 2**32. Since a Unix timestamp is strictly an int,
that test fails on a 32-bit system. In the discussion regarding recently merged
PR #1870, it was felt that the user base might still be using the functions
that convert to and from a timestamp. So, we should not drop this test, but,
since it cannot succeed on a 32-bit system, I changed it to be skipped
whenever the expected result exceeded PHP_INT_MAX. There are 3 "toTimestamp"
functions within that test. Only one of these had been affected, but I thought
it was a good idea to add additional tests to the others to demonstrate this
condition.

In the course of testing, I also discovered some 32-bit problems with
bitwise and base-conversion functions. I am preparing separate PRs to
deal with those.
2021-03-03 10:52:11 +01:00
Mark Baker 42e8680fc0
Statistics more unit tests (#1889)
* Additional unit tests
2021-03-02 18:01:39 +01:00
Mark Baker 2eaf9b53aa
Start splitting some of the basic Statistical functions out into separate classes (#1888)
* Start splitting some of the basic Statistical functions out into separate classes containing just a few similar functions

* Splitting some of the basic Statistical functions out into separate classes containing just a few similar functions - MAX(), MAXA(), MIN() and MINA()

* Splitting some more of the basic Statistical functions out into separate classes containing just a few similar functions - StandardDeviations and Variances
2021-03-02 09:07:28 +01:00
Mark Baker 1d6f36d8df
Initial Formula Translation tests (#1886)
* Initial Formula Translation tests
2021-02-28 13:18:51 +01:00
oleibman 80a20fc991
100% Coverage for Calculation/DateTime (#1870)
* 100% Coverage for Calculation/DateTime

The code in DateTime is now completely covered.
Along the way, some errors were discovered and corrected.
- The tests which have had to be changed at the start of every year are
replaced by more robust equivalents which do not require annual changes.
- Several places in the code where Gnumeric and OpenOffice were thought to differ
from Excel do not appear to have had any justification.
I have left a comment where such code has been removed.
- Use DateTime when possible rather than date, time, or strftime functions to avoid
potential Y2038 problems.
- Some impossible code has been removed, replaced by an explanatory comment.
- NETWORKDAYS had a bug when the start date was Sunday. There had been no tests
of this condition.
- Some functions allow boolean and null arguments where a number is expected.
This is more complicated than the equivalent situations in MathTrig because
the initial date for these calculations can be Day 1 rather than Day 0.
- More testing for dates from 1900-01-01 through the fictitious
everywhere-but-Excel 1900-01-29.
    - This showed that there is an additional Excel bug - Excel evaluates
WEEKNUM(emptycell) as 0, which is not a valid result for
WEEKNUM without a second argument.
PhpSpreadsheet now duplicates this bug.
    - There is a similar and even worse bug for 1904-01-01 in 1904 calculations.
Weeknum returns 0 for this,
but returns the correct value for arguments of 0 or null.
    - DATEVALUE should accept 1900-02-29 (sigh) and relatives.
PhpSpreadsheet now duplicates this bug.
- Testing bootstrap sets default timezone. This appears to be a relic from
the releases of PHP where the unwise decision, subsequenly reversed,
was made to issue messages for
"no default timezone is set" rather than just use a sensible default.
This was a disruptive setting for some of the tests I added.
There is only one test in the entire suite which is default-timezone-dependent.
Setting and resetting of default timezone is moved to that test
(Reader/ODS/ODSTest), and out of bootstrap.
- There had been no testing of NOW() function.
- DATEVALUE test had no tests for 1904 calendar and needs some.
- DATE test changed 1900/1904 calendar in use without restoring it.
- WEEKDAY test had no tests for 1904 calendar and needs some.
    - Which revealed a bug in Shared/Date (excelToDateTimeObject was not
recognizing 1904-01-01 as valid when 1904 calendar is in use).
    - And an additional bug in that legal 1904-calendar values in the 0.0-1.0
range yielded the same "wrong" answers as 1900-calendar (see "One note" below).
Also the comment for one of the calendar-1904 tests was wrong in attempting
to identify what time of day the fraction represented.

I had wanted to break this up into a set of smaller modules, a process already
started for Engineering and MathTrig.
However the number of source code changes was sufficient that I wanted
a clean delta for this request.
If it is merged, I will work on breaking it up afterwards.

One note - Shared/Date/excelToDateTimeObject, when calendar-1900 is in use,
returns an unexpected result if its argument is between 0 and 1,
which is nominally invalid for that calendar.
It uses a base-1970 calendar in that instance. That check is not justifiable
for calendar-1904, where values in that range are legal,
so I made the check specific to calendar-1900,
and adjusted 3 1904 unit test results accordingly. However, I have to admit that
I don't understand why that check should be made even for calendar-1900.
It certainly doesn't match anything that Excel does.
I would recommend scrapping that code altogether.
If agreed, I would do this as part of the break-up into smaller modules.

Another note -
more controversially, it is clear that PhpSpreadsheet needs to support
the Excel and PHP date formats. Although it requires further study,
I am not convinced that it needs to support Unix timestamp format.
Since that is a potential source of Y2038 problems on 32-bit systems,
I would like to open a PR to deprecate the use of that format.
Please let me know if you are aware of a valid reason to continue to support it.
2021-02-27 20:43:22 +01:00
Mark Baker 08673b5820
Initial experiments using the new Database query logic with Conditional Statistical Functions (#1880)
- Refactoring of the Statistical Conditional functions (`AVERAGEIF()`, `AVERAGEIFS()`, `COUNTIF()`, `COUNTIFS()`, `MAXIFS()` and `MINIFS()` to use the new Database functions codebase.
- Extended unit testing
- Fix handling for null values
- Fixes to wildcard text searches

There's still scope for further improvements to memory usage and performance; but for now the code is stable with all unit tests passing
2021-02-27 18:26:12 +01:00
oleibman cb23cca3ec
Avoid Duplicate Titles When Reading Multiple HTML Files (#1829)
This issue arose while researching issue #1823. The issue was not a bug;
it just required clarification to the author of how to use the software.
But, while researching, I discovered that loading html into 2
sheets of a spreadsheet has a problem if the html title tag is the same
for the 2 sheets. PhpSpreadsheet would be able to save the resulting file,
but Excel would not be able to read it properly because of the duplicate title.
The worksheet setTitle method allows for disambiguation is such a circumstance.
The html reader passed a parameter indicating "don't disambiguate", but I can't
see any harm in changing that to "disambiguate". An extremely simple fix,
with tests to back it up.
2021-02-27 15:10:04 +01:00
Mark Baker 25f7dcb9fd
Enable support for wildcard text searches in Excel Database functions (#1876)
* Enable support for wildcard text searches in Excel Database functions
2021-02-23 19:26:29 +01:00
Mark Baker 40a6dee0a4
Enable support for dates and percentages in Excel Database functions (#1875)
* Enable support for dates and percentages in Excel Database functions, and CountIf/AverageIf/etc
* Enable support for booleans in Excel Database functions
2021-02-22 20:40:40 +01:00
Mark Baker 3764f30354
Refactor the Excel Database functions; and rewrite the query building (#1871)
* Refactor the Excel Database functions; and rewrite the query building to fix a bug with complex multi-criteria queries that involve both AND and OR conditions
* Fix handling for empty cells and NULL values in searches
* Expand unit tests; and add TODOs for dates, percentages, and wildcard text comparisons
2021-02-22 12:46:57 +01:00
Mark Baker 1318b90330
Bugfix #1858; Apply stricter scoping rules to named range/cell access (#1866)
* Apply stricter scoping rules to named range/cell access via Worksheet object
* Additional unit tests
2021-02-19 22:03:50 +01:00